Q: How to center oversize font inside Text's bounding box? I'm trying to create a simple Floating Action Bar button with a plus icon in it, and have had trouble true-centering the "plus" in some edge cases.  I was just using '\uFF0B' in a <Text>, but tried to switch to react-native-vector-icons, only to discover that they too were using a font and not an image to back the <Icon> instances, and that my problems seem to persist.
Things are fine on most screens and devices but in some cases users are reporting the plus icon is not perfectly centered.  I have a hypothesis that it may involve users' accessibility options increasing the font size in the app beyond size of the parent View.  At any rate I can reproduce something like the screenshots folks are sharing with me by setting the fontSize greater than the lineHeight.  Assuming that is the issue -
How do you center a single glyph within the view area of a <Text> (or <Icon>, since that derives from <Text>), even when the fontSize may be much larger than the <Text>'s lineHeight or even overall height?
In the below example, the "+" font size is exactly double the line-height, so the plus is centered smack dab on the upper-right corner of the view area, as though it were expecting to be in a box that was 112dp x 112dp; but I want it centered dead-center of the 56dp x 56dp box instead, with the arms of the plus cropped.  No combination of style attributes seems to effect it, but rather just controls where the <Icon> positions within its parent.
Currently:
Normally:

For oversized font:

Code:
<View style={s.fabStyle}>
  <TouchableOpacity onPress={()=>{this.onPlus()}}>
    <Icon name="plus" style={s.fabText} />
  </TouchableOpacity>
</View>

...
const s = StyleSheet.create({
  fabStyle: {
    position: 'absolute',
    right: 16,
    bottom: 16,
    borderRadius: 28,
    width: 56,
    height: 56,
    backgroundColor: styleConstants.color.primary,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    textAlign: 'center',
  },
  fabText: {
    position: 'relative',
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    fontSize: 112,
    color: '#fff',
    textAlign: 'center',
    lineHeight: 56,
    width: 56,
    height: 56,
  },
});

A: This isn't an answer to the question itself, which still stands, but an answer to the underlying issue, in case somebody arrives here by Google search with a similar issue. In my case it was indeed the case that accessibility settings were causing font to be bigger than it was designed to be, thus triggering the above scenario.  While I still don't know how to center the text adequately in this case, in my case the issue could be circumvented by making sure allowFontScaling=false for relevant Views holding text.


Q: How to redirect to previous page? or How to get title from ForeignKey? PART 1
I have some problems with redirecting on same page after click.
or example i was at /memes and after click i am at page /add_to_cart
OR PART 2
I have another solution for my problem
PART 1
in view i have
def add_to_cart(request, **kwargs):
    return redirect(reverse('meme:meme_list'))

and my html looks like this
a href="{% url 'shoppingcart:add_to_cart' post.id %}" class="col-2">

but if i am at the /videos and whant to add to cart i will be redirected at /meme. i ve found request.path_info but it only shows current path  (add_to_cart/1)
PART 2
I have category in my models for product
class product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT)

class Category(models.Model):
    title = models.CharField(max_length=32)

so i can just make my prev path by '/'+ category title and i can't do it because
'ForwardManyToOneDescriptor' object has no attribute 'title'

how to get title from my category?

A: request.META.get('HTTP_REFERER','/')

this how you get prev url page


Q: Php script not showing errors but only redirects to homepage I am making e-commerce site and add to basket script not doing anything I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
  header("Location: " . $config_basedir);
} else {
  if($_POST['submit'])
  {
    if($_SESSION['SESS_ORDERNUM'])
    {
      $itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
                 . $_SESSION['SESS_ORDERNUM'] . ", "
                 . $_GET['id'] . ", "
                 . $_POST['amountBox'] . ")";
      mysqli_query($itemsql);
    } else {
      if($_SESSION['SESS_LOGGEDIN'])
      {
        $sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
               . $_SESSION['SESS_USERID'] . ", 1, NOW())";
        mysqli_query($sql);
        session_register("SESS_ORDERNUM");
        $_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
        $itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
                   . $_SESSION['SESS_ORDERNUM']
                   . ", " . $_GET['id'] . ", "
                   . $_POST['amountBox'] . ")";
        mysqli_query($itemsql);
      } else {
        $sql = "INSERT INTO orders(registered, date, session) VALUES("
               . "0, NOW(), '" . session_id() . "')";
        mysqli_query($sql);
        session_register("SESS_ORDERNUM");
        $_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
        $itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
                   . $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
                   . $_POST['amountBox'] . ")";
        mysqli_query($itemsql);
      }
    }
    $totalprice = $prodrow['price'] * $_POST['amountBox'] ;
    $updsql = "UPDATE orders SET total = total + "
              . $totalprice . " WHERE id = "
              . $_SESSION['SESS_ORDERNUM'] . ";";
    mysqli_query($updres);
    header("Location: " . $config_basedir . "showcart.php");
  } else {
    require("header.php");
    echo "<form action='addtobasket.php?id="
         . $_GET['id'] . "' method='POST'>";
    echo "
";
    echo "
";
    if(empty($prodrow['image']))
    {
      echo "	";
    } else {
      echo "	";
    }
      echo "" . $prodrow['name'] . "	";
      echo "Select Quantity <select name='amountBox'>";
      for($i=1;$i<=100;$i++)
      {
        echo "<option>" . $i . "</option>";
      }
      echo "</select>	";
      echo "£"
           . sprintf('%.2f', $prodrow['price'])
           . "	";
      echo "<input type='submit' name='submit' value='Add to basket'>	";
      echo "
";
      echo "
";
      echo "</form>";
   }
}
require("footer.php");

?>

A: In this section
$updsql = "UPDATE orders SET total = total + "
          . $totalprice . " WHERE id = "
          . $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);

You have a variable named $updsql but on the query, it is named $updres.


Q: Should my equals/hashCode method examine more than the object IDs? In my application, I have model classes of the following form:
class Book
{
    private int ID;
    private String title;

    //other code
}

Now my question is two part:

*

*Is the following a good implementation of the equals() method?
public boolean equals(Object o)
{
    if(o == null)
    {
        return false;
    }

    if(!(o instanceof Book))
    {
        return false;
    }

    Book other = (Book)o;

    if(o.getID() == ID)
    {
        return true;
    }
    return false;
}

I know that equals() implementation largely depends on my
application business logic. But If two Books have the same ID then
they ideally must be the same Book. Hence I am confused as to
whether I should check for equality for other value fields as well
[title, price etc].

*Is this a good implementation of the hashCode() method:
public int hashCode()
{
    return ID;
}

My thinking is that different books will have different IDs and if
two books have the same ID they they are equal. Hence the above
implementation will ensure a good distribution of the hashcode in
context of my application.

A: Just wanted to add some coment over the previous answers. The contract of equals mentions that it must be symmetric. This means that a.equals(b) iff b.equals(a).
That's the reason why instanceof is usually not used in equals (unless the class is final). Indeed, if some subclass of Book (ComicsBook for example) overrides equals to test that the other object is also an instance of ComicsBook, you'll be in a situation where a Book instance is equal to a ComicsBook instance, but a ComicsBook instance is not equal to a Book instance.
You should thus (except when the class is final or in some other rare cases) rather compare the classes of the two objects:
if (this.getClass() != o.getClass()) {
    return false;
}

BTW, that's what Eclipse does when it generates hashCode and equals methods.

A: Don't do this:
if(o.getID() == ID)

ID is an Integer object, not a primitive.  Comparing two different but equal Integer objects using == will return false.
Use this:
if(o.getID().equals(ID))

