text:
Q: Magento - addFieldToFilter doesn't choose the right product I am currently programming a product configurator module for Magento. Everything is working fine so far besides the core functionality: choosing the right product from the database for the selected attributes. My attributes belong to an attribute group from which the form fields for my configurator are generated, the values I use are the admin fields. The shop language is swedish.
The shop contains one configurable product with simple products associated to it. The simple products don't show individually in the shop. Right now not all combinations of my attributes are existing but it should at least return the right product for one combination I know is existing. First it always returned null, right now it returns all products. How can I achieve to have just product be chosen?
First the attributes didn't even show in the query until I activated "Used in Product Listing".
Thanks in advance for any help :)
This is my getProduct method:
public function getProduct($attributes)
{

    Mage::Log($attributes);

    //Get Product Collection
    $collection = Mage::getModel('catalog/product')->getCollection();

    $collectionCount = count($collection);

    Mage::Log($collectionCount);

    //Filter for Selected Product
    $collection->addFieldToFilter('doorconfig_enable',array('eq' => 'Yes'));

    foreach ($attributes as $key => $value)
    {
        $collection->addFieldToFilter($key,array('eq' => $value));
    }

    $selection = $collection->getSelect()->__toString();

    Mage::Log($selection);

    $collectionCount = count($collection);

    Mage::Log($collectionCount);

    $product = $collection->getFirstItem();

    return $product;

}

The $attributes parameter contains the POST data which is correctly submitted:
[doorconfig_color] => 000000
[doorconfig_type] => lines
[doorconfig_size] => 2500x1800
[doorconfig_remote] => no
[doorconfig_digitalkeypad] => No
[doorconfig_extraremotecontrol] => No
[configdoor_addemergencylock] => No
[doorconfig_insideopeningbutton] => No
[doorconfig_window] => No window

"configdoor_addemergencylock" is a typo by my dear collegues, but still read correctly from the database (just if anyone wonders). As I am not good in SQL and not very experienced in Magento, I don't know whether my query is right or wrong:
2013-07-20T09:47:19+00:00 DEBUG (7): SELECT 1 AS `status`, `e`.`entity_id`,
`e`.`type_id`, `e`.`attribute_set_id`, `price_index`.`price`, `price_index`.
`tax_class_id`, `price_index`.`final_price`, IF(price_index.tier_price IS NOT NULL,
LEAST(price_index.min_price, price_index.tier_price), price_index.min_price)
AS `minimal_price`, `price_index`.`min_price`, `price_index`.`max_price`,
`price_index`.`tier_price`, `e`.`doorconfig_color`, `e`.`doorconfig_color_value`,
`e`.`doorconfig_type`, `e`.`doorconfig_type_value`, `e`.`doorconfig_size`,
`e`.`doorconfig_size_value`, `e`.`doorconfig_remote`, `e`.`doorconfig_remote_value`,
`e`.`doorconfig_digitalkeypad`, `e`.`doorconfig_digitalkeypad_value`,
`e`.`doorconfig_extraremotecontrol`, `e`.`doorconfig_extraremotecontrol_value`,
`e`.`configdoor_addemergencylock`, `e`.`configdoor_addemergencylock_value`,
`e`.`doorconfig_insideopeningbutton`, `e`.`doorconfig_insideopeningbutton_value`,
`e`.`doorconfig_window`, `e`.`doorconfig_window_value` FROM `catalog_product_flat_1`
AS `e` INNER JOIN `catalog_product_index_price` AS `price_index`
ON price_index.entity_id = e.entity_id AND price_index.website_id = '1'
AND price_index.customer_group_id = 0 WHERE (e.doorconfig_color = '000000')
AND (e.doorconfig_type = 'lines') AND (e.doorconfig_size = '2500x1800')
AND (e.doorconfig_remote = 'no') AND (e.doorconfig_digitalkeypad = 'No')
AND (e.doorconfig_extraremotecontrol = 'No') AND (e.configdoor_addemergencylock = 'No')
AND (e.doorconfig_insideopeningbutton = 'No') AND (e.doorconfig_window = 'No window')

A: You can try this to filter your product collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect(*);
$collection->addAttributeToFilter('doorconfig_enable',array('eq' => 'Yes'));

A: What type of "doorconfig_enable" attribute? If boolean, use "0" or "1". If "doorconfig_enable" is select attribute, you need to use option id.
So:
$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('doorconfig_enable')
    ->addAttributeToFilter('doorconfig_enable',array('eq' => 1));

Mage::log($collection->getSize(),null,'custom.log');

If you need to get the option ID, checkout this


text:
Q: Probability of 2 permutations of slightly different sets meeting in k places. I have already posted a simplified problem of this (and received a comprehensive answer) hoping that it would lead me to solving this one, however, it does not seem to be the case.
We have got two sets $A=\{1,2,3,...,n-2\}\cup\{s\}$ and $B=\{1,2,3,...,n-2\}\cup\{t\}$. So that, each of the sets contains $n-1$ elements of which $n-1$ are the same. One element is different (in $A$ there is $s$ and in $B$ we have got $t$. Now we take random, uniform permutations of set $A$ and $B$. What is the probability that these two permutations meet in exactly $k$ places ($k\in\{0,...,n-2\}$)? [Meeting in $k$ places means that they have the same numbers in $k$ places.]
This problem is of a great importance in my current work, so I would be extremely happy if you can help me.

A: Step 1. Assume that $s$ and $t$ are equal, and you have to compute the number of matches $m'(k)$ for permutations of identical sets with $n-1$ elements.  Also solve the same problem for permutations of identical sets with $n-2$ elements ($m"(k)$).
Step 2. Adjust for the situations where $s$ and $t$ are in the same position. Subtract the number of permutations $m"(k-1)$ (matches from two permutations of identical sets with $n-2$ elements) from the $m'(k)$ matches, BUT add it to $m'(k-1)$. Do this for $k$ from $1$ to $n-2$.
So the number of matches is:
$m(k)=m'(k)-m"(k-1)+m"(k)$  for  $k=1,n-2$
and
$m(0)=m'(0)+m"(0)$ (0 matches doesn't lose anything as obviously $s, t$ cannot be matched)
The probability is the number of different permutations corresponding to $k$ matches ($m(k)$ obtained as above) divided by the total number of permutations $((n-1)!)^2$.

A: Let the first permutation be identity and let the number you are seeking be $N_{n,k}$ (I'll use $n$ instead of $n-2$ for simplicity of notation). Pick $k$ places where permutations agree - $\binom {n}k$ ways. If $t$ gets mapped to $s$, the rest should be a derangement of $n-k$ elements - $D_{n-k}=[e^{-1}(n-k)!]$ ways. If $t$ gets mapped to $a\ne s$ ($n-k$ ways), then the rest of the elements can be arranged in $N_{n-k-1,0}$ ways. Combining get
$$N_{n,k}=\binom n k\left(D_{n-k}+(n-k)N_{n-k-1,0}\right)$$
You are left to find
$$N_{n,0}=D_n+nN_{n-1,0}=\sum_{i=0}^{n}D_{n-i}\frac {n!}{(n-i)!}\approx n!+n!n/e.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use `get_cleaned_data_for_step` method in a SessionWizardView? I am having an issue with persisting data from one page to the next in a SessionWizardView on my production server. It works fine on my local machine but I kept getting an Exception Value: list index out of range error when I tried to access the value of the list on a subsequent page.
As a result I am trying to use the get_cleared_data_for_step method but with no success.
My current views.py
PATH_ONE_IMAGES =   ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg']

class SurveyWizardOne(SessionWizardView):

    def get_context_data(self, form, **kwargs):
        context = super(SurveyWizardOne, self).get_context_data(form, **kwargs)
        if self.steps.current in ['5','6','7','8','9','10']:
            step = int(self.steps.current)

            if step in (5, 6, 7):
                image = random.choice(PATH_ONE_IMAGES)
                images.insert(step - 5, image)
                PATH_ONE_IMAGES.remove(image)
                context['display_image'] = image

            elif step == 8:
                images[0] = self.get_cleaned_data_for_step(5)
                images[1] = self.get_cleaned_data_for_step(6)
                images[2] = self.get_cleaned_data_for_step(7)

                print 'This is your first image', images[0]
                print 'This is your second image', images[1]
                print 'This is your third image', images[2]

Current outcome
This is your first image None
This is your second image None
This is your third image None

Expected outcome (sample)
This is your first image P1D1.jpg
This is your second image P3D3.jpg
This is your third image P4D4.jpg

What am I doing wrong? I can find very little info on how to implement the get_cleaned_data_for_step method online except for these two SO questions [1], [2] and going by these my implementation looks like it should work.
What annoys me most is that my previous solution works fine on my local machine but does not work in production.
Any help with this would be hugely appreciated. Thanks
Deepend


text:
Q: Play Framework Compile Error: '(' expected but ')' found When I attempting to compile my Play Framework 2. project, I receive this error: '(' expected but ')' found.
What I'm trying to do is : 'After a failed login attempt, user should get feedback. If the login attempt fails server side, show error messages on page after the failed request. Could someone please help me out.
I added the string that I want to display on the form after a failed login attempt as below:
if (response.hasErrors()) {
return ok(create.render(createViewModelForm, "invalid username or password"));

And on the create.scala.html
@if (!@errorMessage.isEmpty()) {

@errorMessage

  }

This is the SessionsController.java   > ui\controllers\SessionsController
package femr.ui.controllers;

import com.google.inject.Inject;
import femr.business.services.core.ISessionService;
import femr.business.services.core.IUserService;
import femr.common.dtos.CurrentUser;
import femr.common.dtos.ServiceResponse;
import femr.data.models.core.IUser;
import femr.ui.models.sessions.CreateViewModel;
import femr.ui.views.html.sessions.create;
import femr.ui.views.html.sessions.editPassword;
import femr.util.calculations.dateUtils;
import femr.util.stringhelpers.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class SessionsController extends Controller {

    private final FormFactory formFactory;
    private final ISessionService sessionsService;
    private final IUserService userService;

    @Inject
    public SessionsController(FormFactory formFactory, ISessionService sessionsService, IUserService userService) {

        this.formFactory = formFactory;
        this.sessionsService = sessionsService;
        this.userService = userService;
    }

    public Result createGet() {
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        if (currentUser != null) {
            return redirect(routes.HomeController.index());
        }

        return ok(create.render(createViewModelForm));
    }

    public Result createPost() {

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        ServiceResponse<CurrentUser> response = sessionsService.createSession(viewModel.getEmail(), viewModel.getPassword(), request().remoteAddress());

        if (response.hasErrors()) {
            return ok(create.render(createViewModelForm));
        }else{
            IUser user = userService.retrieveById(response.getResponseObject().getId());
            user.setLastLogin(dateUtils.getCurrentDateTime());
            ServiceResponse<IUser> userResponse = userService.update(user, false);
            if (userResponse.hasErrors()){
                throw new RuntimeException();
            }

            DateTime start = new DateTime(user.getPasswordCreatedDate());
            DateTime stop = new DateTime(DateTime.now());
            int daysBetween = Days.daysBetween(start, stop).getDays();

            if(daysBetween > 60){
                user.setPasswordReset(true);
            }

            if (user.getPasswordReset() == true){
                return editPasswordGet(user);
            }
        }

        return redirect(routes.HomeController.index());

    }

    public Result editPasswordGet(IUser user){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);

        return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, new ArrayList<String>()));
    }

    public Result editPasswordPost(){

        final Form<CreateViewModel> createViewModelForm = formFactory.form(CreateViewModel.class);
        CreateViewModel viewModel = createViewModelForm.bindFromRequest().get();
        CurrentUser currentUser = sessionsService.retrieveCurrentUserSession();
        IUser user = userService.retrieveById(currentUser.getId());
        Boolean isNewPassword = false;

        Pattern hasUppercase = Pattern.compile("[A-Z]");
        Pattern hasNumber = Pattern.compile("\\d");
        ArrayList<String> messages = new ArrayList<>();
        if (StringUtils.isNullOrWhiteSpace(viewModel.getNewPassword()))
            messages.add("password is a required field");
        else
        {
            if(viewModel.getNewPassword().length() < 6)        //AJ Saclayan Password Constraints
                messages.add("password is less than 6 characters");
            if (!hasUppercase.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have an uppercase");
            if (!hasNumber.matcher(viewModel.getNewPassword()).find())
                    messages.add("password must have a number");
            if(!viewModel.getNewPassword().equals(viewModel.getNewPasswordVerify()))
                messages.add("passwords do not match");
            //check if new password is equal to the old password
            if(userService.checkOldPassword(viewModel.getNewPassword(),userService.retrieveById(currentUser.getId()).getPassword()))
                messages.add("password must not be the same one used before reset");

        }

        if(!messages.isEmpty())
            return ok(editPassword.render(user.getFirstName(), user.getLastName(), createViewModelForm, messages));
        else
        {
            user.setPassword(viewModel.getNewPassword());
            user.setPasswordCreatedDate(DateTime.now());
            user.setPasswordReset(false);
            isNewPassword = true;
        }

        ServiceResponse<IUser> userResponse = userService.update(user, isNewPassword);
        if (userResponse.hasErrors()){
            throw new RuntimeException();
        }
        return redirect(routes.HomeController.index());
    }

    public Result delete() {
        sessionsService.invalidateCurrentUserSession();

        return redirect(routes.HomeController.index());
    }
}

This is the createForm in ui\views\sessions
@(gcreateForm: Form[femr.ui.models.sessions.CreateViewModel], errorMessage: java.lang.String)

@import femr.ui.views.html.layouts.main
@import femr.ui.controllers.routes.SessionsController
    @styles = {
        <link rel="stylesheet" href="@routes.Assets.versioned("css/login.css")">
    }
@main("Login", styles = styles) {

    @helper.form(action = SessionsController.createPost(), 'class -> "form-signin") {

Please sign in

            @if (!@errorMessage.isEmpty()) {

@errorMessage

            }
            <input type="text" name="email" placeholder="Email" />
            <input type="password" name="password" placeholder="Password" />
            <input type="submit" value="Log in" />

    }
}

HomeController.java
package femr.ui.controllers;

import com.google.inject.Inject;
import femr.common.dtos.CurrentUser;
import femr.business.services.core.ISessionService;
import femr.ui.views.html.home.index;
import femr.ui.views.html.sessions.create;
import play.mvc.Controller;
import play.mvc.Result;

public class HomeController extends Controller {

    private ISessionService sessionService;

    @Inject
    public HomeController(ISessionService sessionService) {
        this.sessionService = sessionService;
    }

    public Result index() {
        CurrentUser currentUser = sessionService.retrieveCurrentUserSession();

        if (null != currentUser) {
            return ok(index.render(currentUser));
        }
        return ok(create.render(null));
    }

}

A: Try using: @if(!errorMessage.isEmpty()) {
Corresponding twirl doc here.

A: 1 - When you have an expression like this you don't need to add the @ on the variable because it is already inside a scala code block.
2 -  errorMessage: java.lang.String, Change your variable type to only String I guess it is better if you use Scala string there may be some differences for the template engine.
@if (!errorMessage.isEmpty()) {

@errorMessage

}


text:
Q: Xamarin Forms: Entry Math Fraction I'm trying to create a Entry that displays an Entry in a fraction style. I really need to do in a way that it gets aligned (numerator, horizontal line below and the denominator below) as the image shows.
The fraction can be in the middle of the formula, so I can't just set Grid.Row to it, because it gets unaligned.
Any ideas?

A: You can simply create your own custom control like this without using any third party library:
FractionEntryControl XAML code
<ContentView
    x:Class="SampleApp.Controls.FractionEntryControl"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Name="this">
    <ContentView.Content>
        <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
            <Frame
                Padding="20"
                BorderColor="DodgerBlue"
                CornerRadius="10">
                <StackLayout Spacing="0">
                    <Entry Text="{Binding Source={x:Reference this}, Path=NumeratorText}" WidthRequest="10" />
                    <BoxView BackgroundColor="Black" HeightRequest="1" />
                    <Entry Text="{Binding Source={x:Reference this}, Path=DenominatorText}" WidthRequest="10" />
                </StackLayout>
            </Frame>
        </StackLayout>
    </ContentView.Content>
</ContentView>

FractionEntryControl Code behind:
public partial class FractionEntryControl : ContentView
{
    public FractionEntryControl()
    {
        InitializeComponent();
    }

    public static BindableProperty NumeratorTextProperty = BindableProperty.Create(nameof(NumeratorText), typeof(string),
            typeof(FractionEntryControl), defaultValue: string.Empty);

    public string NumeratorText
    {
        get { return (string)GetValue(NumeratorTextProperty); }
        set { SetValue(NumeratorTextProperty, value); }
    }

    public static BindableProperty DenominatorTextProperty = BindableProperty.Create(nameof(DenominatorText), typeof(string),
            typeof(FractionEntryControl), defaultValue: string.Empty);

    public string DenominatorText
    {
        get { return (string)GetValue(DenominatorTextProperty); }
        set { SetValue(DenominatorTextProperty, value); }
    }
}

Android Entry Renderer for removing default underline:
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
     base.OnElementChanged(e);
     if (Control != null)
     {
         Control.Background = new ColorDrawable(Android.Graphics.Color.Transparent);
         Control.Gravity = GravityFlags.CenterHorizontal;
     }
}

Use this control in your View:
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
     <control:FractionEntryControl DenominatorText="20" NumeratorText="10" />
</StackLayout>

Output:


text:
Q: Magento 1.9 - setting different prices for sizes of products in different stores? i want to set different prices for the sizes of my products in different stores. I have a configurable products which has a size-attribute. Now I want to set a price of 10 EUR for the "10x10"-option in Store 1 and 20 EUR for the "10x10"-option in Store 2. Now we tried the following module: http://bsscommerce.com/magento-multistore-pricing.html but it can only handle the base price of the confiugrable product and not the different attribute prices.
I am just wondering if we are the only ones which faced the same problem. I know that magento has only the website scope option buildin to differentiate the prices in the catalog but is this the correct solution?
Does someone has a similiar problem or can suggest another module? There is this other module: https://www.magentocommerce.com/magento-connect/store-view-pricing.html but the rating is not that great and the credentials to login in their demo-backend are simply wrong so I can't check my problem in their demo.


text:
Q: undefined method `[]' for nil:NilClass when trying to display metadata in nanoc (Ruby noob)
I'm using nanoc to generate a site. Here is my sample page with metadata:
---
title: abc
parameters:
    abc: def
    ghi: ijk
---

test

I know that I can have parameters one level up but I want to access them in layout file:
<%= @item[:parameters][:abc] %>

but I got following error:
undefined method `[]' for nil:NilClass

Parameters are passed to layout because when I do:
<%= YAML::dump(@item[:parameters]) %>

I can see them. As a Ruby noob I think there's a simple solution to my problem. Also, if you could post a snippet iterating through :parameters hash I would be grateful.

A: You probably have more than one page on your site. Therefore parameters does not exist in the layout for every page nanoc processes. For some pages the element will be nil and hence the error you get.
Perhaps you need to rethink how you want to use those parameters, or then you need a conditional in your layout to look for parameters and only use them when they are present:
<% if @item[:parameters] %>
 <%= @item[:parameters][:abc] %>
<% end %>


text:
Q: Cut section out of UIBlurEffect How can I remove a circular section from a UIBlurEffect.
I have a full page blur and a image with circle buttons.
I want to be able to cut out the section of the blur that covers a particular circle button.


text:
Q: Круговой прогресс бар Как я могу создать этот круговой прогресс-бар с помощью CSS. Это вообще возможно добиться совместимости браузеров - ie10+, ФФ, хром, сафари?
Я думаю мы можем для этого использовать SVG, но я не знаю как это сделать.
По кругу, есть небольшие границы или тени, которые динамически меняются в зависимости от процентного прогресса. Если этот процент составляет 100%, граница будет полностью по кругу заполнять прогресс-бар.

Источник: Circle border progress bar