You'd also need to check for ID being null.
Other than that, your logic is fine - you're sticking with the contract that says two equal objects must have the same hashcode, and you've made the business logic decision as to what equality means -a decision that only you can make (there's no one correct answer).

A: If you use Hibernate then you have to consider some Hibernate related concerns.
Hibernate create Proxies for Lazy Loading.

*

*always use getter to access the properties of the other object (you already done that)

*even if it is correct to use if (!this.getClass().equals(o.getClass())) { return false;} in a normal Application it WILL fail for hibernate Proxy (and all other proxies). The reason is if one of the two is a proxy, there classes will never be equals. So the test if(!(o instanceof Book)){return false;} is what you need.

If you want to do it in the symmetric way than have a look at org.hibernate.proxy.HibernateProxyHelper.getClassWithoutInitializingProxy() with help of this class you can implement:
if (!HibernateProxyHelper.getClassWithoutInitializingProxy(this)
     .equals(HibernateProxyHelper.getClassWithoutInitializingProxy(o))) {
   return false;
}

*

*An other problem maybe is the ID -- when you assign the id not with the creation of an new object but later on while storing them, then you can run into trouble. Assume this scenario: You create a new Book with id 0, then put the Book in a HashSet (it will assigned to an bucket in the hashset depending on the hashcode), later on you store the Book in the Database and the id is set to lets say 1. But this changes the hashcode, and you will have problems to find the entity in the set again. -- If this is a problem or not for you, strongly depends on your application, architecture and how you use hibernate.

A: It is no good idea to compare the two Integers like
if(o.getID() == ID) ...

This tests for identity. What you want is a test for equality:
if(ID!=null && ID.equals(o.getID())) ...

A: Just a note: Your equals method
public boolean equals(Object o)
{
    if(o == null)
    {
        return false;
    }

    if(!(o instanceof Book))
    {
        return false;
    }

    Book other = (Book)o;

    if(other.getID() == ID)
    {
        return true;
    }
    return false;
}

can be (equivalently) shorter written like this:
public boolean equals(Object o) {
    return (o instanceof Book) &&
       ((Book)o).getID == ID;
}

Other than this, if your IDs are all different for different books (and same for same books), this is a good implementation.
(But note JB Nizet's remark: To make sure this stays symmetric, make equals (or the whole class) final.)

A: that depends !
i think this kind of implementation is ok, if you can handle the condition below,
you new two books, these two books have the same title, they are same book in fact, but you
don't save them into database, so these two books don't have ids yet, the equals will fall when you compare them


Q: Refresh window.rootViewController.view contents I am building an app in which I use MBProgressHUD library as an activity indicator. I attach the HUD to self.view.window.rootViewController.view . Everything works fine but when I rotate the device, the HUD (UIActivityIndicator) is overlapped by the other screen items and it looks as if HUD is in background of the view. Does any one has any idea how to deal with this issue? has any one used MBProgressHUB library and faced similar issues?
P.S I have to attach HUD to self.view.window.rootViewController.view  only.

A: You should remove your view. Add this code;
[self.view removeFromSuperview];


Q: dll for face recognition I started creating a face recognition application. But nothing works fine. Is any dll available for this so that I can decode the source and implement it ? Any reference or source will be greatly appreciated.

A: You can try with OpenCV. And this list may help you.


Q: Returning Specific Columns from Entitey Framework Query While Utilizing MVC I’m new to using both Entity Framework and MVC, but not new to programming.  I am working with a large table and I want to return selected columns of the query back to the view and list them.  The basic query is as follows:
public class EmployeeController : Controller
{
    private ADPEntities db = new ADPEntities();

    // GET: /Employee/
    public ActionResult Index()
    {
        var tblEmployeeADPs = db.tblEmployeeADPs
            .Where(p => p.Status == "Active")
            .Select(p => new UserViewModel.USerViewModelADP
            {
                Status = p.Status,
                FirstName = p.FirstName,
                LastName = p.LastName,
                SSN = p.SSN
            });

        return View(tblEmployeeADPs.ToList());
    }
}

I created a basic C# class to strongly type the results (i.e. UserViewModel) and I still get an error:

The model item passed into the dictionary is of type
  'System.Collections.Generic.List1[UserViewModel.USerViewModelADP]',
  but this dictionary requires a model item of type
  'System.Collections.Generic.IEnumerable1[DysonADPTest.Models.tblEmployeeADP]'.

when I execute the page.
I’m not sure what I’m missing, as I was sure that (cobbling what I’ve read) that this would be the answer.

A: Please try the following in your view:
@model IEnumerable<DysonADPTest.UserViewModel.USerViewModelADP>

Your problem lies in using the .Select() method which changes the type your controller action is returning from
IEnumerable<DysonADPTest.Models.tblEmployeeADP>

which your view is also expecting to something entirely different. For this to work, the type your controller action returns and your view uses should match. It's either not use the .Select() method in your controller action or change the type your view uses.

A: You are creating a list with a new object type (USerViewModelADP)
You can filter, but just keep the same type (an objects)
public ActionResult Index()
{
    var tblEmployeeADPs = db.tblEmployeeADPs
        .Where(p => p.Status == "Active")
        .Select(p => p)

    return View(tblEmployeeADPs.ToList());
}


Q: Multiple login in Shiro shiro multiple login
I have a web app which have 2 parts: front part and backend part. Both part need a login page for users.
Members need to use /signin to login front part.
Admins need to use /admin/signin to login backend part.
public ShiroFilterFactoryBean shiroFilter(WebSecurityManager securityManager){
    ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
    shiroFilter.setSecurityManager(securityManager);

    Map<String, Filter> filterMap = Maps.newLinkedHashMap();
    FormAuthenticationFilter adminAuthc = new FormAuthenticationFilter();
    adminAuthc.setLoginUrl("/admin/signin");
    adminAuthc.setSuccessUrl("/admin/course");
    filterMap.put("adminAuthc", adminAuthc);
    FormAuthenticationFilter authc = new FormAuthenticationFilter();
    adminAuthc.setLoginUrl("/signin");
    adminAuthc.setSuccessUrl("/");
    filterMap.put("authc", authc);
    shiroFilter.setFilters(filterMap);

    Map<String, String> filterChainDefinitionMap = Maps.newLinkedHashMap();
    filterChainDefinitionMap.put("/signout", "logout");
    filterChainDefinitionMap.put("/style/**", "anon");
    filterChainDefinitionMap.put("/javascript/**", "anon");
    filterChainDefinitionMap.put("/image/**", "anon");
    filterChainDefinitionMap.put("/flash/**", "anon");
    filterChainDefinitionMap.put("/favicon.ico", "anon");
    filterChainDefinitionMap.put("/captcha/**", "anon");
    filterChainDefinitionMap.put("/course", "anon");
    filterChainDefinitionMap.put("/course/**", "anon");
    filterChainDefinitionMap.put("/course/*/collect", "authc");
    filterChainDefinitionMap.put("/course/*/uncollect", "authc");
    filterChainDefinitionMap.put("/course/study/record", "authc");
    filterChainDefinitionMap.put("/**", "authc");
    filterChainDefinitionMap.put("/admin/**", "adminAuthc");
    shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);

    return shiroFilter;
}


Q: Mapping between Childs' List in Same Class The question looks easy but I am really can't get the trick same time I don't want to go through a work around.I have this XML file
<Master>
  <Parent1>
     <child1/>
     <child1/>
     <child1/>
  </Parent1>
  <Parent2>
     <child2/>
     <child2/>
     <child2/>
  </Parent2>
</Master>

I deserialize it in the current class structure
Class Master
{
  List<child1> Parent1;
  List<child2> Parent2;
}

Child2 is displayed on the UI whenever it changed shall change child1 had same ID as child2.The problem is that in child2 I have no access to Parent1 so how can go backward to change in child1.I need a good solution not a workaround.
Edit: Child1 and Child2 two different classes but there is certain mapping between their properties.

A: You are able to let each parent know about which children was added/removed.
Each parent will get the event and will handle it if it's a matching child (or relevant due to other logic).
Two public objects which are used for communication between parent and master:
public enum ChangeType { Added, Removed }

public delegate void ChildChangeEvent(Parent parent, Child child, ChangeType changeType);

The parent class has two main roles- raising an event if it has a child that was added/removed, and handling this event if raised by other parents and it's relevant for them.
class Parent
{
    public event ChildChangeEvent ChildChangeEvent;

    private List<Child> _children;

    public void Add(Child child)
    {
        _children.Add(child);

        ChildChangeEvent(this, child, ChangeType.Added);
    }

    public void Remove(Child child)
    {
        _children.Remove(child);

        ChildChangeEvent(this, child, ChangeType.Removed);
    }

    public void NotifyChange(Parent parent, Child child, ChangeType changeType)
    {
        //do where you want with this info.. change local id or whatever logic you need
    }
}

The Master class should notify all parents about the child added/removed
event that was raised by one of the parents:
class Master
{
    private List<Parent> _parents;

    public void AddParent(Parent parent)
    {
        _parents.Add(parent);
        parent.ChildChangeEvent += parent_ChildChangeEvent;
    }

    void parent_ChildChangeEvent(Parent parent, Child child, ChangeType changeType)
    {
        foreach (var notifyParent in _parents)
        {
            notifyParent.NotifyChange(parent, child, changeType);
        }
    }

}


Q: Controller not making associations in Rails because of wrong format I need to make new associations for Modification model if.save. Also these associations need to be same as related Entity model has. But i'm getting this error:

When assigning attributes, you must pass a hash as an argument.

ModificationController.rb
def create
    @modification = Modification.new(change_params)

    respond_to do |format|
      if @modification.save

        @modification.entity.boxes.each do |d|
          @modification.boxes.new(d)
        end

        flash[:success] = "Success"
        format.html { redirect_to @modification }
        format.json { render :show, status: :created, location: @modification }
      else
        format.html { render :new }
        format.json { render json: @modification.errors, status: :unprocessable_entity }
      end
    end
  end

More info:
Each Modification belongs_to Entity
Both Modifications and Entities has_many Boxes.

A: So you want to create a new box association using an existing Box.  We can grab the attributes of the existing box to create the new one.  However, an existing box will already have an id, so we need to exclude that from the attributes.
Following the above logic, the following should work:
def create
  @modification = Modification.new(change_params)

  respond_to do |format|
    if @modification.save

      @modification.entity.boxes.each do |d|
        @modification.boxes << d.dup
      end

      flash[:success] = "Success"
      format.html { redirect_to @modification }
      format.json { render :show, status: :created, location: @modification }
    else
      format.html { render :new }
      format.json { render json: @modification.errors, status: :unprocessable_entity }
    end
  end
end

A: When you declare a has_many association, the declaring class automatically gains 16 methods related to the association as the mention Guide Ruby On Rails Association Has-Many
  def create

    @modification = Modification.new(change_params)
    respond_to do |format|
      if @modification.save

        @modification.entity.boxes.each do |d|
          @modification.boxes << d # if d.present? use if condition there is nay validation in your model.
        end

        flash[:success] = "Success"
        format.html { redirect_to @modification }
        format.json { render :show, status: :created, location: @modification }
      else
        format.html { render :new }
        format.json { render json: @modification.errors, status: :unprocessable_entity }
      end
    end
  end

Hope this helo you !!!


Q: Z-fighting. Inaccurate coordinates of faces / shakes For sufficiently large approaching the surface of the sphere, which is a model of the Earth, I get inaccurate coordinates of vertices. Because of this, when moving the camera the shaking noticeable.
How to get rid of it? On the Internet to find solutions to invert zNear and zFar, but I have no idea how to do it in three.js

A: THREE.PerspectiveCamera has near and far parameters. These define the distance of the near and far clipping plane.
You have to choose clipping planes depending on your scene. For example if you have a large scene, and the near plane is very small, it can cause things you experienced.


Q: error to run function code in javascript has undefined A table made containing the edit information field
a problem to run code undifined code in function
please help me to fix this error
"info" id table in html
function submit ()
{
    var table = document.getElementById("info");
    var td1 = document.createElement("td")
    var td2 = document.createElement("td");
    var row = document.createElement("tr");

    td1.innerHTML = document.getElementById("p-name").value;
    td2.innerHTML = document.getElementById("p-id").value;

    row.appendChild(td1);
    row.appendChild(td2);
    table.children[0].appendChild(row);

create button in script
var bedit = document.createElement("BUTTON");
var bename = document.createTextNode("Edit");

bedit.appendChild(bename);
bedit.onclick = function () { edit_row(event) }

td6.appendChild(bedit);}

function code on click button in submit function
function edit_row()
{
    bedit.style.display = "none";
    bsave.style.display = "block";

    var input = document.createElement("INPUT");
    input.setAttribute("type", "text");

    var string = td1.textContent;

    td1.innerHTML = "";
    td1.appendChild(input);

    input.value = string;
}

A: Ok, try this. I added some comments.

function submit () {
var table = document.getElementById("info");
var td1 = document.createElement("td")
var td2 = document.createElement("td");

td1.innerHTML = document.getElementById("p-name").value;
td2.innerHTML = document.getElementById("p-id").value;

// create a table row
var row = document.createElement("tr");

row.appendChild(td1);
row.appendChild(td2);

// instead of your append
// table.children[0].appendChild(row);
// use this append
table.appendChild(row);

var bedit = document.createElement("BUTTON");
var bename = document.createTextNode("Edit");
bedit.appendChild(bename);
bedit.onclick = edit_row.bind(null, bedit, td1);

// createtd6 before because it is not known by your previous code
// I use this td2 instead of td6
td2.appendChild(bedit);
}

function edit_row(bedit, td1) {
bedit.style.display = "none";
// create bsave button before because it is not known by your previous code
// bsave.style.display = "block";
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
var string = td1.textContent;
td1.innerHTML = "";
td1.appendChild(input);
input.value = string;
}

submit();

<input id="p-name" type="text" value="name_value" />
<input id="p-id" type="text" value="id_value" />


Q: Setting a cookie from a previous request when using axios in a Lambda function I am using Axios in my NodeJs application to do HTTP requests.
I am logging in using a post request that does not require a cookie set in the header.
const instance = axios.create({ baseURL: 'https://some_url.com' , withCredentials: true});
const response = await instance.post('auth/login', data);

This returns a set-cookie in its header that I need to use in all subsequent API call. This is code I have tried for this.
const getResponse = await instance.get('/getStuff?$top=10', { withCredentials: true });

This always returns a "Not logged in error". I do not have access to the server, but I am assuming this is because my get request did not send the cookie in its header.
Running all of this in a lambda, not sure if that makes a difference.
Question: How do I get the cookie from my first post request and use it in my get request?

A: The withCredentials option is for the browser version of axios, and relies on browser for storing the cookies for your current site.
Since you are using it in Node, you will have to handle the storage yourself.
TL;DR
After the login request, save the cookie somewhere. Before sending other requests, make sure you include that cookie.
To read the cookie, check response.headers object, which should have a set-cookie header (which is all cookies really are - headers with a bit of special convention that has evolved into some sort of standard).
To include the cookie in your HTTP request, set a cookie header.

General example
You could also look for some "cookie-handling" libraries if you need something better than "save this one simple cookie I know I'll be getting".
// 1. Get your axios instance ready
function createAxios() {
    const axios = require('axios');
    return axios.create({withCredentials: true});
}
const axiosInstance = createAxios();

// 2. Make sure you save the cookie after login.
// I'm using an object so that the reference to the cookie is always the same.
const cookieJar = {
    myCookies: undefined,
};

async function login() {
    const response = await axiosInstance.post('http://localhost:3003/auth', {});
    cookieJar.myCookies = response.headers['set-cookie'];
}

// 3. Add the saved cookie to the request.
async function request() {
    // read the cookie and set it in the headers
    const response = await axiosInstance.get('http://localhost:3003',
        {
            headers: {
                cookie: cookieJar.myCookies,
            },
        });
    console.log(response.status);
}

login()
    .then(() => request());

You could also use axios.defaults to enforce the cookie on all requests once you get it:
async function login() {
    const response = await axios.post('http://localhost:3003/auth', {});
    axios.defaults.headers.cookie = response.headers['set-cookie']
}

async function request() {
    const response = await axios.get('http://localhost:3003');
}

As long as you can guarantee that you call login before request, you will be fine.
You can also explore other axios features, such as interceptors. This may help with keeping all "axios config"-related code in one place (instead of fiddling with defaults in your login function or tweaking cookies in both login and request).

Lambda
AWS Lambda can potentially spawn a new instance for every request it gets, so you might need to pay attention to some instance lifecycle details.
Your options are:

*

*Do Nothing: You don't care about sending a "login request" for every lambda run. It doesn't affect your response time much, and the other api doesn't mind you sending multiple login requests. Also, the other api has no problem with you having potentially multiple simultaneous cookies (e.g. if 10 lambda instances login at the same time).

*Cache within lambda instance: You have a single lambda instance that gets used every once in a while, but generally you don't have more than one instance running at any time. You only want to cache the cookie for performance reasons. If multiple lambda instances are running, they will each get a cookie. Beware the other api not allowing multiple logins.
If this is what you need, make sure you put the axios config into a separate module and export a configured instance. It will be cached between runs of that one lambda instance. This option goes well with interceptors usage.
const instance = axios.create({...});
instance.interceptors.response.use(() => {}); /* persist the cookie */
instance.interceptors.request.use(() => {}); /* set the cookie if you have one */
export default instance;

*Cache between lambda instances: This is slightly more complicated. You will want to cache the cookie externally. You could store it in a database (key-value store, relational, document-oriented - doesn't matter) or you could try using shared disk space (I believe lambda instances share some directories like /tmp, but not 100% sure).
You might have to handle the case where your lambda gets hit by multiple requests at the same time and they all think they don't have the cookie, so they all attempt to login at the same time. Basically, the usual distributed systems / caching problems.


Q: Elegant Reflection in Python? I have a small number of different Python classes (each standing for a different kind of strategy) and numerous configurations (e.g. parameters) for them. Currently I have organised the configurations in json files, which may look like this:
{
 "script": "xyz.strategy.strategyA",
 "datafile": "//datasrv10//data$//data//bloom.csv",
 "assets": ["B EQUITY","A EQUITY"],
 ...
}

So, I have to use some sort of reflection to initialize the correct class. I found importlib for that purpose. I managed to import modules. Now each script is its own module and each module has a build function with the same interface:
def build(configuration, data):
    return Risk(configuration, data)

class Risk(Strategy):

All of this looks like bad old-school Java to me. Can anyone show me the light in Python?

A: If you need some sort of configuration for this setup then there is no silver bullet. You can use json, yaml or maybe a relational database to store the configuration. Some improvement could come from allowing python code to be used for config, but this creates security issues if configuration can be provided externally.
The second step is translating configuration into actual python class instances, assign correct parameters etc. importlib serves great for this purpose and there isn't much to be improved upon here. You need some kind of factory for your classes, just try not to abstract too much (this is very Java-like and not pythonic), maybe one global method that is able to create objects based solely on configuration fragment?


Q: General architecture for backend? We are trying to be forward looking in our architecture choice on some of the new systems we are designing. Pretty much we want to architecture back end system that no matter what interface we decide to use (WinForms, Silverlight, MVC, Webforms, WPF, IOS (IPad/Iphone), ect...) which i believe just screams REST. Our organization generally will only use Microsoft APIs but since i have no idea when WCF-Web-Api will be released and we want to get started soon it looks like we have no other choice.
We want to take baby steps here to increase the chances of buy off. So we don't want to have to set up another server with IIS.
In the foreseeable future we will only be using WinForms & WebForms. What i was thinking we could use Nancy on the local machine but communicate with it in a RESTFul way. That way in the future it should be as simple as setting up a server and redirecting all the clients to that server rather than locally.
I've never used either NancyFX or OpenRasta, but, from what ive heard, it sounded like a good fit.
So the questions are:

*

*Is the way i'm thinking on approaching this a good approach

*Does it sound like NancyFX or OpenRasta would be a better fit?

*Any reason why we should wait for WCF-Web-API and if so does anyone have an approx release date.

A: OpenRasta was built for resource-oriented scenarios. You can achieve the same thing with any other frameworks (with more or less pain). OpenRasta gives you a fully-composited, IoC friendly environment that completely decouples handlers and whatever renders them (which makes it different from MVC frameworks like nancy and MVC).
I'd add that we have a very strong community, a stable codebase and we've been in this for quite a few years, we're building 2.1 and 3.0 and our featureset is still above and beyond what you can get from most other systems. Compare this to most of the frameworks you've highlighted, where none have reached 1.0.
Professional support is also available, if that's a deciding factor for your company.
But to answer your question fully, depending on your scenario and what you want to achieve, you can make anything fits, given enough work. I'd suggest reformulating your question in terms of architecture rather than in terms of frameworks.


Q: Typegoose - ObjectId that references a Sub-Document I'm trying to pull a ref from a Subdocument. The Documents looks like this.
Sample Categories Doc:
{
  "_id": 12345
  "keyword": "smart phones",
  "subCategories": [
    {
      "_id": 6789,
      "keyword": "apple"
    },
    {
      "_id": 101123,
      "keyword": "samsung"
    }
  ]
}

Sample Dictionary Doc:
{
  "_id": 12345
  "keyword": "iPhone",
  "category": 12345,
  "subCategory": 6789
}

Here's what I've tried to do on Typegoose model definition:
For Dictionary (notice the subCategory prop, I'm not sure if that's the right way to reference a subdocument):
export class Dictionary extends Typegoose {
  _id!: Schema.Types.ObjectId;

  @prop({
    default: 1
  })
  type!: IDictionaryInput['type'];

  @prop()
  mainKeyword!: string;

  @arrayProp({ items: Synonym })
  synonyms!: Synonym[];

  @prop({ ref: Category })
  category!: Ref<Category>;

  @prop({ ref: CategoryModel.subCategories })
  subCategory!: Ref<Subcategory>;

  @prop({
    default: true
  })
  status!: IDictionaryInput['status'];
}

For Categories:
export class Category extends Typegoose {
  _id!: Schema.Types.ObjectId;

  @prop()
  keyword!: ICategoryInput['keyword'];

  @prop({
    default: 1
  })
  type!: ICategoryInput['type'];

  @arrayProp({ items: Subcategory })
  subCategories!: Subcategory[];

  @prop({
    default: true
  })
  status!: ICategoryInput['status'];

  @prop()
  insertTimestamp!: ICategoryInput['insertTimestamp'];
}

Then I tried to populate the references by doing:
DictionaryModel.findOne({ _id: id })
    .populate({
      path: 'category',
      model: CategoryModel
    })
    .populate({
      path: 'subCategory',
      model: CategoryModel.subCategories
    });

I can successfully populate the ref from category but not on subCategory.


Q: Is the HttpServletRequest-object unique for each request? I have implemented with a servlet with below doGet & doPost methods:
        public void doGet(HttpServletRequest request, HttpServletResponse response){
               // code
            }

        public void doPost(HttpServletRequest request, HttpServletResponse response){
               // code
            }

My question: Is the HttpServletRequest object in these methods unique for every unique ?
I am using request.setAttribute("att","value"); method.  to save some values.
I want to know if I save an attribute in
first request, will be it present in the next request object. (Provided both requests are received at
almost same time)

A: No - its a new request every time - any attributes set in one request, will not be there when the next request comes in.
If you want to set attributes that are persistent across requests, you can use:
request.getServletContext().setAttribute("att","value");


Q: MySQL returns zero rows(Empty set) without limit because of broken/outdated index I work on a large table with around 1.5k entries,
CREATE TABLE `crawler` (
`id` int(11) NOT NULL AUTO_INCREMENT,
...
`provider_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `crawler_provider_id` (`provider_id`),
...
) ENGINE=MyISAM ...

provider_id is used to link this table to another table 'providers, which was cleared and repopulated with new data. I was trying to recreate connections from 'crawler' to 'providers' (which should not really matter in case of MyISAM), but for some reason in my script MySQL returns zero rows if i don't provide a limit.
mysql> SELECT `crawler`.`id` FROM `crawler` WHERE `crawler`.`provider_id` > 1371;
Empty set (0.40 sec)

but
mysql> SELECT COUNT(*) FROM `crawler` WHERE `crawler`.`provider_id` > 1371;
|   346999 |

and
mysql> SELECT `crawler`.`id` FROM `crawler` WHERE `crawler`.`provider_id` > 1371 LIMIT 10;
10 rows in set (0.01 sec)

If I select some data from table and check it by myself I can see values greater than 1371.
I was able to fix this by deleting indexes (and recreating later), but I am extremely confused. I've never seen indexes going out of sync with table data (and I was unaware that they can affect values of returned rows). Unfortunately I haven't performed "CHECK TABLE" before deleting indexes, but it has "status=ok" right now, I can't see anything wrong in logs, and "REPAIR TABLE" shows no problems.
So, is this a common problem? What can be the reason? This server had some low RAM problems before, could it be the issue here as well?

A: Your query is almost certainly related to table corruption in MyISAM.
I did
root@localhost [kris]> create table crawler (
  id integer not null auto_increment primary key,
  provider_id int(11) DEFAULT NULL,
  PRIMARY KEY (id),
  KEY crawler_provider_id (provider_id)
) engine = myisam;
root@localhost [kris]> insert into crawler ( id, provider_id ) values ( NULL, 1 );</code>

and then repeated
root@localhost [kris]> insert into crawler ( id, provider_id)
  select NULL, rand() * 120000 from crawler;

until I had
root@localhost [kris]> select count(*) from crawler;
+----------+
| count(*) |
+----------+
|   524288 |
+----------+
1 row in set (0.00 sec)

I now have
root@localhost [kris]> SELECT COUNT(*) FROM `crawler` WHERE `crawler`.`provider_id` > 1371;
+----------+
| COUNT(*) |
+----------+
|   518389 |
+----------+
1 row in set (0.27 sec)

which is somewhat comparable in size to what you gave in your example above. I do get two different plans for the query with and without a LIMIT clause.
Without a LIMIT clause I get a full table scan (ALL) not using any index:
root@localhost [kris]> explain SELECT `crawler`.`id` FROM `crawler` WHERE `crawler`.`provider_id` > 1371\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: crawler
         type: ALL
possible_keys: crawler_provider_id
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 524288
        Extra: Using where
1 row in set (0.00 sec)

With the LIMIT clause, the INDEX is used for a RANGE access
root@localhost [kris]> explain SELECT `crawler`.`id` FROM `crawler` WHERE `crawler`.`provider_id` > 1371 LIMIT 10\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: crawler
         type: range
possible_keys: crawler_provider_id
          key: crawler_provider_id
      key_len: 5
          ref: NULL
         rows: 518136
        Extra: Using where
1 row in set (0.00 sec)

In your example, without the LIMIT clause (full table scan) you get no data, but with the LIMIT clause (range access using index) you get data. That points to a corrupted MYD file.
ALTER TABLE, as REPAIR TABLE or OPTIMIZE TABLE, will normally copy the data and the kept indexes from the source table to a hidden new version of the table in a new format. When completed, the hidden new table will replace the old version of the table (which will be renamed to a hidden name, and then dropped).
That is, by dropping the indexes you effectively repaired the table.

A: Maybe you can delete and recreate the index, and after that repair or optimize the table so all indices get rebuilt.  That may help you. And look at your configuration to see if the memory settings are appropriate.


Q: How to prevent access to object properties that do not yet exist Often I have this situation:
var obj = { field: 2 };
and in the code:
do_something( obj.fiel );  // note: field spelt wrong
ie The property is incorrectly typed.  I want to detect these bugs as early as possible.
I wanted to seal the object, ie
obj = Object.seal(obj);
But that only seems to prevent errors like obj.fiel = 2; and does not throw errors when the field is simply read.
Is there any way to lock the object down so any read access to missing properties is detected and thrown?
thanks,
Paul
EDIT: Further info about the situation

*

*Plain javascript, no compilers.

*Libraries used by inexperienced programmers for math calc purposes.  I want to limit their errors.  I can spot a misspelt variable but they can't.

*Want to detect as many errors as possible, as early as possible.  ie at compile time (best), at runtime with thrown error as soon as wrong spelling encountered (ok), or when analysing results and finding incorrect calculation outputs (very very bad).

*Unit tests are not really an option as the purpose of the math is to discover new knowledge, thus the answers to the math is often not known in advance.  And again, inexperienced programmers so hard to teach them unit testing.

A: I don't think this will work in Javascript since objects are written like JSON and thus properties will be undefined or null but not throw an error.
The solution will be writing a native getter/setter.
var obj = {
    vars: {},

    set: function(index, value) {
        obj.vars[index] = value;
    },

    get: function(index) {
        if (typeof(vars[index]) == "undefined") {
            throw "Undefined property " + index;
        }

        return vars[index];
    }
};

A: There is no reliable getter/setters in javascript right now. You have to check it manually. Here's a way to do that:
if (!('key' in object)) {
    // throw exception
}


Q: Can't resolve jar library in InteliJ when adding to libraries in SBT project I want to add the Apache commons library to my Scala project. Before moving it to SBT it worked by just adding it to the library or global library setting within my InteliJ project. Now that I moved to sbt it doesn't resolve anymore and I'm getting errors.
How do I add a local jar library as an SBT dependency within InteliJ?

A: You need to make sure SBT is able to find that dependency. Follow a standard way of adding unmanaged dependencies to your project as described here. Citing that reference:

Unmanaged dependencies
Most people use managed dependencies instead of unmanaged. But
  unmanaged can be simpler when starting out.
Unmanaged dependencies work like this: add jars to lib and they will
  be placed on the project classpath. Not much else to it!
You can place test jars such as ScalaCheck, specs, and ScalaTest in
  lib as well.
Dependencies in lib go on all the classpaths (for compile, test, run,
  and console). If you wanted to change the classpath for just one of
  those, you would adjust dependencyClasspath in Compile or
  dependencyClasspath in Runtime for example.
There’s nothing to add to build.sbt to use unmanaged dependencies,
  though you could change the unmanagedBase key if you’d like to use a
  different directory rather than lib.
To use custom_lib instead of lib:
unmanagedBase := baseDirectory.value / "custom_lib"
baseDirectory is the project’s root directory, so here you’re changing
  unmanagedBase depending on baseDirectory using the special value
  method as explained in more kinds of setting.
There’s also an unmanagedJars task which lists the jars from the
  unmanagedBase directory. If you wanted to use multiple directories or
  do something else complex, you might need to replace the whole
  unmanagedJars task with one that does something else.

To test if it works well just run SBT externally (outside of IntelliJ from cmd) and execute update or compile tasks. If your library is used in the code and you get no errors then SBT is happy. Afterwards simply use "Import Project" in IntelliJ and select "Use auto-import" option in one of the wizard steps.

A: Add this to your build.sbt:

libraryDependencies += "org.apache.commons" % "commons-math3" % "3.5"


Q: How to handle relative paths in a bash setup script? I often run into the situation where I would like to provide some kind of 'setup' or 'install' script, for something like a git repository, although it could also be used in other situations.
Just to be clear: with 'setup script' I mean a script which places some files, checks some things, creates certain dependencies and so on.
The problem is that if I want to use resources relative to the script or want to create links that target files in the repository I somehow need to be able to reference resources relative to the repository root or build absolute paths.
Currently I always go with this:
SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd)
ROOT=$(realpath "$SCRIPT_DIR/..")

But this seems really bad, as it hard to understand and basically replicated in every repo or even file.
Is there a better way to do this? Are scripts like this unwanted?

A:
Is there a better way to do this?

No.

Are scripts like this unwanted?

No. That's normal.

Is there another way to go about this?

My fingers are used to typing "$(dirname "$(readlink -f "$0")")", but that's not better.
Also do not use UPPER CASE VARIABLES. Not only they shout, but are meant for environment variables, like PWD LINES COLUMNS DISPLAY UID IFS USER etc. Prefer lower case variables in your scripts. (I would say that ROOT is a very common and thus bad variable name.)

A: In a git repo, you might use git rev-parse --show-toplevel to find the root of the worktree, and then go from there.
In general, it is a somewhat hard problem. There are too many ways to invoke a script that can alter what $0 actually means, so you can't really rely on it. In my opinion, the best you can do there is to establish a standard (for example, by expecting certain values in the environment or insisting the script be executed as ./path/from/root/to/script) and try to exit with good error messages if not.

A: Can this improve scripts management and readability ?
#!/usr/bin/env bash

source $HOME/common-tools/include.sh "${BASH_SOURCE[0]}"

echo $ROOT

in $HOME/common-tools/include.sh :
SCRIPT_DIR=$(cd "$( dirname "$1" )" >/dev/null 2>&1 && pwd)
ROOT=$(realpath "$SCRIPT_DIR/..")


Q: How can I populate this 2d array with values from a char array So I have a grid that is 6 by 7
char[][] grid = new char[6][7];

And is populated with blank spaces using this loop:
for (int row = 0; row < grid.length; row++) {
        for (int col = 0; col < grid[0].length; col++) {
            grid[row][col] = ' ';
        }
    }

I also have a char[] array that holds 'A's 'B's and blank spaces. For example ch[0] = B, ch[1] = A, ch[8] = " ".
And I am simply trying to populate each slot of the 2d array 'grid' with the contents of the char array one at a time.
I tried to use the same for loop with some changes to populate the grid but when I run it only populates the top row of my grid and I'm not sure why. I have tried to move the i++, and change the for loop parameters but nothing is working and I need help. This is how I am trying to do it:
            int i = 0;
            for (int row = 0; row < grid.length; row++) {
                for (int col = 0; col < grid[0].length; col++) {
                    grid[row][col] = ch[i];
                    i++;
                }
            }

If it helps to know I am getting the contents of ch[] from a .csv file and storing it in a char array. When I run this code as is, it perfectly populates the top row of my grid (first row) but then it does not do anything to the remaining rows.
I don't want to change the data types of anything, I know I can get this too work I just need some help.


Q: Why does the mongo shell work without mongod server being explicitly run? Running MongoDB Shell v-3.2.8
I've noticed that articles and tutorials always mention to run the mongod server before running the mongo shell.
However, when I skip the first step and simply type mongo into my terminal, the mongo shell works without any errors / interruptions.
MacBook:Desktop user$ mongo
MongoDB shell version: 3.2.8
connecting to: test

Why does this work? Does mongo call mongod?

A: The mongod is being ran as a service or daemon, which means that there is always a mongod process running listening to a port. I use ubuntu, and when I install mongodb through the package manager, it immediately starts up a mongod process and begins listening on the standard port.
Running mongo is simply a small utility that attempts to connect to the localhost at the standard ip. The data reading, writing, and querying is done by the mongod process while mongo is a small program that sends the the commands to mongod.
If mongod wasn't running, you would see an error stating "Unable to connect to mongodb server"

A: I noticed the same. I think mongoose is doing some smart things there, which I'm not sure how it works. But I have noticed such things before, like mongoose will automatically add an "s" to your database's name when you declare it, which is a very thoughtful act =)).

A: I encountered the same thing and found that in the background services if MongoDB server is running, the mongo shell will work without any error. If we stop the service, the shell will throw an error.


Q: "Unable to connect to server" error while attempting to get street address by entering latitude and longitude this is my code to return address for providing latitude and longitude of a place.
public string GetLocation()
{
    HttpWebRequest request = default(HttpWebRequest);
    HttpWebResponse response = null;
    StreamReader reader = default(StreamReader);
    string json = null;
    try
    {
        //Create the web request
        request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/json?latlng=27.7121753,85.3434027&sensor=true");
         //Get response
            response = (HttpWebResponse)request.GetResponse();
        //Get the response stream into a reader
            reader = new StreamReader(response.GetResponseStream());
            json = reader.ReadToEnd();
            response.Close();
            TextBox1.Text = json;
            if (json.Contains("ZERO_RESULTS"))
            {
                TextBox2.Text = "No Address Available";
            };

            if (json.Contains("formatted_address"))
            {
                //CurrentAddress.Text = "Address Available";
                int start = json.IndexOf("formatted_address");
                int end = json.IndexOf(", Nepal");
                string AddStart = json.Substring(start + 21);
                string EndStart = json.Substring(end);
                string FinalAddress = AddStart.Replace(EndStart, ""); //Gives Full Address, One Line

                TextBox2.Text = FinalAddress;

            };
    }
    catch (Exception ex)
    {
        string Message = "Error: " + ex.ToString();
    }
}

as the code reaches response = (HttpWebResponse)request.GetResponse(); it throws an error
"Unable to connect to the remote server".. can anyone tell how can i solve it?

A: The Web Request code works for me in US. Ensure the following:

*

*You're not using Proxy etc.

*You can enter this URL in the browser and see JSON results: http://maps.googleapis.com/maps/api/geocode/json?latlng=27.7121753,85.3434027&sensor=true

*Run Fiddler and see what is your request/response.

*Google MAP API access is allowed in the country you're trying from.

Most probably this looks like a proxy issue, since Google APIs would give back better error messages for country access/excessive requests etc.
Try setting your proxy in the config as follows:
<system.net>
 <defaultProxy>
  <proxy usesystemdefault = "false" proxyaddress="http://address:port" bypassonlocal="false" />
 </defaultProxy>
</system.net>


Q: Google Static Maps With Traffic and Public Transport Overlays I use the following to get a png image of the location I want:
string.Format(
            "http://maps.googleapis.com/maps/api/staticmap?center={0},{1}&zoom={2}&size={3}x{4}&maptype={5}&sensor=false",
            latitude,
            longitude,
            zoomLevel,
            width,
            height,
            (char)this.Type);

How can I add traffic or public transport overlays to the image via the URL? Is there an alternative URL api?

A: Appending the following, for example for traffic overlay;

&layer=t

For other overlays just use the link button in the top right of the bottom left hand pane after selecting the layer you want to see which parameters need to be added to the URL to show the given overlay(s)


Q: Kubernetes volume snapshot Vs. sql backup? I am running database inside Kubernetes pod. i am planning to run K8s job to take automatic backup of databases from pod.
There is also i can write shell script to take snapshot of volume(PV).
which method will be better to use? in emergency which one will save time restore data ?

A: You can use Stash by AppsCode which is a great solution to backup Kubernetes volumes.
For supported versions check here

Stash by AppsCode is a Kubernetes operator for restic. If you are
  running production workloads in Kubernetes, you might want to take
  backup of your disks. Traditional tools are too complex to setup and
  maintain in a dynamic compute environment like Kubernetes. restic is a
  backup program that is fast, efficient and secure with few moving
  parts. Stash is a CRD controller for Kubernetes built around restic to
  address these issues.
  Using Stash, you can backup Kubernetes volumes mounted in following
  types of workloads:
Deployment, DaemonSet, ReplicaSet, ReplicationController, StatefulSet

After installing stash using Script or HELM you would want to follow
Instructions for Backup and Restore if you are not familiar
I find it very useful


Q: Insert an array into MySQL using LabVIEW and Workbench I am running an experiment and want to log a double array of 500 values to a MySQL table using LabVIEW.  The amount of results will vary per test, and may be up to 2,000 but usually 500.
Firstly, I am instantiating a database.  I am thinking of setting the column to mediumtext, is that the best type?
Secondly, advice such as here, suggests first converting all double arrays to comma separated strings.  Is that the best approach?
It all seems very contrived, is there a better way of storing arrays in MySQL?

A: An array usually consists of values all of the same type. That fits perfectly to a database column, where all values have the same type as well. Hence, for e.g. an array of double, you could create a column that takes float values and insert each member of the array as individual row. 500 rows is nothing, you could insert millions that way.

A: *

*below query works to insert array of string to the column in MYSql Workbench

insert into tableName (column1) values ('["Lorem Ipsum","Lorem Ipsum","Lorem Ipsum","Lorem Ipsum","Lorem Ipsum"]')


Q: Web View com zoom Tenho uma web view sendo carregada na tela (montado por um HTML interno) que as vezes abre com zoom e outras sem o zoom. Não quero que ela abra com zoom, preciso que ela abra na tela inteira!
Aqui o trecho do layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webViewReport"
        android:layout_below="@+id/button_report"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true" />

</LinearLayout>

Aqui carrego o HTML e jogo pro WV
montaHTML();

wv = (WebView) findViewById(R.id.webViewReport);
ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setSupportZoom(true);
ws.setDefaultTextEncodingName("utf-8");
wv.loadData(html, "text/html; charset=utf-8", "UTF-8");

A: Tente adicionar este método: ws.setLoadWithOverviewMode(true);.
Ele define se o carregamento da página WebView será no modo de visão geral, afastando o conteúdo para caber na tela através da largura.
Referência:
https://developer.android.com/reference/android/webkit/WebSettings.html


Q: model name to controller name How can I get the controller name out of the object if I don't know what the object is?
I am trying to do:
object.class.tableize

but Rails says:
undefined method `tableize' for #<Class:0xb6f8ee20>

I tried adding demodulize with same result.
thanks

A: object.class.to_s.tableize

A: For semantic reasons, you might want to do:
object.class.name #=> 'FooBar'

You can also use tableize with this sequence, like so:
object.class.name.tableize #=> 'foo_bars'

I prefer it that way due to readability.
As well, note that tableize also does pluralization. If unwanted use underscore.
Hope it helps anyone, even if it's an old thread :)


Q: Ball arithmetic vs interval arithmetic What are the advantages of ball arithmetic (Arb) over interval arithmetic (MPFI)?
In other words, what are the advantages of representing an interval as [center, radius] over [left, right]?
This is not about particular library (Arb vs MPFI), rather it is about advantages of a particular representation.
I'm especially interested whether one representation allows for faster arithmetic (fewer primitive operations), lesser error over-estimation and more frugal memory usage.

A: In arbitrary-precision arithmetic, ball arithmetic is about twice as fast as interval arithmetic and uses half as much space. The reason is that only the center of a ball needs high precision, whereas in interval arithmetic, both endpoints need high precision. Details depend on the implementation, of course. (In practice, Arb is faster than MPFI by much more than a factor two, but this is largely due to implementation effort.)
In hardware arithmetic, balls don't really have a speed advantage over intervals, at least for scalar arithmetic. There is an obvious advantage if you look at more general forms of ball arithmetic and consider, for example, a ball matrix as a floating-point matrix + a single floating-point number for the error bound of the whole matrix in some norm, instead of working with a matrix of individual intervals or balls.
Joris van der Hoeven's article on ball arithmetic is a good take on the differences between ball and interval arithmetic: http://www.texmacs.org/joris/ball/ball.html
An important quote is: "Roughly speaking, balls should be used for the reliable approximation of numbers, whereas intervals are mainly useful for certified algorithms which rely on the subdivision of space."
Ignoring performance concerns, balls and intervals are usually interchangeable, although intervals are better suited for subdivision algorithms. Conceptually, balls are nice for representing numbers because the center-radius form corresponds naturally to how we think of approximations in mathematics. This notion also extends naturally to more general normed vector spaces.
Personally, I often think of ball arithmetic as floating-point arithmetic + error analysis, but with the error bound propagation done automatically by the computer rather than by hand. In this sense, it is a better way  (for certain applications!) of doing floating-point arithmetic, not just a  better way of doing interval arithmetic.
For computations with single numbers, error over-estimation has more to do with the algorithms than with the representation. MPFI guarantees that all its atomic functions compute the tightest possible intervals, but this property is not preserved as soon as you start composing functions. With either ball or interval arithmetic, blow-up tends to happen in the same way as soon as you run calculations with many dependent steps. To track error bounds resulting from large uncertainties in initial conditions, techniques such as Taylor models are often better than direct interval or ball arithmetic.
True complex balls (complex center + single radius) are sometimes better than rectangular complex intervals for representing complex numbers because the wrapping effect for multiplications is smaller. (However, Arb uses rectangular "balls" for complex numbers, so it does not have this particular advantage.)


Q: SSIS - Loading Japanese Double byte data from DB2 to SQL Server 2017 is giving conversion error I am trying import data from DB2 which has double byte Japanese(1027) data into SQL Server 2017 using SSIS
Tried using data conversion before inserting data "932 (ANSI/OEM - Japanese Shift- JIS)". Tried using Unicode string[DT_WSTR] still the same issue

[Data Conversion [2]] Error: Data conversion failed while converting column "ABC" (286) to column "A\cABC"(38).  The conversion returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".


Q: c# console application run matlab function I have some code written in Matlab however I wish to call this code from a C# console application.
I do not require any data to be returned from Matlab to my app (although if easy would be nice to see).
There appears to be a few options however not sure which is best. Speed is not important as this will be an automated task.

A: MATLAB has a .Net interface that's well-documented. What you need to do is covered in the Call MATLAB Function from C# Client article.
For a simple MATLAB function, say:
function [x,y] = myfunc(a,b,c)
x = a + b;
y = sprintf('Hello %s',c);

..it boils down to creating an MLApp and invoking the Feval method:
class Program
{
    static void Main(string[] args)
    {
        // Create the MATLAB instance
        MLApp.MLApp matlab = new MLApp.MLApp();

        // Change to the directory where the function is located
        matlab.Execute(@"cd c:\temp\example");

        // Define the output
        object result = null;

        // Call the MATLAB function myfunc
        matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");

        // Display result
        object[] res = result as object[];

        Console.WriteLine(res[0]);
        Console.WriteLine(res[1]);
        Console.ReadLine();
    }
}


Q: Gradle project sync failed after Android-Studio (3.1) update After an update I made on 27-03-2018, my gradle sync is failing.I am getting the error
Could not find org.jetbrains.kotlin:kotlin-stdlib:1.1.3-2.

I am posting my gradle files below. I have tried cleaning and rebuilding the project, but it is still not working.
Project level gradle
    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com/'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.loopj.android:android-async-http:1.4.9'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App level gradle
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
        google()
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    lintOptions {
        disable 'InvalidPackage'
    }
    defaultConfig {
        applicationId 'app.myapp.com'
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 33
        versionName "1.1.30"
        useLibrary 'org.apache.http.legacy'
        // Enabling multidex support.
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }
    dexOptions {
        preDexLibraries = false
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    lintOptions {
        checkReleaseBuilds false
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
    }
}
repositories {
    mavenCentral()
    jcenter()

    maven { url 'https://maven.fabric.io/public'

    }

    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
    google()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile project(':android-async-http-1.4.9')

    //    compile 'com.daimajia.androidanimations:library:1.0.3@aar'
    compile project(':PayTabs_SDK_NOSCAN')
    compile('com.twitter.sdk.android:twitter:1.14.1@aar') {
        transitive = true;
    }
    compile('org.apache.httpcomponents:httpmime:4.3') {
        exclude module: "httpclient"
    }
    compile files('libs/signpost-core-1.2.1.2.jar')
    // Discovery and Outlook services
    compile('com.microsoft.services:discovery-services:1.0.0@aar') {
        transitive = true
    }
    compile('com.microsoft.services:outlook-services:1.0.0@aar') {
        transitive = true
    }
    compile 'org.sufficientlysecure:html-textview:3.3'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'cz.msebera.android:httpclient:4.3.6'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.slider:library:1.1.5@aar'
    compile 'me.dm7.barcodescanner:zxing:1.8.4'
    compile 'com.google.android.gms:play-services:9.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.gms:google-services:3.0.0'
    compile 'com.google.android.gms:play-services-ads:9.0.0'
    compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.google.android.gms:play-services-gcm:9.0.0'
    compile 'org.codepond:wizardroid:1.3.1'
    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'com.google.zxing:core:3.2.0'
    compile 'io.card:android-sdk:5.3.0'
    compile 'com.google.firebase:firebase-messaging:9.0.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'me.dm7.barcodescanner:zbar:1.8.2'
    compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.cloudrail:cloudrail-si-android:2.11.0'
    compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
    compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.ss.bannerslider:bannerslider:1.8.0'
    compile 'com.marshalchen.ultimaterecyclerview:library:0.7.3'
//    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7"

    testCompile 'junit:junit:4.12'
}
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.1'
            }
        }
    }
}