A: Этот круговой прогресс-бар  является дополнением к моему же предыдущему ответу : круговой прогресс-бар
В этом ответе использован SVG совместно с JS библиотекой Snap.svg для анимации круговой синей строки и счетчика процентов.

var count = $(('#count'));
$({ Counter: 0 }).animate({ Counter: count.text() }, {
  duration: 5000,
  easing: 'linear',
  step: function () {
    count.text(Math.ceil(this.Counter)+ "%");
  }
});

var s = Snap('#animated');
var progress = s.select('#progress');

progress.attr({strokeDasharray: '0, 251.2'});
Snap.animate(0,251.2, function( value ) {
    progress.attr({ 'stroke-dasharray':value+',251.2'});
}, 5000);
body{text-align:center;font-family:sans-serif;background:#080808;}
svg{width:30%;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="animated" viewbox="0 0 100 100">
  <path id="progress" stroke-width="3" stroke="#4596AB" fill="none"
        d="M50 10
           a 40 40 0 0 1 0 80
           a 40 40 0 0 1 0 -80">
  </path>
  <circle cx="50" cy="50" r="38" fill="transparent" stroke="#fff" stroke-width="1"/>
  <text id="count" x="50" y="50" fill="#fff" text-anchor="middle" dy="7" font-size="20">100%</text>
</svg>

Ответил: web-tiki


text:
Q: Turn Laptop screen as Display for Android device with USB trying to understand how things works,
From reading Android site, I know that utilize Secondary display & Presentation

*

*But upon connecting Android device to laptop, how should I make it a USB appear to part of selection.

*Is there anyway I can utilize browser like chrome to display the screen from Andriod device?
I notice Vysor able to do this, how is the big picture works?
thanks


text:
Q: Error opening the .mdf file to app_data I am not able to add .mdf file in App_data(vs 2010 visual studio).
If I right click on App_data and try to add existing item and select mydatabase.mdf and click OK I am getting this error:

The file can not be opened because it is used by another process.Please close all  applications that might access this file and try again.

But I am just running visual studio.

A: Not sure if you have found a solution for this, but I just ran into the same problem. I found some relevant info here:
How to add a new database under app_data with SQL Server Enterprise Edition
From this I gather that adding new AND existing databases (ie the .mdf file) via VS2010 is not possible.
I'm assuming (for this answer) that your end goal was the same as mine, i.e. to use the Microsoft Entity Framework to generate a model class from the database.
As I didn't want to install SQL express just to do this my solution was:
-Create any new db via SQL Server 2008 MGMT studio (or a script if you are that way inclined).
-Add a CONNECTION to the database in VS2010
-When adding a new model using the 'Entity Data Model Wizard' select 'Generate from database' and then select your existing connection, and the relevant table(s).
Worked for me!


text:
Q: Adding a gif to a UIImageView I'm looking to use an animated GIF in my project. Ideally I don't want to use a third party app/API/plugin. I mean if a plugin exists there must surely be a way to program it natively?
All the examples I have looked at involve the aforementioned third party solutions.

A: I've worked with many popular 3rd party gif players and I can tell you that you can probably copy/follow the implementation of a 3rd party library and use it on your own but the thing is, gif playing is a resource hog thing. A well maintained library would definitely be the way to go if you want performance and better resource management.
My suggestion would be FLAnimatedImage


text:
Q: Getting error at clicking a list item C#, Selenium I want to get an element clicked, the element is in a list, i have successfully opened the list but upon clicking  its generating exception. I tried xpath, id and others but its not working.
action.MoveToElement(client.Browser.Driver.FindElement(By.XPath("//button[contains(@id,'notescontrol-action_bar_add_command')]"))).Click();

xrmApp.ThinkTime(5000);

action.MoveToElement(client.Browser.Driver.FindElement(By.XPath("//div[contains(text()),'appointment']"))).Click();

A: I've also had trouble finding elements by text before, using linkText, XPath and others (it was never consistent). I would advise to:
(for example, if you want a button with text "notescontrol")

*

*Get a list of elements by tag name "button":
IWebElement myElement;
IList<IWebElement> listOfButtons = driver.FindElements(By.TagName("button"));

*Then iterate over the list, and find the button you want by checking the text:
foreach(IWebElement element in listOfButtons){
   if(element.contains("notescontrol")){
      myElement = element;
   }
}


text:
Q: Flutter scrolling behavoir I've searching for a solution for this:
I have a headline in my view and I want to show the headline only on top, when I'm scrolling down. This is my current example:

So the blue headline should only appear if I'm scrolling down. Do you have any ideas, how to do this?
Thanks,
Sir!

A: You can use this approach:
Define global variable called isScrollingDown.
Create a function that checks whether the user scrolling down or up.
  void checkScrollDirection() {
    if (scrollController.position.userScrollDirection == ScrollDirection.reverse) {
      isScrollingDown = true;
    } else {
      isScrollingDown = false;
    }
  }

Give this function to your scrollcontroller as a listener.
scrollController.addListener(checkScrollDirection);

After that manage visibility of AppBar with isScrollingDown condition. You can do with either Visibility widget or AnimatedContainer etc.


text:
Q: How to add Conflict handler (or ConflictHook) in AEM 6.1 Jackrabbit Oak has introduced Conflict handlers and ConflictHooks.
I'm wondering if there is a way to add such handler / hook in AEM application. I tried to find something in documentation, but without any success.


text:
Q: $x_p$ is a component of row space? I'm reading a textbook, and author says
"Any vector $\hat{x}$ can be split into a row space component $x_r$ and a nullspace component $x_n$: $\hat{x}=x_r+x_p$
I guess it represents the "Complete solution": $x=x_p+x_n$
Is that right? If so, the particular solution $x_p$ is in row space?

A: So, I suppose we have a matrix $A\in\Bbb R^{N\times M}$, and we want to solve $$Ax=b$$
Then, indeed, if $x_p$ is any solution (named 'particular'), then $A(x-x_p)=0$ is remained to solve, hence in this case, all the solutions are of the form
$$x_p+x_n$$
as you write, where $x_n$ is in the nullspace of $A$.
On the other hand, according to the textbook, every vector $x$ can be written as $x_r+x_n$ where $x_r$ is in the rowspace of $A$ and $x_n$ is in the nullspace. (For this, consider the rowspace and project $x$ orthogonally to it.)
The common point in the above ones is the 'nullspace', and thus we can state not more than

An $x$ is a solution iff its row space component, $x_r$ is a solution.


text:
Q: Change background to a vertical line I try to change a background color to a vertical line when the color change.
So, i have another code and with ta.crossover and ta.crossunder, that works but with this code, don't work.
The error is : An argument of 'series bool' type was used but a 'series float' is expected.
Ok but i need to use integer with the ta.lowest and ta.highest and so not use ta.crossover.
indicator('IS V1', overlay = true)
varLo = input.int(title="Fast (Conversion) Line", defval=9, minval=1, maxval=99999)
varHi = input.int(title="Slow (Base) Line", defval=26, minval=1, maxval=99999)
emafreq = input.int(title="Ema on price frequency", defval=2, minval=1, maxval=99999)

a = ta.lowest(varLo)
b = ta.highest(varLo)
c = (a + b ) / 2

d = ta.lowest(varHi)
e = ta.highest(varHi)
f = (d + e) / 2

//g = ((c + f) / 2)[varHi]
//h = ((highest(varHi * 2) + lowest(varHi * 2)) / 2)[varHi]

z = ta.ema(close, emafreq)

bggreen = (z > c and z > f)
bgred = (z < c and z < f)

is_new_green = not bggreen[1] and bggreen
is_new_red = not bgred[1] and bgred

bgcolor(bggreen ? color.green : bgred ? color.red: na)

plot(ta.crossover(bggreen, bgred) ? high * 10 : na, style=plot.style_histogram, linewidth=1)

How is it possible then to create a vertical line like the last plot line ?
Thanks

A: Why not doing something like this
sincecrossover = ta.barssince(ta.crossover(varLo, varHi))
sincecrossunder = ta.barssince(ta.crossunder(varLo, varHi))

var float a = 0.
var float b = 0.

if sincecrossover > 0
  a := ta.lowest(sincecrossover)

else if sincecrossunder > 0
  b := ta.highest(sincecrossunder)


text:
Q: Trying to get textView to stick to gridView scroll I have a fragment with a textView giving instructions, and below a gridView. I wanted for the textView to scroll upwards with the gridView. In other words: for textView to disappear off screen when gridView is scrolling.
My idea of how to accomplish this is to give the gridView a fixed height that would make the entire layout scrollable - including the textView. However, up until I cannot achieve this. Is there a way to do this?
Layout no scroll:

When scrolled:

Any help/advice would be appreciated.
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/LightGrey"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/chooseLine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="18dp"
        android:text="@string/chooseLine"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <GridView
        android:id="@+id/gridLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="130dp"
        android:fitsSystemWindows="false"
        android:gravity="center"
        android:horizontalSpacing="5dp"
        android:numColumns="auto_fit"
        android:paddingTop="0dp"
        android:stretchMode="columnWidth"
        android:verticalSpacing="25dp" />

</LinearLayout>

A: Achieving this is is not going to be trivial. What you need is ListView's capability to add a header view, but unfortunately, GridView doesn't offer that functionality.
What I have done in the past to solve this problem is to convert the GridView to a ListView, and then add the header to the ListView. I created a wrapper adapter that takes the original adapter and combines a horizontal row's worth of grid cells into a single list row.
The tricky parts include: dynamically adapting the number of columns in a row based on the width of the screen, accounting for all combinations of view types within a row and remaining empty columns in the last row, and handling click interactions properly.

A: Put the whole LinearLayout in a ScrollView (How to use ScrollView in Android?) and for the GridView set android:layout_height="wrap_content"


text:
Q: Is there a simple way to numerically solve interacting fermion systems like for spins? I know that if one has a spin chain of N spins, with the interaction described by some Hamiltonian, one can find the eigenstates and energies by using Kronecker products to write the Hamiltonian as a $(2s+1)^N
\times (2s+1)^N$ matrix and then digonalizing that matrix.
For example, the 1D quantum Ising model:
$H = - \sum_i(J\sigma_i^x\sigma_{i+1}^x+g\sigma_i^z)$
Written out explicitly, where each term is a $2^N \times 2^N$ matrix:
$H = -J(\sigma^x \otimes \sigma^x \otimes I \otimes\cdots \otimes I+ I \otimes \sigma^x \otimes \sigma^x \otimes I \otimes\cdots \otimes I+ \cdots) - g(\sigma^z \otimes I \otimes \cdots \otimes I + \cdots)$
Of course as the system size increases this matrix quickly becomes impossible to diagonalize, but at least the idea is clear.
Does there exist an analogous simple procedure for exactly solving a fermion system given a second quantized Hamiltonian?
I've seem examples of how to solve e.g. the Hubbard model numerically, but it seems like one needs a very ad hoc sort of procedure.
(Addendum: ok, I see how one can solve a fermion system pretty much the same way by having particle/no particle $\leftrightarrow$ spin up/spin down.  But this only works if particle number is not conserved?  So I guess the idea is that step 1 is to look at the Hamiltonian and see if particle number is manifestly conserved or not? (and I suppose if it is conserved, one needs a more complicated method to figure out what the H matrix is?))

A: Yes. Each fermion site is a two-dimensional Hilbert space (since the site can only have either zero or one fermion). Denote $|1\rangle = \begin{pmatrix} 1 \\ 0 \end{pmatrix}$ as the state with the fermion occupied, and $|0 \rangle = \begin{pmatrix} 0 \\ 1 \end{pmatrix}$ as the fermion unoccupied. The creation operator has the action $c^\dagger |0\rangle = |1\rangle$, $c^\dagger |1\rangle = 0$, so $c^\dagger = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$. Likewise, $c = \begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix}$. These operators can almost be tensor product-ed together the same way as you do in the spin case. The "almost" is because fermion operators on different sites anti-commute. To enforce that in the second quantization, you need to attach an $e^{\nu_j}$, where $\nu_j = \sum_{i=1}^{j-1} c_i^\dagger c_i = \sum_{i=1}^{j-1} n_i$, onto the operator at site $j$ (see this, for example, on second quantization). This means that $c_3^\dagger$ should be represented $e^{n} \otimes e^n \otimes c^\dagger \otimes I \otimes I \otimes \ldots$.
Response to addendum: This procedure works fine if the number of particles is conserved. Simply generate the $2N$ possible operators (the $N$ creation operators and $N$ annihilation operators), and then obtain your Hamiltonian via matrix multiplication and addition. However, it brings up an important point, which is relevant if you care about efficiently diagonalizing these sorts of matrices. If our Hamiltonian has some sort of symmetry, then the resulting matrix will be block diagonal. For example, if our Hamiltonian conserves the total number of particles, then any matrix element connecting states with a different number of fermions will be zero. In other words, you can decompose the $2^N$ dimensional matrix into a $1$ dimensional matrix acting on the zero particle state, an $N$ dimensional matrix acting on the $N$ possible single particle states, the ($N$ choose $2$) possible two particle states, and so on, which allows for more efficient diagonalization.


text:
Q: RatingBar not showing correct amount of stars When I have numStars set to '5' I only see 4 stars and when I have it set to 6 I see 5, but then when I vote for the full 5 in app the toast says "6.0" as the rating which is not what I want. Any help would be great, I'm still new to this.
I've tried changing the java code so that it took 1 integer away from the rating, but then when I tried to give 0 stars the toast said -1. I was however getting 5 stars when I had all 5 selected with this method.
            <RatingBar
                android:id="@+id/ratingBar"
                style="@android:style/Widget.DeviceDefault.RatingBar.Small"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:numStars="6"
                android:isIndicator="false"
                android:padding="@dimen/padding_standard"
                android:rating="3.5"
                android:stepSize="0.1"/>

    ratingBar.setOnRatingBarChangeListener
            (new RatingBar.OnRatingBarChangeListener() {
                @Override
                public void onRatingChanged(RatingBar ratingBar,
                                            float rating, boolean fromUser) {
                    String myRating = (getString(R.string.my_rating) +
                            String.valueOf(ratingBar.getRating()));
                    Toast.makeText(getContext(), myRating,
                            Toast.LENGTH_SHORT).show();

When I have 5 numStars I get a visual of 4 stars, but the rating is still out of 5. I want the visual to line up with what my toast displays.

A: In this style is the issue
You defined style :- @android:style/Widget.DeviceDefault.RatingBar.Small
In this style, size is predefined so that only you can't get 6 stars or more in properly. So it starts to adjust in 5 stars.
So you have to change your style or change android:numStars="6" to android:numStars="5"
Then, It will work definitely.
Note:- You can also use this style:- @android:style/Widget.DeviceDefault.RatingBar

A: The padding in RatingBar is the culprit, set paddingVertical and avoid padding or paddingHorizontal


text:
Q: Shiny R: Updating global environment objects from a batch file on a server application? I have a shiny app that continuously runs on a server, but this app uses SQL data tables and needs to check for updates once a day. Right now, with no batch file in place, I have to manually stop the app, run an R script that checks for these updates, then re-run the app. The objects that I want to update are currently stored in RStudio's global environment. I've been looking around at modifying .RData files because I'm running out of options. Any ideas?
EDIT: I'm aware that I probably have to shut down the app for a few minutes to refresh the tables, but is there a way I can do something like this using a batch file?


text:
Q: .Net 6.0 Web Api, Pass empty string as parameter value I'm start work with .Net 6 web api.
I have write a controller very simple:
[Route("[controller]")]
[ApiController]
public class TestController : ControllerBase
{
  [HttpGet,Route("sample")]
  public IActionResult ReturnSample(string ParameterOne, string ParameterTwo)
  {
    [... do something ...]
  }
}

The problem is who all parameter are madatory.
URL: https:///test/sample?ParameterOne=Value&ParameterTwo=Value
Work fine, all OK
URL: https:///test/sample?ParameterOne=Value&ParameterTwo=
ERROR:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-dc73d9983b53750d2073c48bec522c70-98fe251af1accccf-00","errors":{"ParameterTwo":["The ParameterTwo field is required."]}}
How can I allow empty value as valid value for parameter.
Thanks
Lorenzo

A: In C# 8, a Nullable Reference Type Feature was introduced, which helps identify when a type is null and aids in preventing NullExceptions. It essentially gives you CS8618 warnings throughout your code to let you know that you might want to consider changing reference types to be nullable. With that said, this also changes how the compiler interprets the C# code.
This compiler interpretation change requires you to set your optional reference type parameters for your controller endpoint to be nullable. In this case: string?.
This feature is said to be defaulted to disabled, but when I built a .Net 6 project it was enabled (maybe I accidentally clicked a checkbox that enabled it or something when I built the project).

With the Feature Enabled:
Declare the optional string parameters as nullable: string?
public class TestController : ControllerBase
{
  [HttpGet("sample")]
  public IActionResult ReturnSample(string ParameterOne, string? ParameterTwo, string? ParameterThree)
  {
    [... do something ...]
  }
}

This supports the following URLs:
- https://{domainName}/test/sample?ParameterOne=Value
- https://{domainName}/test/sample?ParameterOne=Value&ParameterTwo=Value
- https://{domainName}/test/sample?ParameterOne=Value&ParameterThree=Value
- https://{domainName}/test/sample?ParameterOne=Value&ParameterTwo=Value&ParameterThree=Value
- https://{domainName}/test/sample?ParameterThree=Value&ParameterOne=Value
NOTE: Notice that ParameterOne is in all of the above URLs, this is because it is required, due to NOT being a nullable string string?. In addition, notice that the query parameter order doesn't matter, the controller will map the query to your endpoint's parameter names (this is called Model Binding).

*

*If you don't want the missing query parameters to be interpreted as null when the endpoint is hit, then you can set the string(s) to have default values. Remember when adding default values to a parameter it makes it optional and optional parameters must go at the end of the parameter list (or end of argument):

  [HttpGet("sample")]
  public IActionResult ReturnSample(string ParameterOne, string? ParameterTwo = "test2", string? ParameterThree = "test3")

With the Feature Disabled:
using System.ComponentModel.DataAnnotations;

public class TestController : ControllerBase
{
 [HttpGet("sample")]
  public IActionResult ReturnSample([Required] string ParameterOne, string ParameterTwo, string ParameterThree)
}

NOTE: Notice that the required parameter ParameterOne has the [Required] attribute associated with it. This will require that parameter when the endpoint is called. [Required] comes from the System.ComponentModel.DataAnnotations namespace and is a Validation Attribute. If you want all reference type parameters to be required use [FromQuery]

*

*This endpoint will support the same URLs that are listed above in the Feature Enabled Section.

*If you don't want the missing query parameters to be interpreted as null when the endpoint is hit, then you can set the string(s) to have default values. Remember when adding default values to a parameter it makes it optional and optional parameters must go at the end of the parameter list (or end of argument):
  [HttpGet("sample")]
  public IActionResult ReturnSample([Required] string ParameterOne, string ParameterTwo = "test2", string ParameterThree = "test3")

Enabling/Disable The Nullable Reference Type Feature
WARNING: Enabling/Disabling the Nullable Reference Type Feature will affect how your code is read by the compiler and may incur major side effects. If you are just starting a project, like me, then this change shouldn't affect anything.

*

*Go to your .csproj file (double-click on your project)

*Adjust <Nullable>disable</Nullable> to <Nullable>enable</Nullable> or vice versa.

A: You can set the default value for the second parameter:
[HttpGet,Route("sample")]
public IActionResult ReturnSample(string ParameterOne, string? ParameterTwo = null)
{
   // ...
}

A: If you don't want to send value at all, you can try using ?:
[HttpGet("{ParameterOne?}/{ParameterTwo?}"),Route("sample")]
public IActionResult ReturnSample(string ParameterOne = null, string ParameterTwo = null)
{
 [... do something ...]
}

Note: if you have two parameters and just one of them could have a value, then the second parameter that has value as null should be always in your uri in the end:
[HttpGet("{ParameterOne?}/{ParameterTwo}")] => wrong
[HttpGet("{ParameterTwo}/{ParameterOne?}")] => correct


text:
Q: Undefined variable error php even after variable is set I have defined a variable $userStatus globally in a class, and the value is to be overridden [when a option is selected in drop-down]. The variable is overridden by a session value that is set when the drop-down is changed.
When the session is not set, the function is working fine.. but when the drop-down is changed and the session is set, Undefined variable $userStatus is displayed.
Here is what I tried:
protected $userStatus = 1;

public function export($f3, $params)
{
    if(null !== ($this->f3->get('SESSION.userStatus')))
    {
        $this->$userStatus =  $this->f3->get('SESSION.userStatus');
    }
    $rowID = 5;
    foreach ($results as $result)
       {
          if($this->userStatus == 2)
             {
                //logic
             }
          else{ //.... }
          $rowID++;
       }
}

Here's how the session is set with ajax:
public function updateUserStatus($f3)
    {
        $status = $this->f3->get('POST.status');
        $this->f3->set('SESSION.userStatus', $status);
        echo $status;
    }

NOTE:

*

*export function is run with default $userStatus value.

*when the value is changed, session is set and $userStatus value is supposed to be overridden

*now when the user clicks "Export" button, the export function is run again, with the session value set. that's when the variable is unrecognized.

I just wanted to set a default value for $userStatus, otherwise, it is working fine when the dropdown is changed. Please where did I do wrong?

A: You have a typo.
Change from this
$this->$userStatus

With this:
$this->userStatus

Also change this
if(null !== ($this->f3->get('SESSION.userStatus')))

With this:
if(!empty($this->f3->get('SESSION.userStatus')))


text:
Q: What is wrong with my delete function for Binary Search Tree I have a BST and I want to add/delete/find/inorder_traversal/... on it. But when I want to delete an item, there is a problem.
initialize tree:
node_t *init() {
    node_t *node = calloc(1, sizeof(node_t));
    node->left = NULL;
    node->right = NULL;
    node->data = NULL;
    return node;
}

add() function:
int add(node_t *node, void *data) {
    if (node->data == NULL) { //first time when there is only root node exists
        node->data = data;
        printf("%d -> %p\n", (int)node->data, node);
        return 0;
    }
    node_t *prev = NULL, *ptr;
    ptr = node;
    char type;
    while (ptr) {
        prev = ptr;
        if (data < ptr->data) {
            ptr = ptr->left;
            type = 'l';
        } else
        if (data > ptr->data) {
            ptr = ptr->right;
            type = 'r';
        }
    }
    if (type == 'l') {
        node_t *node = calloc(1, sizeof(node_t));
        node->data = data;
        node->left = NULL;
        node->right = NULL;
        prev->left = node;
        printf("%d -> %p\n", (int)node->data, node);
        return 1;
    } else
    if (type == 'r') {
        node_t *node = calloc(1, sizeof(node_t));
        node->data = data;
        node->left = NULL;
        node->right = NULL;
        prev->right = node;
        printf("%d -> %p\n", (int)node->data, node);
        return 1;
    }
    return -1;
}

del() function:
int del(node_t *node, void *data) {
    if (data < node->data) {
        del(node->left, data);
    } else
    if (data > node->data) {
        del(node->right, data);
    } else
    if (data == node->data) {
        if (node->left == NULL && node->right == NULL) {  // leaf node
            free(node);
            return 0;
        } else
        if (node->left != NULL) {       //node has only left child
            node->data = node->left->data;
            node->left->data = 0;
            free(node->left);
            return 0;
        } else
        if (node->right != NULL) { //node has only right child
            node->data = node->right->data;
            node->right->data = 0;
            free(node->right);
            return 0;
        } else
        if (node->left != NULL && node->right != NULL) { // node has two children
            node_t *temp = min_value(node->right);
            node->data = temp->data;
            del(node->right, data);
            return 0;
        }
    }
    return -1;
}

main():
int main() {
    node_t *tree;
    tree = init();
    add(tree, (void*)40);
    add(tree, (void*)10);
    add(tree, (void*)30);
    add(tree, (void*)25);
    add(tree, (void*)50);
    add(tree, (void*)11);
    add(tree, (void*)76);

    preorder_traversal(tree);
    printf("\n");
    del(tree, (void*)30);
    preorder_traversal(tree);
    printf("\n");
    return 0;
}

before deleting, I run inorder_traversal(), then delete number 30, and again run inorder_traversal(), but the output is as below:
40 10 11 25 30 50 76
40 10 11 0 25 50 76

Guys I would appreciate if you help me.
Also, min_value() function is as below:
node_t *min_value(node_t *node) {
    while (node->left != NULL) {
        node = node->left;
    }
    return node;
}

A: When you free nodes in del you let them in the tree so later when you access them in preorder_traversal or a new call of del etc you have an undefined behavior.
When you free a node you have to remove it from the tree.
You also suppose the data to remove is present in the tree, if this is not the case the two first cases will reach the end of a branch and you will dereference NULL with bad consequences. You need first to check if node is NULL to return
Also in

   else if(node->left != NULL){       //node has only left child

you do not know if node->right is NULL or not, your assumption node has only left child is false
In init you set a first node without data, that has no sense.
I encourage you to modify your add/del function to get a node ** rather than a node allowing you to modify the tree/variable memorizing the root


text:
Q: Develop for Windows Phone 7 (or 7.1) using Visual Studio 2012 (RTM,Premium) Is it possible to get the WindowsPhone 7.1.1 sdk to work with Visual Studio 2012?
Edit: As stated in the title of my question: I wanted to know whether its possible to develop windows phone 7.1.1 apps using Visual Studio 2012.
I already tried installing the SDK and the hotfix but I still can't open Windows Phone 7.1 projects with VS2012. Hence, my question: Am I missing something obvious or is it simply not possbile?

A: There we go :) --> Windows Phone SDK 8.0

A: I have both Visual studio 2012 RTM (for Windows 8 store application development) and Windows phone 7.1.1 SDK in my Windows 8 Release Preview and they are working fine.
And like you, I am also waiting for the Windows Phone 8 SDK.(btw, there is no windows phone 7.8 sdk)
UPDATE: This Windows Phone 8.0 SDK link states that "you can install Windows Phone SDK 7.1 (and the WPSDK 7.1.1 Update) and continue to build apps and games that target Windows Phone 7.5. The existing Windows Phone SDK installs side by side with Visual Studio 2012, and you can feel confident that the code you write today will work on Windows Phone 8 devices."


text:
Q: How do I show that the set $S$ in $\mathbb R^3$ defined by linear inequalities is a $3$-simplex? Consider the set $S$ in $\mathbb R^3$ defined by the inequalities:
$x+y+z \ge 1$
$-x+y+z \le 1$
$x-y+z \le 1$
$x+y-z \le 1$
How can I show that $S$ is a $3$-simplex ? (Convex hull of $3 + 1$ affinely independent points).
I've been looking over a lot of theorems in my book of convex optimization, but I've found none that could be directly applied.
How can I by inspection find these affinely independent points ?

A: The question is whether $S$ is a simplex. Obviously, it is not. The constraint set of 3-simplex in $R^3$ is
$x+y+z=1$
$x,y,z>=0$


text:
Q: Autocomplete not detecting the correct value from object properties Angular I've a huge list of counties and want to implement an auto complete feature.
I'm using the same form to add a new customer or update an existing customer.
Now, the problem is that for adding a new customer, my program works perfectly, but when I updates it, in county dropdown list it show the countyId instead of name.
How do achieve that ?
see the images in order
county schema is as
{
  countyId: number;
  name:string
}

I'm trying with the following code in html
<mat-form-field appearance="outline" fxFlex="50" class="pr-4">
    <mat-label>County</mat-label>
    <input type="text" placeholder="County" name="" matInput formControlName="countyId" [matAutocomplete]="auto">

    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
        <mat-option *ngFor="let county of filteredCounties | async" [value]="county.name">
            {{county.name}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

and in my component file
import { Component, OnInit, Inject, ViewChild, AfterViewInit, ElementRef, ComponentRef } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomerService } from '../../../../services/customer/customer.service';
import { CountyService } from '../../../../services/county/county.service';
import { SubCountyService } from '../../../../services/subCounty/sub-county.service';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import PNotify from 'pnotify/dist/es/PNotify';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-new-customer',
  templateUrl: './new-customer.component.html',
  styleUrls: ['./new-customer.component.scss']
})

export class NewCustomerComponent implements OnInit {
  dataSending = false;
  customerId;
  updatePerson;
  updatedCustomer;
  ready = false;
  dialogView;
  ref: ComponentRef<any>;
  newCustomerForm: FormGroup;
  counties; // list of counties
  subCounties;
  filteredCounties: Observable<string[]>;

  constructor(
    private _formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private customerService: CustomerService,
    private countyService: CountyService,
    private subCountyService: SubCountyService,
    public dialogRef: MatDialogRef<NewCustomerComponent>,
    @Inject(MAT_DIALOG_DATA) public display: any
  ) {
    this.dialogView = display.view;
    this.route.paramMap.subscribe((params) => {
      this.customerId = params.get('customerId');
      if (this.customerId) {
        this.customerService.getCustomer(this.customerId).subscribe((response) => {
          this.updatePerson = response;
          this.newCustomerForm = this._formBuilder.group({
            name: [this.updatePerson.name, Validators.required],
            nationalId: [this.updatePerson.nationalId, Validators.required],
            gender: [this.updatePerson.gender, Validators.required],
            phone1: [this.updatePerson.phone1],
            phone2: [this.updatePerson.phone2],
            bishopName: [this.updatePerson.bishopName, Validators.required],
            bishopPhone: [this.updatePerson.bishopPhone, Validators.required],
            countyId: [this.updatePerson.countyId, Validators.required],
            county: [this.updatePerson.county, Validators.required],
            subCountyId: [this.updatePerson.subCountyId, Validators.required],
            address: [this.updatePerson.address, Validators.required],
            additionalInfo: [this.updatePerson.additionalInfo],
            input1: [this.updatePerson.input1],
            input2: [this.updatePerson.input2],
            defaultingRecord: [''],
          });
          this.ready = true;
        });
      }
      else {
        this.ready = true;
        this.newCustomerForm = this._formBuilder.group({
          nationalId: ['', Validators.required],
          name: ['', Validators.required],
          gender: ['', Validators.required],
          phone1: [''],
          phone2: [''],
          county: [''],
          countyId: ['', Validators.required],
          subCountyId: ['', Validators.required],
          bishopName: ['', Validators.required],
          bishopPhone: ['', Validators.required],
          address: ['', Validators.required],
          additionalInfo: [''],
          input1: [''],
          input2: [''],
          defaultingRecord: [''],
        });
      }
    });
  }

  // tslint:disable:typedef
  ngOnInit() {
    // Getting the list of counties
    this.countyService.getCounties().subscribe((response) => {
      this.counties = response;
      this.newCustomerForm.patchValue({
        county: response
      });
      if (!this.customerId) {

        this.filteredCounties = this.newCustomerForm.get('county').valueChanges.pipe(
          startWith(''),
          map(value => typeof value === 'string' ? value : value.name),
          map(value => this._filter(value))
        );
      }
    }, error => {
      this.counties = [
        {
          "countyId": 63,
          "name": "Mombasa"
        },
        {
          "countyId": 64,
          "name": "Isiolo"
        },
        {
          "countyId": 65,
          "name": "Murang'a"
        },
        {
          "countyId": 66,
          "name": "Laikipia"
        },
        {
          "countyId": 67,
          "name": "Siaya"
        },
        {
          "countyId": 68,
          "name": "Kwale"
        },
        {
          "countyId": 69,
          "name": "Meru"
        },
        {
          "countyId": 70,
          "name": "Kiambu"
        },
        {
          "countyId": 71,
          "name": "Nakuru"
        },
        {
          "countyId": 72,
          "name": "Kisumu"
        },
        {
          "countyId": 73,
          "name": "Kilifi"
        },
        {
          "countyId": 74,
          "name": "Tharaka-Nithi"
        },
        {
          "countyId": 75,
          "name": "Turkana"
        },
        {
          "countyId": 76,
          "name": "Narok"
        },
        {
          "countyId": 77,
          "name": "Homa Bay"
        },
        {
          "countyId": 78,
          "name": "Tana River"
        },
        {
          "countyId": 79,
          "name": "Embu"
        },
        {
          "countyId": 80,
          "name": "West Pokot"
        },
        {
          "countyId": 81,
          "name": "Kajiado"
        },
        {
          "countyId": 82,
          "name": "Migori"
        },
        {
          "countyId": 83,
          "name": "Lamu"
        },
        {
          "countyId": 84,
          "name": "Kitui"
        },
        {
          "countyId": 85,
          "name": "Samburu"
        },
        {
          "countyId": 86,
          "name": "Kericho"
        },
        {
          "countyId": 87,
          "name": "Kisii"
        },
        {
          "countyId": 88,
          "name": "Taita-Taveta"
        },
        {
          "countyId": 89,
          "name": "Machakos"
        },
        {
          "countyId": 90,
          "name": "Trans Nzoia"
        },
        {
          "countyId": 91,
          "name": "Bomet"
        },
        {
          "countyId": 92,
          "name": "Nyamira"
        },
        {
          "countyId": 93,
          "name": "Garissa"
        },
        {
          "countyId": 94,
          "name": "Makueni"
        },
        {
          "countyId": 95,
          "name": "Uasin Gishu"
        },
        {
          "countyId": 96,
          "name": "Kakamega"
        },
        {
          "countyId": 97,
          "name": "Nairobi"
        },
        {
          "countyId": 98,
          "name": "Wajir"
        },
        {
          "countyId": 99,
          "name": "Nyandarua"
        },
        {
          "countyId": 100,
          "name": "Elgeyo-Marakwet"
        },
        {
          "countyId": 101,
          "name": "Vihiga"
        },
        {
          "countyId": 102,
          "name": "Mandera"
        },
        {
          "countyId": 103,
          "name": "Nyeri"
        },
        {
          "countyId": 104,
          "name": "Nandi"
        },
        {
          "countyId": 105,
          "name": "Bungoma"
        },
        {
          "countyId": 106,
          "name": "Marsabit"
        },
        {
          "countyId": 107,
          "name": "Kirinyaga"
        },
        {
          "countyId": 108,
          "name": "Baringo"
        },
        {
          "countyId": 109,
          "name": "Busia"
        }
      ];
    });
    // Getting a list of sub-counties
    this.subCountyService.getSubCounties().subscribe((response) => {
      this.subCounties = response;
    });
  }
  displayFn(county?: any): string | undefined {
    return county ? county.name : undefined
  }
  private _filter(value) {
    console.log('value: ', value);
    const filterValue = value.toLowerCase();
    return this.counties.filter(county => county.name.toLowerCase().indexOf(filterValue) === 0);
  }
  addCustomer(customer) {
    console.log('Value of customer form before setting is: ', this.newCustomerForm.value);
    const selectedCountyId = this.counties.filter(county => county.name === this.newCustomerForm.value.countyId)[0];
    console.log('CountyId: ', selectedCountyId);
    if (!selectedCountyId) {
      PNotify.error({
        title: 'Please selecte a valid county',
        minHeight: '75px'
      });
      return;
    }
    this.newCustomerForm.patchValue({
      countyId: selectedCountyId.countyId
    });
    customer.countyId = selectedCountyId.countyId;
    console.log('Value of customer form after setting is: ', this.newCustomerForm.value);
    this.dataSending = true;
    this.customerService.addCustomer(customer).subscribe((response) => {
      if (this.dialogView) {
        PNotify.success({
          title: 'Customer added Successfully',
          minHeight: '75px'
        });
        this.dialogRef.close();
      }
      else {
        PNotify.success({
          title: 'Customer added Successfully',
          text: 'Redirecting to list page',
          minHeight: '75px'
        });
        this.dataSending = false;
        document.getElementById('submitButton').style.display = 'initial';
        this.router.navigate(['searchcustomer']);
      }

    }, (error) => {
      console.log('Following error occured: ', error);
      PNotify.error({
        title: 'Error occured while adding customer',
        text: 'Failed to add new customer',
        minHeight: '75px'
      });
      this.dataSending = false;
    });
  }

  updateCustomer(customer) {
    this.dataSending = true;
    this.updatedCustomer = this._formBuilder.group({
      customerId: [this.customerId],
      nationalId: [customer.nationalId],
      name: [customer.name],
      gender: [customer.gender],
      phone1: [customer.phone1],
      phone2: [customer.phone2],
      countyId: [customer.countyId],
      subCountyId: [customer.subCountyId],
      address: [customer.address],
      additionalInfo: [customer.additionalInfo],
      bishopName: [customer.bishopName],
      bishopPhone: [customer.bishopPhone],
      input1: [customer.input1],
      input2: [customer.input2],
    });

    this.customerService.updateCustomer(this.updatedCustomer.value, this.customerId).subscribe((response) => {
      PNotify.success({
        title: 'Customer updated Successfully',
        text: 'Redirecting to list page',
        minHeight: '75px'
      });
      this.dataSending = false;
      this.router.navigate(['searchcustomer']);
    }, (error) => {
      console.log('An error occured while updating customer: ', error);
      PNotify.error({
        title: 'Error occured while updating customer',
        text: 'Failed to update customer',
        minHeight: '75px'
      });
      this.dataSending = false;
    });
  }
}

Pictures for better understanding

A: If you feed the autocomplete an id, that is what it will show. In your first image where you say it works, it looks like it works, but in fact it is not storing the countyId when a choice is made, but the name property which you have set as value. I would assume that it is actually the id you want stored there too.
The cleanest solution in my opinion, is to actually store the whole county object. So I would suggest the following:
<input type="text" matInput formControlName="county" [matAutocomplete]="auto">

<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn">
  <mat-option *ngFor="let county of filteredCounties | async" [value]="county">
    {{county.name}}
  </mat-option>
</mat-autocomplete>

with that I removed the countyId formcontrol and instead added county, which stores the whole object and added displayWith to show the name property of the county.
Then modify the valueChanges to check if user has typed or it has been fed an object:
// add the correct name of your form
this.filteredCounties = this.myForm
  .get("county")
  .valueChanges.pipe(
    startWith(""),
    map(value => typeof value === 'string' ? value : value.name),
    map(value => this._filter(value))
  );

and the displayFn which is shown in template:
// don't use 'any' !!
displayFn(county?: any): string | undefined {
  return county ? county.name : undefined
}

So now is only left the option where you want to create the edit form. If you only have the countyId property, you can use find to add the correct object. Here in this sample I set it on creation, but you will maybe use setValue(), but the idea is the same!
// replace 2 with the variable/prop you have the desired id
county: [this.counties.find(x => x.countyId === 2)],

So now you have the whole object. When submitting form and if you only want the countyId from the form control, you can access it by: this.myForm.get('county').value.countyId.
STACKBLITZ with the above code.


text:
Q: How do I enlarge my boxplot?
How can I enlarge my boxplot in jupyter? I can't find any optional parameters that allows me to do so. specifically using seaborn.

A: You can try using rc parameter in seaborn:
sns.set(rc={'figure.figsize':(11,8)})

where (11,8) refers 11 inch width and 8 inch height.
You can also enlarge font by passing font_scale parameter along with style to change background from default. Using example from [seaborn boxplot example][1]:
import seaborn as sns
%matplotlib inline

sns.set(rc={'figure.figsize':(11,8)}, font_scale=1.5, style='whitegrid')

tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips);

Screenshot for result in Jupyter Notebook:
The default with no change would give:

After the change as above would give:


text:
Q: Pagination on with query_posts in custom post type template I know there about a thousand pagination issue questions on here, and I've looked at them, but I can't seem to figure out what's going wrong with mine. This is a loop on a custom post type archive template, but it should call ALL POSTS since I'm using it as a blog. At the very top of the template, is a query for a specific page, but I don't think that's what's causing the problem.
What happens is that on the second page I get a 404 error.
<?php get_header(); ?>
<?php // query post #4606
$post_id = 4606;
$queried_post = get_post($post_id);
$title = $queried_post->post_title;?>
<?php echo $title;?>

<?php $post = $posts[0]; $c=0;
$args = array(
    'post_type'=> 'post',
    'posts_per_page' => 7,
    'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
    );
query_posts($args);
while (have_posts()) : the_post();
?>

<?php $c++;
if( !$paged && $c == 1) :?>
                <?php if ( has_post_thumbnail()) : ?>
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
                        <?php the_post_thumbnail('archive-featured-img', array('class' => 'aligncenter')); ?>

                <?php endif; ?>

<?php else :?>

<?php endif;?>
<?php endwhile; ?>

<?php if (  $wp_query->max_num_pages > 1 ) : ?>

<?php next_posts_link('Next Page »', 0); ?>

<?php previous_posts_link('« Previous Page', 0); ?>

<?php endif; ?>
<?php
wp_reset_query();  // Restore global post data
?>

<?php echo $title;?>

                <?php echo $queried_post->post_content;?>

            <?php dynamic_sidebar( 'Main Blog Page Sidebar' ); ?>

<?php get_footer() ?>

A: @Milo Thanks, the pre_get-posts seems to work perfectly. I was missing that before, thought my choices were between wp_query and query_posts.
The below should ONLY alter the query on the "rg_blog" custom post type archive, right?
function blog_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_post_type_archive('rg_blog')) {
      $query->set('post_type', 'post');
    }
  }
}
add_action('pre_get_posts','blog_filter');