I tried all that I know, but nothing is working for now. Android Studio and Gradle are updated to the latest version. The app used to work before the update. I followed the instructions in developer.android.com about gradle migration, but nothing is mentioned there that might help me with the issue.
I am posting the error I get here
Could not find org.jetbrains.kotlin:kotlin-stdlib:1.1.3-2.
Searched in the following locations:
    https://maven.fabric.io/public/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.pom
    https://maven.fabric.io/public/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.jar
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.pom
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.jar
Required by:
    project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1
    project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.build:builder:3.0.1
    project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.lint:lint:26.0.1
    project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.build:builder:3.0.1 > com.android.tools:sdk-common:26.0.1
    project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.build:builder:3.0.1 > com.android.tools:sdklib:26.0.1 > com.android.tools:repository:26.0.1
    project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.lint:lint:26.0.1 > com.android.tools.lint:lint-checks:26.0.1 > com.android.tools.lint:lint-api:26.0.1

A: i too came up with the same issue. seems like android studio seeking to update the kotlin plugin as well.
go to Tools > Kotlin > Configure Kotlin Plugin Update and update the plugin.
then restart studio, and it will sync the gradle on restart.

A: I found the answer. I changed the versions of gradle plugins.I am adding my Gradle files below
Project Level
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath 'com.google.gms:google-services:3.1.1'
        classpath 'com.loopj.android:android-async-http:1.4.9'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Level build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    lintOptions {
        disable 'InvalidPackage'
    }
    defaultConfig {
        applicationId 'app.ecopon.com'
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 33
        versionName "1.1.30"
        useLibrary 'org.apache.http.legacy'
        // Enabling multidex support.
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }
    dexOptions {
        preDexLibraries = false
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    lintOptions {
        checkReleaseBuilds false
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
    }
}
repositories {
    mavenCentral()
    jcenter()

    maven { url 'https://maven.fabric.io/public'

    }

    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile project(':android-async-http-1.4.9')

    //    compile 'com.daimajia.androidanimations:library:1.0.3@aar'
    compile project(':PayTabs_SDK_NOSCAN')
    compile('com.twitter.sdk.android:twitter:1.14.1@aar') {
        transitive = true;
    }
    compile('org.apache.httpcomponents:httpmime:4.3') {
        exclude module: "httpclient"
    }
    compile files('libs/signpost-core-1.2.1.2.jar')
    // Discovery and Outlook services
    compile('com.microsoft.services:discovery-services:1.0.0@aar') {
        transitive = true
    }
    compile('com.microsoft.services:outlook-services:1.0.0@aar') {
        transitive = true
    }

    compile 'org.sufficientlysecure:html-textview:3.3'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'cz.msebera.android:httpclient:4.3.6'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.slider:library:1.1.5@aar'
    compile 'me.dm7.barcodescanner:zxing:1.8.4'
    compile 'com.google.android.gms:play-services:9.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.gms:google-services:3.0.0'
    compile 'com.google.android.gms:play-services-ads:9.0.0'
    compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.google.android.gms:play-services-gcm:9.0.0'
    compile 'org.codepond:wizardroid:1.3.1'
    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'com.google.zxing:core:3.2.0'
    compile 'io.card:android-sdk:5.3.0'
    compile 'com.google.firebase:firebase-messaging:9.0.0'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'me.dm7.barcodescanner:zbar:1.8.2'
    compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.cloudrail:cloudrail-si-android:2.11.0'
    compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
    compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.ss.bannerslider:bannerslider:1.8.0'
    compile 'com.marshalchen.ultimaterecyclerview:library:0.7.3'

    compile 'com.github.barteksc:android-pdf-viewer:2.8.2'

    testCompile 'junit:junit:4.12'
}
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.1'
            }
        }
    }
}

Now, everything is working perfectly

A: Found a solution to this. You need to add google() to the buildscript and allprojects repository section as below:
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

A: 1- Go to http://services.gradle.org
2- Go to Distributions
3- Click on the latest one to download it (I downloaded "gradle-4.6-rc-2-all.zip")
4- Unzip or Extract it
5- In Android Studio go to File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution > then choose the file (that you just download and unzip it) from your computer
6- Click Ok
7- Inside "build.gradle(Module:app)" make sure that compileSdkVersion and targetSdkVersion are same
8- Click Sync Now
Resource: https://www.youtube.com/watch?v=q_qWUQNbFLY

A: Change your Buildscript part of your build.gradle To this , Actully Remove google() & jcenter(). This Worked for me.
buildscript {

repositories {
    maven { url 'https://jitpack.io' }
    mavenCentral()
    maven { url "https://maven.google.com" }
}

dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'
}
}

A: You could try updating your Kotlin version and maybe add https://maven.google.com to the repositories tag of allProjects.
Your project level build.gradle should look something like this afterwards:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
   ext.kotlin_version = '1.2.30'
   repositories {
      jcenter()
      google()
   }
   dependencies {
      classpath 'com.android.tools.build:gradle:3.1.0'
      classpath 'com.google.gms:google-services:3.1.0'
      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
      classpath 'com.loopj.android:android-async-http:1.4.9'
   }
}