text:
Q: Trigger a HTML-class with external javascript file
I'm using these icons on my webpage: http://fontawesome.io/examples/
One preset class they use for their icons is fa-spin, and it will make the icon spin (du-uh).  I want to make the icons spin whenever they're hovered.
A snippet of my HTML(The class "fa fa-envelope" triggers the icon itself):

Gotta make the fa-spin-class trigger somehow by the function onmouseover, right?
Here's my javascript code, I know that I haven't done anything yet, other than linking the id of the  with the variable x, but I'm kinda lost.
function dothis()
{
var x = document.getElementById ("wantspin")
}

I hope it makes sense, and you get the question. I appreciate any help, insight, tips and tricks, thanks.

A: You can grab the fa-spin rule from font awesome's stylesheet and add a :hover selector:

.spin:hover {
    -webkit-animation: fa-spin 2s infinite linear;
    animation: fa-spin 2s infinite linear
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

A: Chris G's answer is better.  Here is another answer along the same grain of what you were trying to do.  An even better approach would be to look into jquery and use unobtrusive event handlers instead.
You can ignore my HTML, it's just there so the javascript example works.

function dothis() {
  var el = document.getElementById('wantspin');
  if (el) {
    el.classList.add('fa-spin');
  }
}

function dothat() {
  var el = document.getElementById('wantspin');
  if (el) {
    el.classList.remove('fa-spin');
  }
}
#wantspin {
  height: 20px;
  width: 20px;
  background: blue;
}