allprojects {
   repositories {
      jcenter()
      maven { url 'https://jitpack.io' }
      maven { url "https://maven.google.com" }
   }
}

task clean(type: Delete) {
   delete rootProject.buildDir
}

Besides that, try cleaning the project and maybe removing your .gradle folders manually

A: Try to invalidate cache(did it a few times) or reinstall studio, or check gradle-wrapper.properties distributionUrl should be like this:
distributionUrl=https://services.gradle.org/distributions/gradle-4.4-all.zip


Q: What is the syntax for the input for a def function with multiple nested functions? I'm learning Python right now and I am just trying to get to grips with all of the syntax options.
Currently, the only thing that I can't seem to google up is what to do if I for some reason want to define a function which contains multiple other defines.
While I understand what to do if there's only 1 define inside the the larger define (val = f()(3,4) returns 7 if you exclude the second def below), I don't know how to correctly use the function below.
If it's possible, what is the syntax for a def function with an arbitrary amount of defined functions within it?

Code:
def f():
    def x(a,b):
        return a + b
    return x
    def y(c,d):
        return c + d
    return y

 val = f()(3,4)(5,6)
 print(val)

I expected the above to return either (7,11) or 11. However, it returns 'int object is not callable'

A: When you write val = f()(3,4)(5,6), you want f to return a function that also returns a function; compare with the simpler multi-line call:
t1 = f()
t2 = t1(3,4)
val = t2(5,6)