.fa-spin {
  border: 3px solid red;
}

A: To do this just add and remove the class in the javaScript and add a onmouseout function to your element. Your html will be this (Notice no fa-spin class).

And your javascript.
function dothis() {
    var x = document.getElementById("wantspin");
    x.classList.add("fa-spin");
}
function stopthis() {
    var x = document.getElementById("wantspin");
    x.classList.remove("fa-spin");
}


text:
Q: is there a possible way to check if the document() path exists using XSLT? Im using an XML as a lookup in an XSLT transformation file using the document() function to load the XML in a XSLT variable. Now if the lookup XML is missing the processor throws an error.
Is there a way to prevent or check whether the XML file is existing or not in the specified path in document() (e.g. document('c:\temp\lookup.xml') before assigning it into a variable for usage in the XSLT?

A:
if the lookup XML is missing the processor throws an error.

That is conforming to the specification that states:

If there is an error retrieving the resource, then the XSLT processor may signal an error; if it does not signal an error, it must recover by returning an empty node-set.

I am not aware of any method in XSLT 1.0 that would enable you to override your processor's behavior.


text:
Q: jquery post array data from HTML forms In one of my HTML page, there are a few input fields with the same name attributes since I want to send them as an array to another PHP for back-end transactions.
Suppose the input field like below :
<input type="text" name="language_names[]" value="english">
<input type="text" name="language_names[]" value="french">
<input type="text" name="language_names[]" value="spanish">

Now I want to use Jquery to send this array? I am using the .post() method for this, I know for single value it could be send as {key1: value1, key2:value2...}, but for array How can I do it like this ? I guess it should be close to
{'language_names[]' : $('#input[name="language_names[]"]').val()}

But it doesn't work (I check the request body). Anyone can help ?

A: Use serialize function of jquery like this
// This returns a json representation of your form values
$('#formid').serialize();

A: Or you can also do this :
{'language_names[]' : $('input[name=language_names\\[\\]]').serialize()}

A: Since you need a simple array with the values of those specific input elements, you could use something like:
function getLanguageValues() {
    var language_names = [];
    $.each($("input[name=language_names\\[\\]]"), function (indexInArray, valueOfElement) {
        language_names.push($(valueOfElement).val());
    });
    return language_names;
}

Here is the jsfiddle.


text:
Q: SQL Server 2008 - Removing schema ownership I just created a new web application that accepts some form based input from the user and inserts it in into the database. To go along with this I created a new user in the database and initially assigned the user to two roles and schemas ...
db_datareader
db_datawriter

After thinking things over I realized the user did not need to be part of the db_datareader role because the user only inserted data into the database and never read any. So I went back and removed the role of db_datareader and noticed that the schema options were grayed out. I could not remove the user from schema ownership of db_datareader.
How does one go about removing a user from ownership of a specific schema? Should I have even assigned schema ownership in the first place?
I am logged in as administrator of the SQL Server and of the Windows 7 OS.

A: No, you shouldn't have assigned ownership of the schema to the user. You should have just made the user a member of the schema. Revert ownership to dbo and check that the user account is not still a member of the schema.

A: I had same issue today and found a way to remove user as owner of schema.  Open Schema node below Security in database and change the owner for the user that you mistakenly used with the default owner. For example if some oddball user name is listed as schema owner for db_datareader, change it to dbo (the default) and so on.


text:
Q: How do I Moq It.IsAny for an array in the setup of a method? I'm brand new to Moq (using v 4) and am struggling a little with the documentation.
What I'm trying to do is to Moq a method that takes a byte array and returns an object. Something like:
decoderMock.Setup(d => d.Decode(????).Returns(() => tagMock.Object);

The ???? is where the byte[] should be, but I can't work out how to make it so that I don't care what's in the byte array, just return the mocked object I've already set up.
Moq.It.IsAny expects a generic.
Any help please?

A: Setup Method With Params Array
mock.Setup(m => m.GetFirstTicketInQueueIfMatches(It.IsAny<string[]>()))

A: It.IsAny<byte[]>()

??


text:
Q: I haven't slept well vs I didn't sleep well yesterday? If someone tells you that you look tired?
What do you say?
1- I haven't slept well.
or
2- I didn't sleep well yesterday.

A: You could say either one, though there is some difference between them.

I haven't slept well.

This does not indicate any timeframe. It is possible you did not sleep well for a day, week, month, etc.

I didn't sleep well yesterday.

Here we know it was only one day (yesterday).

A: 1 I haven't slept well.
2 I didn't sleep well.
In 1 your sentence is an explanation of your present appearane. Your sentence refers to the present situation.
In 2 you have in mind a thing in the past.
Both sentences could be used, but I think 1 would be more appropriate.

A: You could say either.
"I haven't slept well" could mean that you didn't sleep well last night or for several nights. As another person explained, it doesn't imply a timeframe.
I would add that the seemingly similar phrase, "I haven't been sleeping well", actually means something different from "I haven't slept well." This is because "I haven't been sleeping well" has a timeframe. It implies that you haven't slept well in at least 3 or so days.
"I didn't sleep well yesterday" means that you only slept badly last night. Although this phrase isn't technically incorrect, and virtually every English speaker would understand it, I would suggest saying "I didn't sleep well last night" because this is more similar to what a native speaker might say.

A: I can't think of any time or way I would ever say "I haven't slept well." If it's been a problem for some time, I would use present perfect continuous:
I haven't been sleeping well.
If it was just the one sleep period, I'm simply say:
I didn't sleep well.
I might add "last night" (although it's already implied), but "yesterday" is odd, unless you are someone who sleeps during the daytime.
I believe that the difficulty with present perfect in the negative is that it is often used to mean you have never done something. For example:
I haven't seen the pyramids.
Means you have never seen them. So saying you haven't slept well could mean that you have never slept well in your entire life. But even if that's what you are trying to say, it's very ambiguous. It leaves me wondering what you mean, anyway. I might use the present perfect if I put an actual time boundary on it:
I haven't slept well, lately.


text:
Q: How can I read the "attributedBody" column in macOS' iMessage database? Apple changed the Messages database schema in the latest macOS Ventura update, and sent messages seem to no longer store their body/content in the text column. The attributedBody column has the content, but it's stored as an encoded blob.
Has anyone had any luck getting plaintext out of this?

A: The attributedBody column is a serialized NSMutableAttributedString — packed using NSArchiver. It can be unpacked and read using NSUnarchiver but must first be extracted from the Messages sqlite database without losing any of its non-printable characters.
To preserve the column's content when performing a query, you can use sqlite3's HEX() function. The resulting bytes can then be read back into their original state by iterating over them and building a new NSString.

In the example below, NSData is extended with two helper methods to handle reading a file with hex-encoded data. Using dataWithContentsOfHexEncodedFile, a message record's attributedBody can be passed to NSUnarchiver, which will handle decoding the serialized NSAttributedString. This can then be converted to a normal NSString by accessing the string property.
#import <Foundation/Foundation.h>

@implementation NSData (NSDataExtended)
+ (NSData *)dataWithContentsOfHexEncodedString:(NSString *) string {
    const char * chars = [string UTF8String];
    int i = 0;

    NSMutableData *data = [NSMutableData dataWithCapacity: string.length / 2];
    char byteChars[3] = {'\0', '\0', '\0'};
    unsigned long wholeByte;

    while (i < string.length) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }

    return data;
}

+ (NSData *)dataWithContentsOfHexEncodedFile:(NSString *) filePath {
    return [self dataWithContentsOfHexEncodedString:[NSString
                                    stringWithContentsOfFile:filePath
                                    encoding:NSUTF8StringEncoding
                                    error:nil]];
}
@end

int main(int argc, const char * argv[]) {
    system([[[NSString alloc] initWithFormat:@"%s %s > %s",
             "/usr/bin/sqlite3 ~/Library/Messages/chat.db",
             "'SELECT HEX(attributedBody) FROM message ORDER BY ROWID DESC LIMIT 1'",
             "/private/tmp/msgbody"] UTF8String]);

#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    NSMutableAttributedString *msg = [[[NSUnarchiver alloc]
                                       initForReadingWithData:[NSData dataWithContentsOfHexEncodedFile:@"/private/tmp/msgbody"]
                                      ] decodeTopLevelObjectAndReturnError:nil];

    NSLog(@"%@", [msg string]);

    return 0;
}


text:
Q: Integration of Spring 5+ Hibernate 5 + Atomikos 4 + Tomcat Unable to locate current JTA transaction I have tried many different solutions, but getting the exception:

org.hibernate.HibernateException: Unable to locate current JTA
  transaction   at
  org.hibernate.context.internal.JTASessionContext.currentSession(JTASessionContext.java:75)
  ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]   at
  org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:465)
  ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]

I am using Atomikos 4.0.4, Hibernate 5.2.12, Spring 5.0.2 and Tomcat.
How to configure Spring 5 + Hibernate 5
This is my configuration
application-context.xml

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            <prop key="net.sf.ehcache.configurationResourceName">/ehcache/ehcache.xml</prop>
            <prop key="hibernate.connection.datasource">java:/comp/env/jdbc/myoracle</prop>
            <prop key="hibernate.transaction.jta.platform">cgaweb.common.atomikos.SpringJtaPlatformAdapter</prop>
            <prop key="hibernate.max_fetch_depth">2</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
            <prop key="hibernate.connection.release_mode">after_transaction</prop>
            <prop key="hibernate.current_session_context_class">jta</prop>
            <prop key="javax.persistence.transactionType">jta</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.id.new_generator_mappings">true</prop>
            <prop key="hibernate.mapping.precedence">class, hbm</prop>
            <prop key="connection.driver_class">oracle.jdbc.OracleDriver</prop>
        </props>
    </property>