The function f defines and returns also has to define and return a function that can be called with 2 arguments. So, as @jonrsharpe said, you need more nesting:
def f():
    def x(a, b):
        def y(c, d):
            return c + d
        return y
    return x

Now, f() produces the function named x, and f()(3,4) produces the function named y (ignoring its arguments 3 and 4 in the process), and f()(3,4)(5,6) evaluates (ultimately) to 5 + 6.


Q: Парсинг большого XML на PHP Написал парсер, который парсит yandex YML с товарами, а так же копирует все картинки товаров и заносит всё в базу, картинки в папки разлаживает.
Файл в котором 400 товаров парсит нормально, а вот файл с 27411 товаров очень долго проходит.
В настройках выставляется какое количество товаров парсить за один раз, выставлял разное количество, толку нет. За каждый проход парсер загружается заново.
$yml = simplexml_load_file($shop_info["yml_location"]);

Можно ли как-то получать товары по 10 или 20 штук из файла? Что бы не грузить постоянно весь файл. Хостинг не выдерживает.
Зато на денвере грузит всё чётко быстро.

A: Для парсинга больших XML файлов средствами PHP лучше всего подходит библиотека XMLReader.
Библиотека поддерживает обработку сжатых XML файлов.
$xmlfile = 'compress.zlib://dir/largefile.xml.gz';
$reader = new XMLReader();
$reader->open($xmlfile);