</bean>

<!-- jta transaction -->
<bean id="atomikosTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp" init-method="init" destroy-method="shutdownWait" >
<constructor-arg>
    <props>
        <prop key="com.atomikos.icatch.log_base_name">UserTransactionServiceImplog</prop>
    </props>
</constructor-arg>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close" depends-on="atomikosTransactionService">
    <property name="forceShutdown" value="true"/>
    <property name="transactionTimeout" value="300" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp" depends-on="atomikosTransactionService">
    <property name="TransactionTimeout" value="300"/>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionManager" ref="atomikosTransactionManager"></property>
    <property name="userTransaction" ref="atomikosUserTransaction"></property>
    <property name="allowCustomIsolationLevels" value="true"></property>
</bean>
<!-- Manager lookup-->
<bean id="springJtaPlatformAdapter" class="cgaweb.common.atomikos.SpringJtaPlatformAdapter">
    <property name="jtaTransactionManager" ref="transactionManager" />
</bean>

<!-- post construct -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

the code of springJtaPlatformAdapter
public class SpringJtaPlatformAdapter extends AbstractJtaPlatform {

private static TransactionManager sTransactionManager;
private static UserTransaction sUserTransaction;

@Override
protected TransactionManager locateTransactionManager() {
    return sTransactionManager;
}

@Override
protected UserTransaction locateUserTransaction() {
    return sUserTransaction;
}

public void setJtaTransactionManager(JtaTransactionManager jtaTransactionManager) {
    sTransactionManager = jtaTransactionManager.getTransactionManager();
    sUserTransaction = jtaTransactionManager.getUserTransaction();
}

public void setTransactionManager(TransactionManager transactionManager) {
    sTransactionManager = transactionManager;
}

public void setUserTransaction(UserTransaction userTransaction) {
    sUserTransaction = userTransaction;
}

}
i am using tomcat, and i add the following lib :