A: Есть вариант оптимизации процесса импорта. Можно написать XSLT преобразователь XML в CSV, использовать для преобразования http://xmlsoft.org/XSLT/xsltproc.html в режиме командной строки, а потом уже работать с чистыми данными, без смысловой разметки, средствами PHP. Разборка и обработка XML контента средствами PHP более ресурсоемкая операция.


Q: Installing Glassfish to work with Eclipse I am stock here with glassfish configuration at Eclipse.
Take a look:

The finish button is disabled. What should I do here? I am pointing it to the directory in which I have installed glassfish. Plz help.

A: I think the problem might be that you were trying to register GF 3.1.2 to use Java SE 5.  Java EE 6 requires a Java SE 6 JDK to run successfully.

A: Okay I don't know what was wrong with it. Just tried it one more time and it worked! Sry for taking your times.


Q: c-index for parametric links in binary regression I am conducting a binary regression using different sorts of parametric links (logistic, Pregibon, Aranda-Ordaz, ... see) and I would like to compare their predictive and classification perfomance in a particular data set using the c-index. However, I wonder if this is correct given that this measure does not depend on the additional shape parameters in the link function, only on the estimated regression parameters.

A: The $c$-index (concordance probability or ROC area; simple function of Somers' $D_{xy}$ rank correlation) only uses the ranks of predictions so is not sensitive enough for model comparisons, especially of the type you outline.  I suggest using proper scoring rules such as the Brier (quadratic) score and deviance-based measures such as generalized $R^2$.  Even those are not ideal.  Bootstrap bias-corrected smooth (loess) calibration curves may be a better approach.  An indirect approach would be to find the link that minimized the likelihood ratio $\chi^2$ due to all two-way interaction terms, i.e., the link that maximizes additivity.
Sometimes I see analysts worrying about getting the link function right when the more important assumption may be the linearity assumption for the predictors.  It is often a mistake to assume linearity.  Expanding predictors using regression splines is an important part of the fitting process no matter what the link.


Q: Decode a special character...? I am pulling through the field item_name from a database. It should read : "Reminisce Basic £11.99 + Card £4.99 + Free"
But when its coming through the £ signs are coming out as � is there a method to decode this to at least make it look like a £ sign?
My code is as follows :
<?php
    $con = mysql_connect("localhost","","");
    mysql_select_db("", $con);

    $result = mysql_query("SELECT custom, item_name from paypalsub WHERE custom = '$_SESSION[uid]'");

    while($row = mysql_fetch_array($result))
    {
        $sub_type = $row['item_name'];
    }
?>

You are currently subscribed to : <?php echo ($sub_type); ?>

The H2 is outputting it like this :

You are currently subscribed to : Reminisce Basic �11.99 + Card �4.99 + Free

Any help.. Much appreciated.

A: Try with utf8_encode($string) or utf8_decode($string). I never remember which one to use, sorry.

A: 1.) Are you sending the output in UTF-8?
header('content-type: text/html; charset=utf-8')

2.) Have you also set the MySQL connection to UTF-8?
mysql_query("SET NAMES 'utf-8'");

A: It looks like your database is in some encoding (not UTF-8) and your output is in a different encoding.
Find out which encoding the database uses.