*

*transaction-jta-4.0.4.jar

*transaction-jdbc.4.0.4.jar

*transaction-hibernate4-4.0.jar

*transaction-api-4.0.4.jar

*transactions-4.0.4.jar

*jta-1.1.jar
can you please help me to solve this issue ?
Thanks

A: The commercial edition of Atomikos contains built-in Tomcat integration and Hibernate 5 support:
https://www.atomikos.com/Main/ExtremeTransactionsFreeTrial
Alternatively, you can wait for the 5.0 release of TransactionsEssentials where Hibernate 5 demos would also be included. I will not have built-in Tomcat integration though.
Best regards


text:
Q: How do you select the entire excel sheet with Range using VBA? I found a similar solution to this question in c# How to Select all the cells in a worksheet in Excel.Range object of c#?
What is the process to do this in VBA?
I select data normally by using "ctrl+shift over arrow, down arrow" to select an entire range of cells. When I run this in a macro it codes out A1:Q398247930, for example. I need it to just be
.SetRange Range("A1:whenever I run out of rows and columns")

I could easily do it myself without a macro, but I'm trying to make the entire process a macro, and this is just a piece of it.
Sub sort()
    'sort Macro
    Range("B2").Select
    ActiveWorkbook.Worksheets("Master").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Master").sort.SortFields.Add Key:=Range("B2"), _
      SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Master").sort
        .SetRange Range("A1:whenever I run out of rows and columns")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

edit:
There are other parts where I might want to use the same code but the range is say "C3:End of rows & columns". Is there a way in VBA to get the location of the last cell in the document?

A: you have a few options here:

*

*Using the UsedRange property

*find the last row and column used

*use a mimic of shift down and shift right

I personally use the Used Range and find last row and column method most of the time.
Here's how you would do it using the UsedRange property:
Sheets("Sheet_Name").UsedRange.Select

This statement will select all used ranges in the worksheet, note that sometimes this doesn't work very well when you delete columns and rows.
The alternative is to find the very last cell used in the worksheet
Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
    Range(Cells(1, 1), rngTemp).Select
End If

What this code is doing:

*

*Find the last cell containing any value

*select cell(1,1) all the way to the last cell

A: Another way to select all cells within a range, as long as the data is contiguous, is to use Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select.

A: I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet.
If so - simply use...
Range("A1").CurrentRegion

A: You can simply use cells.select to select all cells in the worksheet.  You can get a valid address by saying Range(Cells.Address).
If you want to find the last Used Range where you have made some formatting change or entered a value in you can call ActiveSheet.UsedRange and select it from there.  Hope that helps

A: you can use all cells as a object like this :
Dim x as Range
Set x = Worksheets("Sheet name").Cells

X is now a range object that contains the entire worksheet

A: I would recommend recording a macro, like found in this post;
Excel VBA macro to filter records
But if you are looking to find the end of your data and not the end of the workbook necessary, if there are not empty cells between the beginning and end of your data, I often use something like this;
R = 1
Do While Not IsEmpty(Sheets("Sheet1").Cells(R, 1))
    R = R + 1
Loop
Range("A5:A" & R).Select 'This will give you a specific selection

You are left with R = to the number of the row after your data ends. This could be used for the column as well, and then you could use something like Cells(C , R).Select, if you made C the column representation.

A: Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A1", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)

A: Here is what I used, I know it could use some perfecting, but I think it will help others...
''STYLING''

Dim sheet As Range

' Find Number of rows used
Dim Final As Variant
    Final = Range("A1").End(xlDown).Row

' Find Last Column
Dim lCol As Long
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

Set sheet = ActiveWorkbook.ActiveSheet.Range("A" & Final & "", Cells(1, lCol ))
With sheet
    .Interior.ColorIndex = 1
End With

A: I have found that the Worksheet ".UsedRange" method is superior in many instances to solve this problem.
I struggled with a truncation issue that is a normal behaviour of the ".CurrentRegion" method. Using [ Worksheets("Sheet1").Range("A1").CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted).  In this case, the ".CurrentRegion" will truncate at the first record.  I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):
Sub mytest_GetAllUsedCells_in_Worksheet()
    Dim myRange

    Set myRange = Worksheets("Sheet1").UsedRange
    'Alternative code:  set myRange = activesheet.UsedRange

   'use msgbox or debug.print to show the address range and counts
   MsgBox myRange.Address
   MsgBox myRange.Columns.Count
   MsgBox myRange.Rows.Count

  'Copy the Range of data to another sheet
  'Note: contains all the cells with that are non-empty
   myRange.Copy (Worksheets("Sheet2").Range("A1"))
   'Note:  transfers all cells starting at "A1" location.
   '       You can transfer to another area of the 2nd sheet
   '       by using an alternate starting location like "C5".

End Sub

A: Maybe this might work:
Sh.Range("A1", Sh.Range("A" & Rows.Count).End(xlUp))

A: Refering to the very first question, I am looking into the same.
The result I get, recording a macro, is, starting by selecting cell A76:
Sub find_last_row()
    Range("A76").Select
    Range(Selection, Selection.End(xlDown)).Select
End Sub


text:
Q: Can i 3d rotate an image on the Y axis 10-15 degrees from php? From  I want to create
Is this possible with php?

A: Set Perspective of an Image Using PHP GD:
http://www.jqueryit.com/2010/03/set-perspective-of-image-using-php-gd.html
If you have Imagemagick:
http://php.net/manual/en/function.imagick-distortimage.php

A: You can, with imagemagick. Here is the ImageMagick documentation for that kind of processing.

A: You could "fake" the effect by putting a white mask with transparent center corresponding to the desired rotation over the image.


text:
Q: How do I import a 3d object from blender into react and then display it I cant get the object to display within my react webpage.  Or rather I cant find a guide on how to.  If anyone could at least shoot me a reference that would be awesome.
Ive been using three.js to attempt this, but obviously haven't found any luck.