Q: Arrangement properties in WPF styles Is it normal to store Alignments, Margins, Paddings and other arrangement properties in styles?


Q: Get Woocommerce product reviews via rest api I tried to get product reviews with rest api but I got an error woocommerce_rest_cannot_view
https://example.com/wp-json/wc/v3/products/reviews?product=ID

I don't know where is the problem

A: In some how it was an issue on woocommerce api

I edited the class-wc-rest-product-reviews.php
$prepared_args['type'] = 'review';

changed review to comment and it works


Q: Object of class [org.jongo.bson.RelaxedLazyDBObject] must be an instance of class com.mongodb.BasicDBObject I'm trying to setup tests with Spring Boot and Mongo Embedded (JHipster, Flapdoodle).
In general it works. I can see database in Robomongo with created test collections and objects (migrations using Mongobee).
But when I want to access Clients collection:

    List clients = clientRepository.findAll();

It throws:

    java.lang.IllegalArgumentException: Given DBObject must be a BasicDBObject! Object of class [org.jongo.bson.RelaxedLazyDBObject] must be an instance of class com.mongodb.BasicDBObject

When I run application with real Mongo instance:
./mvnw -Pdev
there are no errors even though test and dev configurations use the same Mongobee mibrations.
Spring documentation is very laconic:
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-mongo-embedded
My test configuration file application.yml is:

    spring:
        mongodb:
            embedded:
                version: 3.2.1
        data:
            mongodb:
                host: localhost
                port: 27117
                database: mydb-test

I use Mongo (real instance) version v3.2.7, in configuration highest possible version of Embedded Mongo which I set is 3.2.1, maybe this could be a problem?
Maybe someone could share his configuration with example working tests?

A: I find my self the solution.
Problem was that I used org.jongo.Jongo instead of JHipster default com.mongodb.Db in @ChangeSet.
For some reasons Jongo doesn't work well with Embedded Mongo.
When I switched to Db, all problems has gone.
NOT WORKING:
@ChangeSet(...)
public void someChange(Jongo jongo) throws IOException {

    org.jongo.MongoCollection collection = jongo.getCollection("collection");
    DBObject basicDBObject = new BasicDBObject();
    collection.insert(basicDBObject);

     ...
}

WORKING:
@ChangeSet(...)
public void someChange(Db db) throws IOException {

    com.mongodb.MongoCollection collection = db.getCollection("collection");
    DBObject basicDBObject = new BasicDBObject();
    collection.insert(basicDBObject);
    ...
}


Q: Backbone trigger event after custom function possible? Excuse my backbone i'm not an expert, Must execute function Show absolutely and only after ResetQuestions
      ResetQuestions:function () {
       //Great Code Here
        }),

I tried this:
    initialize: function () {
     this.on("Show", this.Show, this);
      },
     ResetQuestions:function () {
       //Great Code Here
           this.trigger("Show");
        }),

But that was unsuccessful, does anyone know how i can accomplish this?

A: no need of events you can simply call the function from other function
 var sampleView = Backbone.View.extend({
        initialize: function () {
            this.ResetQuestions();
        },
        Show: function () {
            alert('i am at show');
        },
        ResetQuestions: function () {
            // Execute all you code atlast call Show function as below.
            this.Show();
        }

    });
var view = new sampleView();

A: var sampleView = Backbone.View.extend({
    initialize: function(){
       this.ResetQuestions().promise().done(function() {   // Using promise here.
         this.Show();
       });
    },
    Show: function(){

    },
    ResetQuestions: function(){
    // Execute all you code atlast call Show function as below.

    }

});

Then initiate your view,
var view = new sampleView();

Hope this works!!

A: Perhaps you just got confused what runs what and by naming event and method with same name Show. I have created a jsfiddle with your code - http://jsfiddle.net/yuraji/aqymbeyy/ - you call ResetQuestion method, it triggers Show event, and the Show event runs Show method.
EDIT: I have updated the fiddle to demonstrate that you probably have to bind the methods to the instance, I used _.bindAll for that. If you don't do that you may get event as the context (this).
EDIT: Then, if your ResetQuestions runs asynchronous code, like an ajax request to get new questions, you will have to make sure that your Show event is triggered when the request is completed.


Q: Коснулся первый объект второго? Как узнать? Python Tkinter Код сейчас:
from tkinter import *
import time
root=Tk()
canvas=Canvas(root, width=700, height=700)
canvas.pack()
canvas.create_polygon(50, 2, 90, 10, 10, 10,
                      fill='red',
                      outline='black')
def movetriangle(event):
    if event.keysym=='Up':
        canvas.move(1, 0, -3)
    elif event.keysym=='Down':
        canvas.move(1, 0, 3)
    elif event.keysym=='Left':
        canvas.move(1, -7, 0)
    elif event.keysym=='Right':
        canvas.move(1, 7, 0)
canvas.bind_all('<KeyPress-Up>', movetriangle)
canvas.bind_all('<KeyPress-Down>', movetriangle)
canvas.bind_all('<KeyPress-Left>', movetriangle)
canvas.bind_all('<KeyPress-Right>', movetriangle)
root.mainloop()

Сейчас есть только один объект. А если добавить второй. Как узнать коснулся ли первый объект второго? А если второй объект коснулся стены, как это узнать?

A: У Canvas есть метод find_overlapping, который находит все объекты, попадающие в заданный прямоугольник. Мы можем как первое приближение "заменить" первую фигуру на прямоугольник, найти пересекающиеся с этим прямоугольником фигуры - так мы найдем фигуры, которые возможно пересекаются с данной фигурой и отсечем фигуры, которые точно не пересекаются с ней.
В коде будет что-то вроде этого:
poly1 = canvas.create_polygon(50, 2, 90, 10, 10, 10, fill='red', outline='black')

...
# Получаем множество возможно пересекающихся фигур:
overlapping = set(canvas.find_overlapping(*canvas.bbox(poly1)))
# canvas.bbox(poly1) - получить ограничивающий прямоугольник (bounding box) указанной фигуры

# В множество пересекающихся фигур попадает сама исходная фигура, удаляем ее из множества:
overlapping.discard(poly1)

Дальше уже нужно использовать более точные методы - например проверять, есть ли пересекающиеся стороны двух фигур.
Рекомендую почитать книгу "Физика для разработчиков компьютерных игр" (Д.Конгер), конкретно главу про обнаружение столкновений.
По поводу столкновения со стеной - это довольно просто проверяется, просто проверяете, не вышел ли какой-то из углов за границы допустимой области.


Q: Pentaho SDK, how to define a text file input I'm trying to define a Pentaho Kettle (ktr) transformation via code. I would like to add to the transformation a Text File Input Step: http://wiki.pentaho.com/display/EAI/Text+File+Input.
I don't know how to do this (note that I want to achieve the result in a custom Java application, not using the standard Spoon GUI). I think I should use the TextFileInputMeta class, but when I try to define the filename the trasformation doesn't work anymore (it seems empty in Spoon).
This is the code I'm using. I think the third line has something wrong:
PluginRegistry registry = PluginRegistry.getInstance();
TextFileInputMeta fileInMeta = new TextFileInputMeta();
fileInMeta.setFileName(new String[] {myFileName});
String fileInPluginId = registry.getPluginId(StepPluginType.class, fileInMeta);
StepMeta fileInStepMeta = new StepMeta(fileInPluginId, myStepName, fileInMeta);
fileInStepMeta.setDraw(true);
fileInStepMeta.setLocation(100, 200);
transAWMMeta.addStep(fileInStepMeta);

A: To run a transformation programmatically, you should do the following:

*

*Initialise Kettle

*Prepare a TransMeta object

*Prepare your steps

*

*Don't forget about Meta and Data objects!

*Add them to TransMeta

*Create Trans and run it

*

*By default, each transformation germinates a thread per step, so use trans.waitUntilFinished() to force your thread to wait until execution completes

*Pick execution's results if necessary

Use this test as example: https://github.com/pentaho/pentaho-kettle/blob/master/test/org/pentaho/di/trans/steps/textfileinput/TextFileInputTests.java
Also, I would recommend you create the transformation manually and to load it from file, if it is acceptable for your circumstances. This will help to avoid lots of boilerplate code. It is quite easy to run transformations in this case, see an example here: https://github.com/pentaho/pentaho-kettle/blob/master/test/org/pentaho/di/TestUtilities.java#L346


Q: How to access kubernetes CRD using client-go? I have few CRDs, but I am not exactly sure how to query kube-apiserver  to get list of CRs. Can anyone please provide any sample code?

A: my sample code for an out of cluster config
    var kubeconfig *string
    kubeconfig = flag.String("kubeconfig", "./config", "(optional) relative path to the kubeconfig file")
    flag.Parse()

    // kubernetes config loaded from ./config or whatever the flag was set to
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err)
    }

    // instantiate our client with config
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }

    // get a list of our CRs
    pl := PingerList{}
    d, err := clientset.RESTClient().Get().AbsPath("/apis/pinger.hel.lo/v1/pingers").DoRaw(context.TODO())
    if err != nil {
        panic(err)
    }
    if err := json.Unmarshal(d, &pl); err != nil {
        panic(err)
    }

PingerList{} is an object generated from Kubebuilder that I unmarshal to later in the code. However, you could just straight up println(string(d)) to get that json.
The components in the AbsPath() are "/apis/group/verison/plural version of resource name"
if you're using minikube, you can get the config file with kubectl config view
Kubernetes-related imports are the following
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"

A: Refer this page to get information on how to access the crd using this repo
and for more information refer this document
document

A: Either you need to use the Unstructured client, or generate a client stub. The dynamic client in the controller-runtime library is a lot nicer for this and I recommend it.