text:
Q: Error setting text to a textView from strings.xml via java code I just want to set a text in a textView from strings.xml using java code but I just can't, eclipse gives me this error: "textView1 cannot be resolved" and "textView2 cannot be resolved".
Here is mi activity:
package com.example.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

public class Descripcion extends Activity{

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.descripcion);

    Intent i = getIntent();

    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);

    switch (position){
    case 0:

    ImageView imageView0 = (ImageView) findViewById(R.id.full_image_view);
    imageView0.setImageResource(imageAdapter.mThumbIds[position]);

    textView1.setText(this,getString(R.string.case0));
    textView2.setText(this,getString(R.string.case0b));

    break;

    case 1:

    ImageView imageView1 = (ImageView) findViewById(R.id.full_image_view);
    imageView1.setImageResource(imageAdapter.mThumbIds[position]);

    textView1.setText(this,getString(R.string.case1));
    textView2.setText(this,getString(R.string.case0b));

    break;
    }
}
}

I've beeing looking for a solution for about 3 hours but I can't fid it.

A: I can't see where you are declaring your TextView's, such as:
TextView textView1 = (TextView)findViewById(R.id.textView1);

A: 1) You didn't define TextView
2) You didn't do findViewById to get corresponding TextView
How to do that?
Your code itself has clues on how to do that, example:
ImageView imageView1 = (ImageView) findViewById(R.id.full_image_view);

Here you defined ImageView and pointed it to R.id.full_image_view defined in layout.xml
like this you need to get TextView, example:
TextView textView1 = (TextView)findViewById(R.id.textView1);

A: You forgot to define the variables textView1 and textView2. Besides that you need to obtain a reference to them using findViewById. Weird part is that you did this for imageView1 and forgot to do it for the TextViews.
Add the following piece of code below etContentView(R.layout.descripcion):
TextView textView1 = (TextView) findViewById(<<-- the id of textView1 -->>);
TextView textView1 = (TextView) findViewById(<<-- the id of textView2 -->>);

A: That's because textView1 and textView2 aren't defined....
You see what you do with the ImageView?
ImageView imageView0 = (ImageView) findViewById(R.id.full_image_view);
You have to apply the same concept to the text views.
TextView textView1 = (TextView) findViewById(R.id.id_of_text_view_1);
TextView textView2 = (TextView) findViewById(R.id.id_of_text_view_2);

Then you can perform operations on that text view, such as setting the text!

A: define your textviews as you did your imageview.
you can use
TextView textView1 = (TextView)findViewById(R.id.textView1);
TextView textView2 = (TextView)findViewById(R.id.textView2);

where
R.id.textView1

is the id of your textview1 in your xml layout
R.id.textVie2

is the id of your textview2 in your xml layout


text:
Q: Cast int to enum in Python for my program? How can a int be cast to an enum in python?

A: You can use the built-in Enum (Python 3.4+), the enum34  backport, or, for more advanced needs (which this is not), the new aenum library.
If you use IntEnum:
class RGB(IntEnum):
    red = 1
    green = 2
    blue = 3

If you have an int and want the matching Enum member:
>>> c = 2
>>> c = RGB(c)
>>> c
<RGB.green: 2>

Once you have an IntEnum member, it is already an int:
>>> type(c)
<enum 'RGB'>
>>> isinstance(c, int)
True

The downside to IntEnum is that every IntEnum member will compare equal to every other IntEnum member that has the same value:
class Fruit(IntEnum):
    banana = 1

>>> Fruit.banana == Color.red
True

If you want to keep your Enums separate, but don't want to lose the intability of an IntEnum you could do:
class RGB(Enum):
    red = 1
    green = 2
    blue = 3
    def __int__(self):
        return self.value

Lookup works the same:
>>> c = 2
>>> c = RGB(c)
>>> c
<RGB.green: 2>

But members are no longer ints:
>>> type(c)
<enum 'RGB'>
>>> isinstance(c, int)
False

So you do have to cast it (or access the value attribute):
>>> int(c)
2
>>> c.value
2

And we no longer have the problem if Fruit.banana being equal to RGB.red:
>>> Fruit(1) == RGB(1)
False

If you are using Python 3+ there are some cool things you can do with aenum, such as:
import aenum

class RGB(aenum.Enum, start=1):
    red
    green
    blue
    def __int__(self):
        return self.value

which results in the same class as the last Enum example.

A: If you want the flexibility to convert between int and an enum, you can use enum.IntEnum
import enum

class Color(enum.IntEnum):
    green = 1
    blue = 2
    red = 3
    yellow = 4

color_code = 4
# cast to enum
color = Color(color_code)

# cast back to int
color_code = int(color)

Note: If you are using python<3.4, enum has been backported, but you will need to install it, e.g. via pip install enum
More on enums in python - https://docs.python.org/3/library/enum.html

A: For here latest Python 3.7 and some Enum:
from enum import Enum

class BatteryState(Enum):
    Unknown = 0
    Unplugged = 1
    Charging = 2
    Full = 3

Convert Int to Enum
just pass int to Enum
batteryStateInt = 2
curBattryState = BatteryState(batteryStateInt)
print("curBattryState=%s" % curBattryState)

can got what you expected Enum:
curBattryState=BatteryState.Charging

Extra
get Enum string expression can via name
curBattryStateName = curBattryState.name
print("curBattryStateName=%s" % curBattryStateName)

can got expected: Charging

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS Not going well nth-of-type
I want to be able to get the divs by calling them "first, second, third" via nth-of-type
now the problem is that this works:
.box:nth-of-type(1)
.box:nth-of-type(3)
.box:nth-of-type(5)

But I don't understand why I can't call them like that:
.box:nth-of-type(1)
.box:nth-of-type(2)
.box:nth-of-type(3)

It's going like this:

The problem is get fixed when I removing the two dividers which go between them (There are 2 divs called "divider") so I can call them like 1, 2, 3 but why should I need to call them 1, 3, 5 with the dividers? Also when I change the divs to whatever else like p or h1, etc... its okay and I can call them 1, 2, 3
Thank you for your help!

A: :nth-of-type is relative to siblings elements with the same tag name. It has no notion of classes.
So the .box:nth-of-type(X) selector is only satisfied when:

*

*The element has the box class and

*Its position relative to its siblings which have the same tag name satisfy the nth-of-type rule.

Solution: switch either your box or divider elements to another tag and it will work as you expected.
Demo

.divider { margin:0; }
.box:nth-of-type(1) {
  /* custom styling for the .box which is
   * the first element among its siblings which have the same tag name (div)
   */
}
.box:nth-of-type(2) { /* same now for the 2nd */ }
.box:nth-of-type(3) {}

You might as well want to change the selector to div.box:nth-of-type(X) just to make it more clear that the nth-of-type relation is with div elements.
Note: of course, adding another div before the .boxes will break these nth-of-type rules. So you have to be careful when using this selector, as changing the DOM structure may affect your styling.
A sturdy alternative which is commonly used (for those paranoid about future changes to the DOM structure, like me) is to apply a modifier class (following the BEM methodology):

.box { /*base style for all boxes here*/ }
.box--1 { /* custom styles for the box--1 */ }

A: nth-of-type works with types not classes. So when you use it with a class it will find the type of the class and use it to find the element.
Like in your case it will evaluate the type of .box to div and then find 1, 2 and 3 or 1, 3 and 5 if you use divider.

A: Nth-of-type only selects based on element type. You cant select classes, so at it is only looking at divs.
From quirksmode:

:nth-of-type() works the same, except that it only considers element of the given type ( in the example).

http://quirksmode.org/css/selectors/nthchild.html
Since you already gave the ones you want to select a class, why not just use .box as your selector with no pseudo class?


text:
Q: Android:position of an element in a scrollable window I have 20 buttons in vertical layout in a scrollable window. While click on a button I want to know the position of that button on screen.Some times I click the button after a scrolling.I want the exact position at that time too.What is the code for that.please help me.

A: Never use 20 buttons inside layout. Use listview with button and use onitem click of listview and get button position:
list view onitem click:
listId.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
          -------Here position displays **pos**----
       }
    });

Refer this example for a nice listview sample

A: lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                System.out.println("this is position"+lv.getItemAtPosition(arg2)

            }
        });


text:
Q: Axios Interceptor (Response) doesn't update the header In my react application, I am trying to implement silent refresh for the access token I use for my requests. Everything related to the Axios request interceptor setting Authorization header is working fine. However, when I get a 401 response from the backend I retry the original request after making a refresh token request and setting the new header. I get the below error
    react_devtools_backend.js:4012 DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function(header, parser) {
    header = normalizeHeader(header);
    if (!header)
      return void 0;
    const key = findKey(this, header);
    if (key) {
      const value = this[key];
      if (!parser) {
        return value;
      }
      if (parser === true) {
        return parseTokens(value);
      }
      if (utils_default.isFunction(parser)) {
        return parser.call(this, value, key);
      }
      if (utils_default.isRegExp(parser)) {
        return parser.exec(value);
      }
      throw new TypeError("parser must be boolean|regexp|function");
    }
  }' is not a valid HTTP header field value.
    at setRequestHeader (http://localhost:5173/node_modules/.vite/deps/axios.js?v=18256307:1209:17)
    at Object.forEach (http://localhost:5173/node_modules/.vite/deps/axios.js?v=18256307:89:10)
    at dispatchXhrRequest (http://localhost:5173/node_modules/.vite/deps/axios.js?v=18256307:1208:21)
    at new Promise (<anonymous>)
    at xhrAdapter (http://localhost:5173/node_modules/.vite/deps/axios.js?v=18256307:1112:10)
    at Axios.dispatchRequest (http://localhost:5173/node_modules/.vite/deps/axios.js?v=18256307:1425:10)
    at async NotFound404.useQuery.retry [as queryFn] (http://localhost:5173/src/pages/404.tsx?t=1669973204409:60:12)

Here is the Axios client
import axios from "axios";

export const APIClient = axios.create({
    baseURL: "http://localhost:5050/api",
    withCredentials: false,
});

Here you can find the react custom hook I used, it has both the request and the response Axios interceptors
import { AxiosRequestConfig, AxiosResponse } from "axios";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { APIClient } from "../api";
import { requestRefresh, selectToken, useAppDispatch } from "../store";

export const useAPIClient = () => {
    // react router related
    const navigate = useNavigate();

    // react redux store related
    const dispatch = useAppDispatch();
    const token = useSelector(selectToken);

    const APIRequestIntercept = APIClient.interceptors.request.use(
        (config: AxiosRequestConfig) => {
            // Do something before request is sent
            if (
                config?.headers !== undefined &&
                (token !== "" || token !== null)
            ) {
                if (config.headers !== undefined) {
                    config.headers["Authorization"] = `Bearer ${token}`;
                }
            }

            return config;
        },
        (error) => {
            // Do something with request error
            return Promise.reject(error);
        }
    );

    const APIResponseIntercept = APIClient.interceptors.response.use(
        (response: AxiosResponse<any, any>) => {
            // Any status codes that fails outside the range of 2xx cause this function to trigger
            // Do something with response error
            return response;
        },
        async (error) => {
            // Any status codes that falls outside the range of 2xx cause this function to trigger
            // Do something with response error
            if (error?.response && (token !== "" || token !== null)) {
                const prevRequest = error?.config;

                if (error?.response.status === 401 && !prevRequest?._retry) {
                    // refresh the access token and set the auth store state
                    // dispatch refresh async action and it will set the new token
                    const response: any = await dispatch(
                        requestRefresh()
                    ).unwrap();

                    // start to resend the previous failed request
                    prevRequest._retry = true;

                    // set the prevRequest headers
                    prevRequest.headers[
                        "Authorization"
                    ] = `Bearer ${response.data.accessToken}`;

                    // return the previous request
                    return APIClient(prevRequest);
                } else if (error?.response.status === 403) {
                    // navigate the user to sign in page
                    navigate("/sign_in", { replace: true });
                    return;
                } else {
                    return Promise.reject(error);
                }
            } else {
                return Promise.reject(error);
            }
        }
    );

    return APIClient;
};

I made I simple request using the APIClient instance with React Query in a component
import { useAPIClient } from "../hooks";

export function SimpleComponent() {
    // API request related
    const apiClient = useAPIClient();

    useQuery(
        ["dummy"],
        async () => {
            return await apiClient.get("/auth/dummy_json");
        },
        {
            retry: false,
            onSuccess: (response) => {
               console.log("res: ", response);
            },
            onError: (error) => {
               console.log("error: ", error);
            },
        }
    );

    return (
Simple Component
);
}


text:
Q: Card game repeating cards I have this game of War and it works great, but the cards that have been payed repeat themselves.  Each card should only display once per game. How do I get my used cards to display only once?
Here is my code:
$(document).ready(function () {
var used_cards = new Array();

var player_cards = new Array();
var slick_cards = new Array();
var playerName="";
var count = 0;
document.getElementById("play").disabled = true;

var P_hand = {
    cards: new Array()
}
var S_hand = {
    cards: new Array()
}
var Hand = {
    cards: new Array()
}

Deck of card variables:
var deck = [
    new card('Ace', 'Hearts', 11, 142),
    new card('Two', 'Hearts', 2, 22),
    new card('Three', 'Hearts', 3, 32),
    new card('Four', 'Hearts', 4, 42),
    new card('Five', 'Hearts', 5, 52),
    new card('Six', 'Hearts', 6, 62),
    new card('Seven', 'Hearts', 7, 72),
    new card('Eight', 'Hearts', 8, 82),
    new card('Nine', 'Hearts', 9, 92),
    new card('Ten', 'Hearts', 10, 102),
    new card('Jack', 'Hearts', 10, 112),
    new card('Queen', 'Hearts', 10, 122),
    new card('King', 'Hearts', 10, 132),
    new card('Ace', 'Diamonds', 11, 141),
    new card('Two', 'Diamonds', 2, 21),
    new card('Three', 'Diamonds', 3, 31),
    new card('Four', 'Diamonds', 4, 41),
    new card('Five', 'Diamonds', 5, 51),
    new card('Six', 'Diamonds', 6, 61),
    new card('Seven', 'Diamonds', 7, 71),
    new card('Eight', 'Diamonds', 8, 81),
    new card('Nine', 'Diamonds', 9, 91),
    new card('Ten', 'Diamonds', 10, 101),
    new card('Jack', 'Diamonds', 10, 111),
    new card('Queen', 'Diamonds', 10, 121),
    new card('King', 'Diamonds', 10, 131),
    new card('Ace', 'Clubs', 11, 143),
    new card('Two', 'Clubs', 2, 23),
    new card('Three', 'Clubs', 3, 33),
    new card('Four', 'Clubs', 4, 43),
    new card('Five', 'Clubs', 5, 53),
    new card('Six', 'Clubs', 6, 63),
    new card('Seven', 'Clubs', 7, 73),
    new card('Eight', 'Clubs', 8, 83),
    new card('Nine', 'Clubs', 9, 93),
    new card('Ten', 'Clubs', 10, 103),
    new card('Jack', 'Clubs', 10, 113),
    new card('Queen', 'Clubs', 10, 123),
    new card('King', 'Clubs', 10, 133),
    new card('Ace', 'Spades', 11, 144),
    new card('Two', 'Spades', 2, 24),
    new card('Three', 'Spades', 3, 34),
    new card('Four', 'Spades', 4, 44),
    new card('Five', 'Spades', 5, 54),
    new card('Six', 'Spades', 6, 64),
    new card('Seven', 'Spades', 7, 74),
    new card('Eight', 'Spades', 8, 84),
    new card('Nine', 'Spades', 9, 94),
    new card('Ten', 'Spades', 10, 104),
    new card('Jack', 'Spades', 10, 114),
    new card('Queen', 'Spades', 10, 124),
    new card('King', 'Spades', 10, 134)
];

Functions:
    function card(name, suit, value, trump) {
        this.name = name;
        this.suit = suit;
        this.value = value;
        this.trump = trump;
    }

    $("#newPlayer").click(function(){
            var newPlayer = prompt("Please enter your name.","");
            playerName = newPlayer;
            if(newPlayer != null){
                document.getElementsByClassName("pName")[0].innerHTML = newPlayer;
                document.getElementsByClassName("pName")[1].innerHTML = newPlayer+":";
            }
        });

     $("#deal").click(function(){
        if(playerName == ""){
            var newPlayer = prompt("Please enter your name.","");
            playerName = newPlayer;
            if(newPlayer != null){
                document.getElementsByClassName("pName")[0].innerHTML = newPlayer;
                document.getElementsByClassName("pName")[1].innerHTML = newPlayer+":";
            }
        }
        document.getElementById("pHandImg").src = "";
        document.getElementById("cHandImg").src = "";
        document.getElementById("play").disabled = false;
        document.getElementById("cardCount").innerHTML = 26;
        document.getElementById("cScore").innerHTML = "";
        document.getElementById("pScore").innerHTML = "";
        document.getElementById("win").innerHTML = "";
    });

    $("#play").click(function(){

        debugger;
        var cardcount = parseInt(document.getElementById("cardCount").textContent);
        if(cardcount == 1){
            document.getElementById("cardCount").innerHTML = cardcount-1;
            var pScore = parseInt(document.getElementById("pScore").textContent);
            var cScore = parseInt(document.getElementById("cScore").textContent);
            if(pScore > cScore){
                document.getElementById("pHandImg").src = "./images/other/check.png";
                document.getElementById("win").innerHTML = "Congrats "+playerName + " Won Game";
            }
            if(pScore < cScore){
                document.getElementById("pHandImg").src = "./images/other/x.png";
            }
            if(pScore < cScore){
                document.getElementById("cHandImg").src = "./images/other/check.png";
                document.getElementById("win").innerHTML = "Congrats  slick Won Game";
            }
            if(pScore > cScore){
                document.getElementById("cHandImg").src = "./images/other/x.png";
            }

            document.getElementById("play").disabled = true;
        }else{
            if(count > 0){
                document.getElementById("cardCount").innerHTML = cardcount-1;
            }
            pItem = deck[Math.floor(Math.random() * deck.length)];
            sItem = deck[Math.floor(Math.random() * deck.length)];
            player_cards.push(pItem);
            slick_cards.push(sItem);
            used_cards.push(sItem,sItem);
            pSrc = "./images/"+pItem.suit+"/"+pItem.name+".jpg";
            sSrc = "./images/"+sItem.suit+"/"+sItem.name+".jpg";
            document.getElementById("pHandImg").src = pSrc;
            document.getElementById("cHandImg").src = sSrc;
            pValue = pItem.value;
            sValue = sItem.value;
            val = pValue + sValue;
            var pScore = parseInt(document.getElementById("pScore").textContent);
            if(!pScore){
                pScore = 0;
            }
            var cScore = parseInt(document.getElementById("cScore").textContent);
            if(!cScore){
                cScore = 0;
            }
            if(pValue > sValue){
                document.getElementById("pScore").innerHTML = pScore + val;
            }
            if(pValue < sValue){
                document.getElementById("cScore").innerHTML = cScore + val;

            }
        }
        count++;
    });

});

A: I am not sure what are pItem and sItem and used_cards and slick_cards but for example if you want to check if sItem not used before in used_cards (and similar for pItem and slick_cards) then before consuming the new cards generate new items in a loop until you make sure that they are not used before:
var usedBefore=false;
while (!usedBefore){
    sItem = deck[Math.floor(Math.random() * deck.length)];
    if (used_cards.includes(sItem)){
        usedBefore=true;
    }
}
//Then do other stuff

A: Just add a played property to each card to keep track of them:

const suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
const ranks = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Jack', 'Queen', 'King']

function card(rank, suit, value, trump) {
  this.rank = rank;
  this.suit = suit;
  this.value = value;
  this.trump = trump;
  this.played = false
}

let cards = []
ranks.forEach(rank => {
  suits.forEach(suit => {
    cards.push(new card(rank,suit,10,10))
  })
})

//sets every King to played
cards.forEach(card => card.played = card.rank === 'King' ? true : false )
console.log(cards.filter(card => card.played))


text:
Q: JToolBarHelper :: DeleteList - Does not work I created a Joomla 2.5 custom component and load data to grid on administrator side. All data loaded and adding and editing work well. But deleting is not working. It gives following error.
Fatal error: Call to a member function delete() on a non-object in
C:\wamp\www\Joomla\libraries\joomla\application\component\controlleradmin.php on line 131

In view class I used JToolBarHelper for delete action as follows.
JToolBarHelper::deleteList('', 'regions.delete', 'JTOOLBAR_DELETE');

A: I had this problem myself, and I've just figured it out. Look into your file corresponding to admin/controllers/helloworlds.php, there should be this line:
public function getModel($name = 'HelloWorld', $prefix = 'HelloWorldModel')

The first param's default value is the name of a single item (in your case, probably Region) and the second one contains the name of the component. So it  should be:
public function getModel($name = 'Region', $prefix = 'NameOfYourComponentModel')

I hope this helps also in your case. In the HelloWorld example, they use HelloWorld all over the code, both as the name of the component and the main view, so it's sometimes hard to distinguish which one is what.


text:
Q: Checkstyle is not working while building the project in eclipse I am facing checkstyles issue while building the project. Please guide me based on my below error message as soon as possible.
Errors occurred during the build:

Errors running builder 'Checkstyle Builder' on project 'CMS'.
cannot initialize module TreeWalker - Unable to instantiate   ReturnNullInsteadOfBoolean
         cannot initialize module TreeWalker - Unable to instantiate ReturnNullInsteadOfBoolean
         cannot initialize module TreeWalker - Unable to instantiate ReturnNullInsteadOfBoolean
         cannot initialize module TreeWalker - Unable to instantiate ReturnNullInsteadOfBoolean

A: ReturnNullInsteadOfBoolean is not part of the core Checkstyle distribution.  Instead, it is part of SevNTU - which is typically not installed into Eclipse by default.
In Eclipse, under the "Help" menu, select "Install New Software...".  Search for "EclipseCS SevNTU plugin feature", check its box, then install.
This may also appear as "Extension for eclipse-cs plugin with additional Checks".
See also: Error while installing check style plugin for eclipse
Please comment back if this still doesn't work for you.


text:
Q: How to adjust grandparent style for only one child element and then reset back to normal? I am wanting #homeContainer to have the full width of the page. A grandparent element is controlling the width and margin.
Below is the DOM. When I uncheck margin: 0 auto the full width is achieved. How can I control the .p-body-inner code for only code associated with #homeContainer?
I tried adding this line of JS. It takes off the margin for .p-body-inner but it isn't for only `#homeContainer. It does it for the entire page and I only want it for that section then to revert back to normal.
For anyone wanting to see this, the actual site is: https://stangline.com/ewr-porta/

document.querySelector('#homeContainer').closest('.p-body-inner').style.margin = '0';
.p-body
{
    display: flex;
    align-items: stretch;
    flex-grow: 1;
    min-height: 1px;
  background: gray;
}
.p-body-inner
{
    display: flex;
    flex-direction: column;
    width: 100%;
  max-width: 1200px;
  padding: 0 10px;
  margin: 0 auto;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
  padding-bottom: 20px;
}
.p-body-main
{
    display: table;
    table-layout: fixed;
    width: 100%;
    margin-bottom: auto;
    min-height: 1px; // IE11 workaround - related to #139187
}
#homeContainer {
    width: 100vw;
    height: 100px;
  background: red;
  border: 5px solid green;
}
#reset {
  width: 300px;
  border: 5px solid blue;
}

      Need full width of .p-body

      This should be centered and inherit the margin: 0 auto again.

A: I think you are adding margin: 0 auto into wrong element...
And with display: flex; children will fill the width automatically hens you don't need specify width: 100%

.p-body
{
    display: flex;
    align-items: stretch;
    flex-grow: 1;
    min-height: 1px;
  background: gray;
}
.p-body-inner
{
    display: flex;
    flex-direction: column;
    width: 100%;
  max-width: 1200px;
  padding: 0 10px;
  margin: 0 auto;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
  padding-bottom: 20px;
}
.p-body-main
{
    display: table;
    table-layout: fixed;
    width: 100%;
    margin-bottom: auto;
    min-height: 1px; // IE11 workaround - related to #139187
}
#homeContainer {
  height: 100px;
  background: red;
  border: 5px solid green;
}
#reset {
  width: 300px;
  border: 5px solid blue;
  margin: 0 auto;
}

      Need full width of .p-body

      This should be centered and inherit the margin: 0 auto again.


text:
Q: Summing Rows by grouping two columns in R I have a data base of firearm background checks conducted the original data had months but not in separate columns so I changed the column name to years and now have 12 rows for each year for each state. I would like to summarize the total checks conducted in the other columns by using state and year. I've tried some variations of group_by and summarize and also aggregate. When i ran
gunData <-aggregate(.~year+state,gunData, sum)

It seemed to work but erased most of the years and states. Is there a limit on the amount of variables that can get aggregated any help is appreciated.
 year state                permit permit_recheck handgun long_gun other multiple totals
   <dbl> <chr>                 <dbl>          <dbl>   <dbl>    <dbl> <dbl>    <dbl>  <dbl>
 1  2021 Alabama               31803            512   20970    16026  1548      959  74710
 2  2021 Alaska                  222              1    3055     2564   375      189   6667
 3  2021 Arizona                9290           1159   20530     9991  1754     1114  45496
 4  2021 Arkansas               3123           1152    7068     5289   448      390  18916
 5  2021 California            16025          11953   40789    27915  6499        0 119784
 6  2021 Colorado              10891              6   21729    13839  1960     1760  50485
 7  2021 Connecticut            9792            476    6046     1996  1438        0  19748
 8  2021 Delaware                353              0    2775     1563   158      153   5245
 9  2021 District of Columbia    538              1     304        4     0        2    920
10  2021 Florida               31875              0   66307    26720  5116     2894 138870
# ... with 14,730 more rows

Here is a table with the months labeled maybe it will help explain what i mtryign to do
A tibble: 14,740 x 10
   year  month state                permit permit_recheck handgun long_gun other multiple totals
   <chr> <chr> <chr>                 <dbl>          <dbl>   <dbl>    <dbl> <dbl>    <dbl>  <dbl>
 1 2021  02    Alabama               31803            512   20970    16026  1548      959  74710
 2 2021  02    Alaska                  222              1    3055     2564   375      189   6667
 3 2021  02    Arizona                9290           1159   20530     9991  1754     1114  45496
 4 2021  02    Arkansas               3123           1152    7068     5289   448      390  18916
 5 2021  02    California            16025          11953   40789    27915  6499        0 119784
 6 2021  02    Colorado              10891              6   21729    13839  1960     1760  50485
 7 2021  02    Connecticut            9792            476    6046     1996  1438        0  19748
 8 2021  02    Delaware                353              0    2775     1563   158      153   5245
 9 2021  02    District of Columbia    538              1     304        4     0        2    920
10 2021  02    Florida               31875              0   66307    26720  5116     2894 138870


text:
Q: If SOAP is now considered overengineered over REST why isn't WCF? I'm amazed that years over years IT pretend to simplify communication or software design and a few years later it declare it was over-engineered. EJB, SOAP, so looking at all the WCF stuffs do we as users (not as Microsoft or IBM who need to sell new stuffs) really need it ?
Update: this is a concrete example
http://www.go4answers.com/Example/expert-interoperability-issues-ws-736.aspx
The guy knows how to call a server with WS-Security using old soap and in WCF it seems it doesn't really help and worst it seems even more complicated as it is said:
"WCF has still some limitation - not all WS-Security configuration  are possible without custom development."
Nobody seems to be able to have found a solution.
So can people instead of mere opinions give concrete examples (with source code both in wcf and in soap or rest for comparison) of hard problems (and not easy problems) that can be solved by WCF more easily than can be with traditional soap ?

A: What I like about WCF is that it can be as simple or as complex as you want it to be. I also really appreciate the separation between contract and binding, where you can clearly define your operations and have the option of choosing which transport to use.

A: WCF is meant to make a developer's life easier. You can re-write the logic for a service, auto-wire multiple endpoints, and voila...your logic is available via SOAP, REST, Named Pipes, etc.
Unfortunately it's not as easy as it was all made to sound. Personally, though, I still find it a useful tool for re-using my code.
If you really want to jump on the bandwagon and say that REST/JSON is the only way to go...then WCF will definitely seem over-engineered. ASP.NET MVC does a great job at RESTful JSON services if you don't want to deal with the WCF overhead.

A: With 4.0, they've simplified configuration. I find it very easy to do this. But realize WCF is designed to make a lot of the internals of communication between services transparent. You don't care if its SOAP, REST, etc. All you do is write your service and "hook them up". COde for my services is exactly like I'd write normal code, with the exception of a couple of attributes added to the class and methods and some configuration (with 4.0, very simple imho)


text:
Q: Repeated password requests on Ubuntu after reboot. Sudo/admin privileges seem to be revoked after reboot I am running Jakeday's Surface Pro Ubuntu build and I dual boot Windows 10 and Ubuntu.
Each time I reboot, when I log in to my admin user I get 4 prompts, two each (shown below), for my password.
System policy prevents control of network connections
An application is attempting to perform an action that requires privileges. Authentication as one of the users below is required to perform this action

Authentication is required to create a color managed device
An application is attempting to perform an action that requires privileges. Authentication as one of the users below is required to perform this action

I am also prompted for admin password when opening network manager, when I plug in a USB and several other tasks. I have also noticed that in settings that I cannot unlock my users. I reviewed my groups and I appear to be a member of admin and sudo. And my sudo password works when I enter it for the prompts. I checked ownership of my /home directory and found no issues there.
I can log in and out of my user several times and eventually (the number of log in / log out varies) the prompts stop and I have access/permission to all elements listed above.
I use Chrome Remote Desktop, and I set it up following these instructions: https://superuser.com/questions/778028/configuring-chrome-remote-desktop-with-ubuntu-gnome-14-04/850359#850359
I did a fresh install of Ubuntu on a different partition and I did not encounter the issue, but I also did not reinstall all the programs I have on my current primary use partition. I recently started encountering the same issue on a desktop I have set up at work.
I would really like to avoid a fresh install, and I use Chrome Remote Desktop regularly. I have spent three weeks reading through suggestions with no luck. Any suggestions are welcome!


text:
Q: Hibernate @OneToMany without a separate join table Consider the following database schema:
create table UserGroup ( id int not null auto_increment, name varchar(200),
    primary key(id));
create table User ( id int not null auto_increment, name varchar(200),
    groupId int not null, primary key(id));

User.groupId = UserGroup.id, so a user can only be a member of one group, but a usergroup can exist of many users. Fine so far, let's make the entities in Hibernate.  Here's User:
@Entity
@Table(name = "User")
public class User {

    @Id
    @Column(name="id", nullable = false)
    private Integer id;

    @Column(name="name", length = 200, nullable = true)
    private String name;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "groupId", nullable = false, insertable=false, updatable=false)
    @ForeignKey(name="FK_GroupId")
    private UserGroup userGroup;

    /* Getters, Setters, toString, equals & hashCode */
}

Here's UserGroup:
@Entity
@Table(name = "UserGroup")
public class UserGroup {

    @Id
    @Column(name="id", nullable = false)
    private Integer id;

    @Column(name="name", length = 200, nullable = true)
    private String name;

    @OneToMany(fetch=FetchType.EAGER)
    private List<User> users;

    /* Getters, Setters, toString, equals & hashCode */
}

Now I'll get an error "Table mydb.usergroup_user' doesn't exist" because it expects a join-table. My data structure is "set in stone" due to interoperability with other applications that this application will replace, so I won't be making a join-table. Also, it should not be needed. How can I make a List<User> users that simply is a list of User where User.groupId == UserGroup.Id?

A: I think you need the mappedBy="UserGroup" in the @OneToMany annotation.


text:
Q: Might have deleted kernel - where do I install grub? Ubuntu 14.04 LTS
I might have deleted the Kernel whilst trying to delete 10GB of old kernels.  I haven't switched the PC off yet.
@Karel suggests an answer in a virtually identical question: Might have deleted kernel, but haven't shut off computer yet but it is vague on how to find grub (boot menu) device.  I don't have enough reputation to comment there.
His answer:
sudo apt-get install --reinstall linux-image-generic
sudo grub-install /dev/sdX
sudo update-grub

Disks program shows that, I have one SSD (device sda), split thus:
|             | Extended Partition |             |
|             |     Partition 3    |             |
| Filesystem  |        129GB       |  Filesystem |
| Partition 1 |____________________| Partition 2 |
| 25GB EXT4   |     Filesystem     |  102GB FAT  |
|             |     Partition 5    |             |
|             |     129GB EXT4     |             |

The 25GB is Linux (bootable); the 129GB is Linux and the 102GB is W95 FAT32
So I'm guessing that I need to replace the middle command with either sudo grub-install /dev/sda or sudo grub-install /dev/sda1  When @Karel suggests to enter the device name, I don't know if he means me to include the partition number.


text:
Q: Call Ant target directly and indirectly based on condition I have the following default target defined in my build file:
<target name="main" depends="generate.doc" unless="generated.doc.present"/>

The property is set when the doc files already exist. In that case I don't want to do anything. However, it doesn't work since the dependent target is always executed before the condition is evaluated.
I still need to be able to call the dependent target directly and execute it, no matter if the output already exists or not. Hence something like this would not work:
<target name="main" depends="generate.doc"/>
<target name="generate.doc" unless="generated.doc.present">...</target>

Is there a solution without using antcall in the main target?

A: In the example below, the main <target> has been changed to have two dependencies. A new <target> named -pre-conditions will run before generate.doc.
The -pre-conditions <target> sets the skip-generate.doc property only if the generated.doc.present property has already been set.
The generate.doc <target> has been changed so it will be skipped if -pre-conditions set the skip-generate.doc property.
With these changes, generate.doc will always run when it's called directly.
<target name="-pre-conditions">
    <condition property="skip-generate.doc">
        <isset property="generated.doc.present"/>
    </condition>
</target>

<target name="main" depends="-pre-conditions, generate.doc"/>

<target name="generate.doc" unless="skip-generate.doc">
    <echo>generate.doc running</echo>
</target>


text:
Q: Temporary Input Redirection in Bash I am looking for a way to dump input into my terminal from a file, but when EOF is reached I would like input returned back to my keyboard.  Is there a way to do this with Bash (or any other commonly-available *nix shell)?
Details:
I am debugging a server program which executes a fork to start a child process.  Every time I start a debugging session with gdb I have to type set follow-fork-mode child.  I would like to use some sort of input redirection to have this pre-populated.  There are other uses as well that I can think of, so I'd prefer a general solution - hence the reason this question is not about gdb.
Solution:
start-server.sh
#!/bin/bash
cat run-server.txt - |/bin/bash

run-server.txt
gdb ./Server
set follow-fork-mode child
run

A: You can do this:
cat input_file - | program

That will concatenate input_file followed by stdin to program, which I think is what you want.

A: maybe expect is what you want

A: Maybe use an intermediate file? Assuming you want to run the script myscript.sh:
INPUT_FILE=input.txt
TEMP_FILE=`mktemp -t input`
myscript.sh < $TEMP_FILE &
cat $INPUT_FILE >> $TEMP_FILE
cat >> $TEMP_FILE


text:
Q: Database backup I want to take backup of Xampp database available in /opt/lampp/var/mysql
`but I am unable to do it.
I used below command

/opt/lampp/htdocs/vivek.s$ sudo mysqldump -u root -p vive.se >
  07feb.sql

and

/opt/lampp/htdocs/vivek.s$ sudo mysqldump -h root -u root -p vive.se >
  07feb.sql

Result is same

bash: 07feb.sql: Permission denied

Then I used

sudo -s
sudo mysqldump -u root -p vive.se > 07feb.sql

Result is

sudo: mysqldump: command not found

and it created a Empty file named 07feb.sql in /opt/lampp/htdocs/vivek.s
What is wrong while I saw my friend using same command and he got
database backup of 95 MB.
What should I try.
Thanks

A: The problem is that you do not have permission to write to /opt/lampp/htdocs/vivek.s as your normal user. Running mysqldump as root elevates mysqldump (unnecessarily), but the redirection happens with the permissions of the shell - running as your regular user.
There's a few workarounds:

*

*Start a root shell by e.g. sudo -i or sudo -s. You should not use sudo to run the next command - mysqldump.

*Use tee:
mysqldump -u root -p vive.se | sudo tee 07feb.sql > /dev/null
This will run the process tee as root, writing one copy to file, and redirecting stdout to /dev/null as we don't need it.
Another workaround would be to write the backup to a location where your user has write permission, for instance your home directory.


text:
Q: Why do I keep getting the wrong output for my if statement JAVA i'm testing sides of a triangle to see if the triangle is a equilateral or isosceles, but even when all the values are equal I still get the else output.
the code in question is at the bottom, i just included the rest for reference
public static void main(String[] args)
{
    System.out.println("  Triangle Calculator  \n");

    Scanner inputab = new Scanner(System.in);

    System.out.println("Input lenghts of sides 'a' and 'b':");
    double sideA = inputab.nextDouble();
    double sideB = inputab.nextDouble();

    System.out.println("Input the size of Angle C in degrees:");
    double angleC = inputab.nextDouble();
    inputab.close();

    double sideC = Math.sqrt((Math.pow(sideA, 2) +
    Math.pow(sideB, 2)- 2*(sideA*sideB)*Math.cos(Math.toRadians(angleC))));

    System.out.println("\n\t   /\\\n\t  /  \\\n\t /    \\\n\t/      \\");
    System.out.printf("   %3.1f",sideA);
    System.out.print("/        \\");
    System.out.printf("%3.1f",sideB);
    System.out.println("\n      /          \\\n     /            \\\n    /______________\\");
    System.out.printf("\t  %3.1f\n", sideC);

    double angleA = Math.asin(sideA*Math.sin(Math.toRadians(angleC))/sideC);

    angleA = Math.toDegrees(angleA);

    double angleB = 180 - angleC - angleA;

    double perimeter = sideA + sideB + sideC;

    double hf = 0.5 * (sideA + sideB + sideC);
    double area = Math.sqrt(hf*(hf-sideA)*(hf-sideB)*(hf-sideC));

    System.out.printf("\nSide a       = ");
    System.out.printf("%4.3f",sideA);
    System.out.printf("\nSide b       = ");
    System.out.printf("%4.3f", sideB);
    System.out.printf("\nSide c       = ");
    System.out.printf("%4.3f", sideC);
    System.out.printf("\nAngle A(Deg) = ");
    System.out.printf("%5.3f", angleA  );
    System.out.printf("\nAngle B(Deg) = ");
    System.out.printf("%5.3f", angleB);
    System.out.printf("\nAngle C(Deg) = ");
    System.out.printf("%5.3f", angleC);
    System.out.printf("\nPerimeter    = ");
    System.out.printf("%5.3f", perimeter);
    System.out.printf("\nArea         = ");
    System.out.printf("%5.3f", area);

    if (sideA == sideB && sideA == sideC)
    {
        System.out.println("\nThis is an Equilateral Triangle");
    }
    else
    {
        System.out.println("\nThis is not an Equilateral Triangle");
    }

    if ((sideA == sideB && sideB!= sideC )
       ||(sideA != sideB && sideC == sideA)
       || (sideC == sideB && sideC != sideA))
    {
        System.out.println("\nThis is an Isosceles Triangle");
    }
    else
    {
        System.out.println("\nThis is not an Isosceles Triangle");
    }

A: Pointy is correct. I ran eclipse in debugger mode to look at the values as the program executed. I used 5 for the values of sides A and B and 60 for angleC. The result was that A and B were equal to 5.0 while side C was equal to 4.9999...
There are multiple ways you could go about fixing this, but you seem capable, especially now that you know what the issue is.


text:
Q: Rich:modalpanel Wizard behaviour doesn't work i'm having a problem with my wizard-like behavior in rich:modal panel.
I've read the tutorials and this http://maxkatz.sys-con.com/node/1428854/mobile and this http://www.mkyong.com/jsf2/jsf-form-action-navigation-rule-example/. But non of them were of any help.
My code is as follows:
faces-config:

    <navigation-rule>
    <from-view-id>/widgets/wizard/ProjectStep.xhtml</from-view-id>
    <navigation-case>
        <from-action>#{projectWizard.goNext}</from-action>
        <from-outcome>SUCCESS</from-outcome>
        <to-view-id>/widgets/wizard/InfoStep.xhtml</to-view-id>
    </navigation-case>
    <navigation-case>
        <from-action>#{projectWizard.goNext}</from-action>
        <from-outcome>FAIL</from-outcome>
        <to-view-id>/widgets/wizard/InfoStep.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>

my Richpanel:
<?xml version="1.0" encoding="UTF-8"?>

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:c="http://java.sun.com/jstl/core"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:a4j="http://richfaces.org/a4j"
  xmlns:rich="http://richfaces.org/rich">

 <rich:modalPanel id="#{id}" width="750" resizeable="false" autosized="true">

      <f:facet name="header">
        <h:panelGroup>
                <h:outputText  value="Wizard"/>
        </h:panelGroup>
      </f:facet>
      <h:form>
        <h:panelGroup id="test">
            <a4j:include id="wizardPage" viewId="#{src}"/>
        </h:panelGroup>
      </h:form>
    </rich:modalPanel>
</ui:composition>

The modal panel gets the parametrs correctly. The fist page openes up and the bean is called afterwards.
Here's the first page - ProjectStep.xhtml
<h:panelGroup xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:c="http://java.sun.com/jstl/core">

        <h:outputText value="I've opened up #{bean}" />
        <h:inputText value=" " />

          <a4j:commandButton id="btnNext"
                             value="Next"
                             action="#{bean.goNext()}"
                             style="display:#{bean.isCanGoNext() ? '' : 'none'}"
                             reRender="test"/>

            <a4j:region>
            <a4j:commandButton  onclick="#{rich:component(id)}.hide()"
                                value="Cancel"
                                style="display:#{bean.isCanCancel() ? '' : 'none'}"/>
            </a4j:region>

</h:panelGroup>

I've tried to use ui:composition instead of h:panelGroup. It didn't work. Thee second page is imlemented in the same way.
When i'm clicking Next my bean returns SUCCESS message, but the page doesn't get changed.
Please, doe anyone has an idea what's wrong?

A: Add the <redirect/> attribute to your faces_config.xml and probably try on the ajaxRendered="true" on your <a4j:include/>. Be absolutely sure your navigation cases are being invoked. Your faces_config should look like
 <navigation-rule>
    <from-view-id>/widgets/wizard/ProjectStep.xhtml</from-view-id>
    <navigation-case>
        <from-action>#{projectWizard.goNext}</from-action>
        <from-outcome>SUCCESS</from-outcome>
        <to-view-id>/widgets/wizard/InfoStep.xhtml</to-view-id>
        <redirect/>
    </navigation-case>
    <navigation-case>
        <from-action>#{projectWizard.goNext}</from-action>
        <from-outcome>FAIL</from-outcome>
        <to-view-id>/widgets/wizard/InfoStep.xhtml</to-view-id>
        <redirect/>
    </navigation-case>
</navigation-rule>


text:
Q: How to restrict admin link/button in Django? This is what I expect: if a user has position "1" (Admin) the nav menu in home.html must show "Admin" link to an admin page. If a user has position "2" (User) it won't show the link.
But when I run server this code generate as many Admin links as there are registered users. I want only one link for currently logged-in user to be shown. How can I do that? I know that there's something wrong with "for user in position", but how to fix it for currently logged-in user?
models.py
class Profile(models.Model):
    positions = (
        ('1', 'Admin'),
        ('2', 'User'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    position = models.CharField(max_length=50, default='Position', choices=positions)

views.py
def home(request):
    user_position = Profile.objects.all()
    return render(request, 'home.html', {
        'position': user_position,
        })

home.html
{% for user in position %}
    {% if user.position == '1' %}
        Admin
    {% endif %}
{% endfor %}

A: You can also use the is_superuser attribute in your template to achieve this:
{% if user.is_superuser %}
 admin
{% endif %}

if you want to check it based on the username only you can use:
{% if user.username == "Admin" %}
   admin
{% endif %}

Another thing you can do is to create 2 groups inside your admin panel; admins & users.
Then you have to create a custom template tag(has_group for example) to show the nav items based on these groups which is a better solution i think. Then you can use something like this in your template:
{% if user|has_group:"admin" %}

User belongs to the admin group
{% else %}

belongs to users group

{% endif %}


text:
Q: Transferring state before removal from load balancer (AWS) I have an application that maintains state where it is not practical to store the state on every state change.  When an AWS Auto Scaling group initiates a scale-in my plan was to then "transfer" the state to either disk or a memory grid.  I assumed using the Lifecycle Hooks I'd be able to tell the node it was going to be removed and then initiate that transfer.
However, it appears the hooks let me know AFTER the node is removed from the load balancer but before the instance is destroyed.  I'd like to be able to hook before the load balancer removes the node.  Is anyone aware of a way to do that?


text:
Q: Debug user profiles? There's an error in a user profile I'm generating to configure an wireless internet connection. When I try to import it the Profile Manager tells me there's an error, and if I try to use the profiles utility I get the following error:
$ profiles -v -I -F ./xxx.mobileconfig
profiles: verbose mode ON
profiles: using user name = xxx
profiles install profile xxx.mobileconfig for user: xxx
profiles install for file: 'xxx.mobileconfig' and user:'xxx' returned 3840 (The data couldn't be read because it isn't in the correct format.)
profiles: returned error: 3840
fail

This is the error you get if you try to import any file that's not valid, from an .mp3 file to a proper .mobileconfig file with a missing closing tag, so it's not very helpful.
I've checked for obvious errors, like whether it's correct XML, whether there are any weird characters or whatever - didn't find anything. I've tried comparing it to a correct file but I haven't been able to find anything yet. Is there any way to get more detail about what's wrong? Some sort of tool, or at least a proper documentation about the format of these files? Thanks.
EDIT: Okay, I found the specification, I'm going to look into it.


text:
Q: dictionary Value of type 'Int?' has no member I use this code that find value for key in dictionary and remove value.
var downloadQ = [Int: Int]()

downloadQ[id] = indexPath.row

but I get error in this line if let idx = downloadQ[id].index(of: indexPath.row) { error: Value of type 'Int?' has no member 'index'
if let idx = downloadQ[id].index(of: indexPath.row) {
    self.downloadQ[id].remove(at: idx)
}

How to fix it?

A: To remove the value under the given key, use this:
if downloadQ[id] == indexPath.row {
    downloadQ.removeValue(forKey: id)
}

Read its documentation.
Or alternatively, you can use:
if downloadQ[id] == indexPath.row {
    downloadQ[id] = nil
}

If you would use dictionary with [Int] as values (var downloadQ = [Int: [Int]](), then you would use the code that you had originally in the question (just with ? to unwrap optional):
if let idx = downloadQ[id]?.index(of: indexPath.row) {
    self.downloadQ[id]?.remove(at: idx)
}

A: Only guessing what you are trying to do. If you want to remove the index from the downloadQ only if the value is the same as indexPath.row:
if downloadQ[id] == indexPath.row {
  downloadQ[id] = nil
}


text:
Q: Printing out error messages in python So for a point class I'm making I have this error class:
class Error(Exception):
    def __init__(self, message):
        self.message = message

I'm using this to raise an error and print out a message for certain errors. What I'm doing here is printing out an error message if either x or y (or both) are not float values:
def __init__(self, x, y):
    if not isinstance(x, float):
        raise Error("Parameter \"x\" illegal.")
    self.x = x
    if not isinstance(y, float):
        raise Error ("Parameter \"y\" illegal.")
    self.y = y

By raising and printing errors that way, the error messages I get look like this:
********** Point
*** constructor
caught: Parameter "x" illegal.
caught: Parameter "y" illegal.
0
***

But the error message is actually supposed to look like this:
********** Point
*** constructor
caught: Parameter "x" illegal.
caught: Parameter "y" illegal.
0 1
***

So why does the expected output print a 1 next to the 0? Other error messages also include:
*** rotate
caught: Parameter "a" illegal.
0
***

When I want it to look like:
*** rotate
caught: Parameter "a" illegal.
0 -1
***

So is there something I'm not printing out in my error message? Here's the code that prints out the error message:
print '*** constructor'
try:
    p0 = Point(1,1.0) # x illegal
except Error as e:
    print 'caught:', e.message
try:
    p0 = Point(1.0,'y') # y illegal
except Error as e:
    print 'caught:', e.message

print Point(0.0,1.0)

Here's my str method:
def __str__(self):
    return str(int(round(self.x)))

A: Default x and y to None:
x = None
y = None

Then in str method,
def __str__(self):
    str_x = ""
    if self.x is not None:
        str_x = str(int(round(self.x)))
    str_y = ""
    if self.y is not None:
        str_y = str(int(round(self.y)))
    return "%s %s" % (str_x, str_y)

A: Why not use python's built-in raise?
It will terminate the program and show an error message, just like it came out of the interpreter.
If you're picky about the class, define it like this:
class YourNameHere(Exception): pass

Whether you defined the class or not, raise it like this:
raise ExampleError("Parameter \"x\" illegal.","Parameter \"y\" illegal.")

It will show the following output:
Traceback (most recent call last):
  File "C:/testanswer.py", line 3, in <module>
    raise ExampleError("Parameter \"x\" illegal.","Parameter \"y\" illegal.")
ExampleError: ('Parameter "x" illegal.', 'Parameter "y" illegal.')

For single answers, there is no need to put it in a tuple.


text:
Q: Reading a dictionary that has function calls How to read a file that has complex nested dict/list with some values as a function call.
Data = {'key1' : func1(arg1, arg2)}.....

How to read it as a dictionary so that I can query values after loading the file.

A: You need to save the name of the module in which the function is located and the name of the function
import importlib

# Suppose it is loaded from a file
d = {
    "module": "my_lib",
    "function": "f1",
    "args": ["Hello", "World!"]
}

module = importlib.import_module(d["module"])

ext_func = getattr(module, d["function"])
ext_func(*d["args"])

It is assumed that you have my_lib.py with the following content
def f1 (s1, s2):
     print (s1, s2)

And don't forget to create __init__.py


text:
Q: I am tring to create a digraph to represent a DFA (deterministic finite automata) I am new to LaTeX, so the more details the better. Thanks!

A: As mentioned in the comments you can use the automata library here. You may want to use foreach loops to avoid repetition.
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{arrows.meta,automata,positioning,quotes}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,>={Stealth[round]},
    every state/.style={draw},blue!60,text=black]
 \path node[state,double] (S_0) {$S_0$}
   foreach \X [count=\Y] in {0,1}
  {node[state,right=of S_\X] (S_\Y) {$S_\Y$}};
 \path foreach \X [count=\Y] in {0,1}
  {(S_\X) edge[bend right,->,"\the\numexpr1-\X"'] (S_\Y)
   (S_\X) edge[bend left,<-,"\the\numexpr1-\X"] (S_\Y)}
  (S_2) edge [loop right,"1"] ()
  (S_0) edge [loop above,"0",rotate=45] ()
  (S_0) edge [<-] ++ (-1,0);
\end{tikzpicture}
\end{document}


text:
Q: OpenTK: Just showing a point at the middle of screen instead of a graph I am trying to plot a graph of a 1d list using OpenTK and winforms. I need to plot millions of data so I am preferring to save my data as a list instead of array. I am not sure if opengl only accepts ptrs to array or not. Also, I feel I might be doing something wrong when trying to change the 1d list to a vec3(using EditVertices Function). For now, I am running a small list as a test of concept.
public GraphWIndow () : base(800, 600, default, "Data Analyzer", GameWindowFlags.Default, default,4,0, default)
        {
        var test = new List<double> { 1, 22, 0.87, 4, 5 };
        List<double> list1 =  EditVertices(test);
        GCHandle handle1 = GCHandle.Alloc(list1);
        parameter = (IntPtr)handle1;
        }

protected override void OnLoad(EventArgs e)
        {
            CursorVisible = true;
            shader = new Shader("shader.vert", "shader.frag");
            VertexArrayObject = GL.GenVertexArray();
            VertexBufferObject = GL.GenBuffer();
            GL.BindVertexArray(VertexArrayObject);
            GL.BindBuffer(BufferTarget.ArrayBuffer, VertexBufferObject);
            GL.BufferData(BufferTarget.ArrayBuffer, 5 * sizeof(double), parameter, BufferUsageHint.StaticDraw);
            //GL.bu(BufferTarget.ArrayBuffer, (IntPtr)0, 5, parameter);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Double, false, 3 * sizeof(double), 0);
            GL.EnableVertexAttribArray(0);

            }
protected override void OnRenderFrame(FrameEventArgs e)
        {
            GL.ClearColor(Color4.DarkBlue);
            GL.Clear(ClearBufferMask.ColorBufferBit);

           // GL.UseProgram(;
            GL.UseProgram(shader.Use());
            GL.BindVertexArray(VertexArrayObject);
            GL.DrawArrays(PrimitiveType.Points,0, 5);
            GL.PointSize(10);
            SwapBuffers();
        }

private List<double> EditVertices(List<double> list)
        {
            List<double> list2d = new List<double>();
            for(int i =0; i<list.Count(); i++)
            {
                list2d.Add(i/(list.Count()));
                list2d.Add((list[i]-list.Min())/(list.Max()-list.Min()));
                list2d.Add(0);
            }
            return list;
        }

I am compiling the shaders in a separate class:
  public class Shader
    {
        int Handle, VertexShader, FragmentShader;

        public Shader(string vertexPath, string fragmentPath)
        {
            string FragmentShaderSource, VertexShaderSource;
            using (StreamReader reader = new StreamReader(vertexPath, Encoding.UTF8))
            {
                VertexShaderSource = reader.ReadToEnd();
            }
            using (StreamReader reader = new StreamReader(fragmentPath, Encoding.UTF8))
            {
                FragmentShaderSource = reader.ReadToEnd();
            }

            VertexShader = GL.CreateShader(ShaderType.VertexShader);
            GL.ShaderSource(VertexShader, VertexShaderSource);
            FragmentShader = GL.CreateShader(ShaderType.FragmentShader);
            GL.ShaderSource(FragmentShader, FragmentShaderSource);
            GL.CompileShader(VertexShader);

            string infoLogVert = GL.GetShaderInfoLog(VertexShader);
            if (infoLogVert != System.String.Empty)
                System.Console.WriteLine(infoLogVert);

            GL.CompileShader(FragmentShader);

            string infoLogFrag = GL.GetShaderInfoLog(FragmentShader);
            if (infoLogFrag != System.String.Empty)
                System.Console.WriteLine(infoLogFrag);

            Handle = GL.CreateProgram();
            GL.AttachShader(Handle, VertexShader);
            GL.AttachShader(Handle, FragmentShader);
            GL.LinkProgram(Handle);
            GL.DetachShader(Handle, VertexShader);
            GL.DetachShader(Handle, FragmentShader);
            GL.DeleteShader(FragmentShader);
            GL.DeleteShader(VertexShader);

        }
        public int  Use()
        {
            return Handle;
        }

Vertex Shader:
 #version 400 core
    layout (location = 0) in vec3 aPosition;
void main()
{
    gl_Position = vec4(aPosition.x, aPosition.y, aPosition.z, 1.0f);
}

Fragment Shader:
#version 400 core
out vec4 FragColor;

void main()
{
    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}

I am seeing 1 orange dot at the middle of the blue screen. Not sure what I missed.


text:
Q: Getting text from EditText without a button In my app i create an EditText dynamically when a CheckBox is not checked and i want to get the text the user writes in it. The problem is that i don't know where to write the getText().toString(). I have debugged this and i see that when the EditText is created the getText().toString() is executed immediately and returns always "" . I have also tried the focusChange in the EditText but without any success. Any help is appreciated!
        final EditText editText = new EditText(this);
        TableRow.LayoutParams params = new TableRow.LayoutParams(getPx(100) , ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0 ,0 ,getPx(100) ,0);
        tr.addView(editText);
        date = editText.getText().toString();

A: Have you tried this:
         editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(isValidDate()) {
                   date = s.toString();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    ...

    private boolean isValidDate() {
       // implement your logic here
    }

A: So you dont want to take text when user inputs.
editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            String typedStringIs=s.toString();
            //Here your code . It is dynamaclly changing . if anything you write will be here
            }
        });


text:
Q: WSO2 ESB Chinese characters garbled? I have a problem. My response message contains Chinese characters. So in the console and backstage, all message is garbled.
My log:
Response message=== = <message><TransactionID>1</TransactionID><Timestamp>2012-09-07 17:06:55</Timestamp><OpCode>IAG.BOSS_SYNC_USER</OpCode><MsgType>RESP</MsgType><ReturnCode>3095</ReturnCode><ErrorMessage>智能卡已被其他用户使用</ErrorMessage></message>

backstage:
Response message=== = <″凡琚<T″凡琚onID>1</TransactionID><Timestamp>2012-09朵荤ㄦ蜂娇绋</ErrorMessage></message>

Someone can tell me how to do with this problem? Best regards.

A: In your eclipse.ini file add the following line:
-Dfile.encoding=UTF8

After that, restart Eclipse.


text:
Q: Python Minidom : Change Value of Node I'm using Python's minidom library to try and manipulate some XML files. Here is an example file :
<document>
    <item>
            <link>http://www.this-is-a-url.com/</link>
            <description>This is some information!</description>
    </item>

    <item>
            <link>http://www.this-is-a-url.com/</link>
            <description>This is some information!</description>
    </item>

    <item>
            <link>http://www.this-is-a-url.com/</link>
            <description>This is some information!</description>
    </item>
</document>

What I need to do, is take the value in "description" and put it into "link" so both say "This is some information!". I've tried to do it like so:
#!/usr/bin/python

from xml.dom.minidom import parse

xmlData = parse("file.xml")

itmNode = xmlData.getElementsByTagName("item")
for n in itmNode:
    n.childNodes[1] = n.childNodes[3]
    n.childNodes[1].tagName = "link"
print xmlData.toxml()

However "n.childNodes[1] = n.childNodes[3]" seems to link the two nodes together, so when I do "n.childNodes[1].tagName = "link"" to correct the name BOTH child nodes become "link" where before they were both "description".
Furthermore, if I use "n.childNodes[1].nodeValue" the changes don't work and the XML is printed in it's original form. What am I doing wrong?

A: I'm not sure you can modify the DOM in place with xml.dom.minidom (creating the whole document from scratch with new values should work though).
Anyway, if you accept a solution based on xml.etree.ElementTree (I strongly recommend using it since it provides a friendlier interface), then you could use the following code:
from xml.etree.ElementTree import ElementTree, dump

tree = ElementTree()
tree.parse('file.xml')

items = tree.findall('item')
for item in items:
    link, description = list(item)
    link.text = description.text

dump(tree)


text:
Q: How to determine the Operating System using Java? I want to find out the OS in a java program so that I can load the correct native library. I know that using System.getProperty("os.name") is an option, but I would prefer not to use it because it can be set by anyone in a code base by using System.setProperty("os.name", "foo").

A: The only way to be sure to load the correct JNI lib from the Java runtime is to try to load any of them with System.loadLibrary() and catch exceptions, until one native library is loaded correctly. The other ways to find the underlying OS are only heuristic tools.

A: Just use System.getProperty("os.name") because I don't think their is another way to do it, and don't worry about setProperty because if you think about it, no one will set it to foo or bar or something like that.


text:
Q: MongoDB: Relational Data which is only used in one context? (Collection vs. Schema) I have a few people saved in my database. Sometimes teams are formed an I need to add a few people to a team. Some people won't have any team.
I will never need to access the teams separately, i.e. I only ever need to look at the teams when I am already looking at the people. So I thought of saving it all together. So instead of creating a new collection for teams, I thought it might be better to just nest it:
      people: [
      {
        name: "Jack",
        team: team_id_1,
      },
      {
        name: "John",
        team: null,
      },
      {
        name: "Jane",
        team: team_id_1,
      },
      ...
      ],

      teams: [
      {
        team_id: team_id_1
        color: "red",
      },
      ...
      ]

However, I do not know how I can now create this sort of relationship in mongo, and assign a team_id to each of the person-objects without it being a collection.
Someone here suggested to Define user's team as a reference to team's collection and then populating it. - but, as I undestand it, this means creating a separate model for my team, and turning team into its own separate collection. I would prefer to not do this, since I will never need to access this collection directly and don't want to go through one massive collection of teams, if I only ever need to access three teams and can easily keep them in the relevant object.
What would you advise me to do? Is this the wrong approach?


text:
Q: Trigger paypal donate on form submit i'm working on a paypal donate feature in a rails 4 app. I'm not very familiar with paypal api, so any advices about the right way to work with it are welcome.
What i want to do:
the donate page is a form to create a new Donateur object who will hold all informations about the donator like name, email, status of the donation (paid or not) etc
When a user fill and submit this form to make a donation, i want to redirect him to the paypal paiement page (after the form submission has succeed).
Then, when paypal donation is done, IPN send to my app the paiement datas so i can update the previous Donateur entry created and fill informations about the success or failure of the donation.
What i got
I have the classic form for creating a new Donateur object, nothing special here.
In my controller, i wonder how i can redirect user to the paiement page of my paypal account
#donateurs_controller.rb
def create
  @donateur = Donateur.new(post_params)
  @donateur.save ? redirect_to(PAYPAL_DONATE_PAGE) : render('index')
end

The callback (after paiement) doesn't matter for the moment
My question
Donations with paypal are they classic transactions (so i could use the api like if i was selling some products) or should i specifiy something about it s a donation while make a payement call?
Thanks

A: I've fix my problems. I used this gem https://github.com/paypal/buttonmanager-sdk-ruby to generate a donate button on form submit. I can get programmaticaly the api request url sent when clicking this button, so i don't have to display it on the screen.


text:
Q: How to make one to many relationship in laravel I'm trying to make a one to many relationship using eloquent model and want to show the products in the specified category
that is my product model :
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;

class Product extends Model
{
    use softDeletes;
    protected $table='products';

    public function category(){
        return $this->belongsTo('App\Category');
    }
}

And that is my category model :
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;

class Category extends Model
{
    use softDeletes;
    protected $table='category';

   public function product(){
    return $this->hasMany('App\Product','category_id','id');
   }
}

And that's the product controller :
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Product;
use App\Category;

class productsController extends Controller
{
    public function getShow($id,Request $request){
            $in=$request->get('id');
            $category=Category::all();
            $product=Product::find($id);
            $products=$product->category()->where('category_id','=',$in);

            return view ('contents.products')->with('products',$products)
                                            ->with('category',$category);
    }
}

And this is the product table :
public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('category_id');
        $table->string('describtion');
        $table->string('image_name');
        $table->timestamps();
        $table->softDeletes();
    });
}

And that is the category table :
public function up()
{
    Schema::create('category', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
        $table->softDeletes();
    });
}

And it gives me this error : Call to a member function category() on a non-object
So how can i solve it ?

A: As far i understand your question :
In your controller:
$category = Category::find($id);
$products = $category->product;

Better yet you could use eager loading and forget about assigning products manually:
Controller:
$category = Category::with('product')->where('id', 1)->first();

Hope this help you .


text:
Q: How to add two radio buttons in a single row? I want to add two radio buttons in as single row with label, as shown in the photo, ow can I achieve this??

A: here is the example how to solve your issue.

label {
  display: block;
  color: #7d7d7d;
}

.floatBlock {
  margin: 0 1.81em 0 0;
}

.labelish {
    color:#7d7d7d;
    margin: 0;
}

.paymentOptions {
    border: none;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    break-before: always;
    margin: 0 0 3em 0;
}

#purchaseOrder {
    margin: 0 0 2em 0;
}

Payment Method:

                     <input id="paymentCC" name="paymentType" type="radio" value="CREDIT_CARD" />  Credit Card

                     <input id="paymentInv" name="paymentType" type="radio" value="INVOICE" /> Invoice

                     <input id="payment3rd" name="paymentType" type="radio" /> Third Party

note: idea taken from codepen

A: you need display: flex; for this:

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  display: flex;
  justify-content: space-around;
  padding: 16px;
}

.radio-container {
  display: flex;
  margin-right: 15px;
}

.radio-group {
  display: flex;
  justify-content: end;
  flex-direction: column;
}

radios 1

      <input type="radio" name="group1" />radio 1
      <input type="radio" name="group1" />radio 2

radioss 2

      <input type="radio" name="group2" />radio 1
      <input type="radio" name="group2" />radio 2

radioss 3

      <input type="radio" name="group3" />radio 1
      <input type="radio" name="group3" />radio 2


text:
Q: Total time to HH:MM:SS to rdlc this is the code i have right now. This code computes the total time in my rdlc using expressions.
(Sum(System.TimeSpan.Parse(Fields!Number_of_Hours.Value).Hours)) &":"&(Sum(System.TimeSpan.Parse(Fields!Number_of_Hours.Value).Minutes))

this code shows the total hours and minutes.
111:217
What I want to see is this.. is this possible ?
113:37

A: Its a little unclear, but I think you are saying that you have an input of time as a string in the format like 111:217 where the minutes component can be >= 60. You want to display that in hh:mm where the minutes component is < 60.
TimeSpan.Parse() dosent seem to like the format your input is in. It expects the minutes < 60 and hours < 24. You will have to use the TimeSpan constructor. Give this code a try:
string input = "111:217";

// Split the string into pieces on ":"
string[] parts = input.Split(':');

// Create a TimeSpan from our pieces
int hours = Int32.Parse(parts[0]);
int minutes = Int32.Parse(parts[1]);

TimeSpan time = new TimeSpan(hours, minutes, 0);

// Show the time formatted
string formatted = time.ToString(@"hh\:mm");

Console.WriteLine(formatted);

// Show the total time in minutes
double totalMinutes = time.TotalMinutes;

Console.WriteLine(totalMinutes);

Here is fiddle showing the code working: https://dotnetfiddle.net/iEeA6J


text:
Q: How to add @change to a custom Vue component I've searched around and can't find a solution to my issue so I'm hoping someone can help.
I have created a couple of custom form components but I still have to revert back to 'original' code to fulfill some tasks as I can't find a way to use @change on a custom select.
This is what I'm doing normally...
Custom select component - with props and methods omitted:
<v-select v-if="inputType === 'select'"
                  @input="updateValue($event)"
                  :background-color="backgroundColor ? 'backgroundColor' : 'white'"
                  class="rounded-lg"
                  :clearable="clearable"
                  :chips="chips"
                  color="accent2"
                  :deletable-chips="deletableChips"
                  :disabled="disabled || isFormReadOnly"
                  :error="error"
                  :error-messages="errorMessages"
                  filled
                  flat
                  hide-details="auto"
                  :items="items"
                  :item-text="itemText && itemText"
                  item-value="value"
                  :label="label"
                  :multiple="multiple"
                  :outlined="!outlined && !isFormReadOnly"
                  :return-object="returnObject"
                  :small-chips="smallChips"
                  :value="value"/>

...and I call it like this:
<app-input input-type="select"
           class="rounded-lg mb-4"
           :class="$vuetify.breakpoint.width >= 600 && 'pl-2'"
           :error="errors.type"
           :is-form-read-only="isFormReadOnly"
           :items="['Drill', 'Emergency']"
           label="Type"
           v-model="form.type"/>

...which works just fine, but I just can't call a function on change using @change.
Any ideas?

A: I think you can try $emit or write a watch in the instance


text:
Q: Does the range of the correlation coefficient or the covariance belongs to $\mathbb{Q}$ I have a question that seems to me logic, but I haven't seen anywhere such a claim.
Could we claim that the range of the correlation coefficient or the covariance belongs to $\mathbb{Q}$, namely in the set of rational numbers? Is any theorem or something that gives a connection between them?

A: If your data points are themselves rational, then the covariance will be rational since the covariance formula involves only addition, subtraction, multiplication, and division. The formula for the correlation coefficient $r$ involves square roots, so might be irrational, but $r^2$ will be rational.


text:
Q: If user inputs "sum(x,y)" how can I get x and y as doubles I am writing a simple calculator program such that the user is entered into the programs own console environment. Each new line starts with a $. User will enter commands such as '''sum(x,y)''' '''mul(x,y)''' etc. and the program will take x and y as doubles and execute a function i.e. '''double mul(x, y){return x*y)''' and display the returned value.
I have gotten it to correctly identify the command based on matching the first three characters in the string.
I cant seem to read the numerical values correctly no matter what I do. Any suggestions are greatly appreciated!
The Code below is from main()
    printf("%s", " $    ");
    fgets(input, sizeof(input), stdin);
    sscanf(input,"(%d,%d)",&arg1,&arg2);

    if(strstr(input,"sum")){
        //char *starting_pos = strchr(input,dlm);
        //int position = (starting_pos == NULL ? -1 : (uintptr_t)starting_pos);

        //arg1 = input[position + 1];
        //arg2 = input[position + 3];
        printf("DEBUG: arg1 is %d arg2 is %d\n", arg1,arg2);
        double output = sum(arg1,arg2);
        printf("DEBUG: Output should be: %d\n", output);
        printf("%d\n",output);

    }else if ...

The commented section is the remnants of another way I was trying. If anyone can tell me what the right way to do this is I would be very grateful.

A: Good job in reading with fgets() and then parsing values with sscanf(). If I understand the question, and you may have multiple operators followed by two doubles in parenthesis, e.g. SUM(1.1, 2.2), and you want to separate and save the operator, and the double values, then you can use a format string such as:
#define MAXOP   32
...
    char op[MAXOP];
    ...
    sscanf (input, "%31[^( ] (%lf,%lf)", op, &x, &y)

This will read from input separating everything up to a whitespace or '(' into op and then reading the double values into x and y. By reading the op to a whitespace or '(', you allow input of sum(1.1, 2.2) or sum (1.1, 2.2) seamlessly.
For example, you could do:
#include <stdio.h>

#define MAXC  1024
#define MAXOP   32

int main (void) {

    while (1) {
        char input[MAXC], op[MAXOP];
        double x, y;

        fputs ("\nenter OP(x, y): ", stdout);
        fflush (stdout);

        if (!fgets (input, MAXC, stdin)) {
            puts ("(user canceled input)");
            return 0;
        }
        if (*input == '\n')
            break;

        if (sscanf (input, "%31[^( ] (%lf,%lf)", op, &x, &y) == 3)
            printf (" op: '%s'  x: %.2f  y: %.2f\n", op, x, y);
        else
            fputs ("  error: invalid input.\n", stderr);
    }
}

Example Use/Output
./bin/sumxy

enter OP(x, y): mult(10.1,12.4)
 op: 'mult'  x: 10.10  y: 12.40

enter OP(x, y): mult (8.3, 12.1)
 op: 'mult'  x: 8.30  y: 12.10

enter OP(x, y): sum(1.1, pickles)
  error: invalid input.

enter OP(x, y): sum(1.1, 2.2)
 op: 'sum'  x: 1.10  y: 2.20

enter OP(x, y):

Let me know if you have further question, or if I misunderstood the question.


text:
Q: How if statement works in Perl with a hash argument? i have this variable:
my %permit = (
        "activity" => '',
        "type" => '',
        "sub_type" => '',
        "status" => '',e
        );

    my $permit;

and before i have tihis if:
if($permit->{activity}){
     print "inside if\n";
}

the question is: when the if statement is execute?

A: You have two variables here - %permit which is a hash containing key/value pairs and $permit which is a scalar and doesn't contain anything.
To look up a value in the hash, you should use the syntax $permit{activity} (notice there is no arrow there). The syntax $permit->{activity} (with the arrow) attempts to use the scalar $permit as a hash reference and will return nothing - as $permit does not contain a hash reference.
You will never get into your if branch as your code is looking at the wrong variable.
This is why it's generally a very bad idea to have two variables of different types with the same name (%permit vs $permit).


text:
Q: Query Multiple SQL Tables I need to query values in more than one table and ensure the results are displayed correctly.
Each table has the unique product_id within, but how do I ensure the data lines up correctly? For example, product_price is queried from a different table and needs to be aligned with the correct product.
I'm new to SQL so apologies if this is an easy one.

$query = "SELECT * FROM jos_vm_product ORDER BY product_publish DESC";
$result = mysql_query($query);

echo "
";
while($row = mysql_fetch_array($result)){

echo "
" . $row['product_id'] . "	" . $row['product_sku'] . "	" . $row['product_name'] . "	" . $row['product_in_stock'] . "	" . $row['product_sales'] . "	" .  $row['product_price'] . "	" . $row['product_available_date'] . "	" . $row['product_publish'] . "
";

}

echo "
";

A: Do a join (either INNER JOIN or LEFT JOIN, depending on what should happen if a table lacks matching rows):
SELECT * FROM jos_vm_product
  INNER JOIN <second product table> on jos_vm_product.product_id = <second product table>.product_id
  INNER JOIN <third product table> on jos_vm_product.product_id = <third product table>.product_id
ORDER BY jos_vm_product.product_publish DESC

A: SELECT * FROM jos_vm_product ORDER BY product_publish DESC

the above query to me looks like you are only fetching from 1 table or view. In which case you are not selecting from multiple tables...
but for an example you would use a JOIN as @Matt.C suggested.
SELECT * -- select everything from P and PS you can specify (P.ID, PS.productPrice)
FROM jos_vm_product P
INNER JOIN jos_vm_productPrices PS -- join to another table.
ON P.ProductID = PS.ProductID -- join on what?
ORDER BY P.product_publish DESC


text:
Q: with custom user i have not the group form in admin django I created a custom user, it works well, but I notice that in the django admin, if I create a new user, I don't have access to the form that manages the groups.
If I use a standard user system, when you create a user, in the admin, you have access to the management of groups and permissions. On the other hand in my project group and user are not linked
my models.py
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.db import models

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password):
        if not email:
            raise ValueError('Vous devez entrer une adresse email.')
        email = self.normalize_email(email)
        user = self.model(email=email)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password):
        user = self.create_user(email=email, password=password)
        user.is_staff = True
        user.is_admin = True
        user.save()
        return user

class CustomUser(AbstractBaseUser):
    email = models.EmailField(
        max_length=255,
        unique=True,
        blank=False
    )
    nom = models.CharField(max_length=50, blank=False, unique=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = "email"

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    def __str__(self):
        return self.email

in the views.py
from django.contrib.auth import authenticate
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import login as log_user
from django.contrib.auth import logout as logout_user

from accounts.forms import UserRegistrationForm
from accounts.models import CustomUser

def home(request):

    # return HttpResponse(f"Bienvenue {request.user} !")
    nom_user = request.user.nom
    #nom_user = CustomUser.objects.all()
    context = {'nom_user': nom_user}
    return render(request, "index.html", context)

def signup(request):
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("home")
    else:
        form = UserRegistrationForm()

    return render(request, "accounts/signup.html", {"form": form})

def profile(request):
    return HttpResponse(f"Bienvenue {request.user.email}")

def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)
        if user is not None:
            log_user(request, user)
            return redirect("home")
        else:
            return HttpResponse("Impossible de connecter l'utilisateur...")

    return render(request, 'registration/login.html', {})

def logout(request):
    logout_user(request)
    return redirect("home")

admin.py
from django.contrib import admin
from accounts.models import CustomUser

@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):

    list_display = ('email', 'nom', )

in settings.py
AUTH_USER_MODEL = "accounts.CustomUser"

thank for any help

A: I added PermissionsMixin in CustomUser model
class CustomUser(AbstractBaseUser, PermissionsMixin)

and in admin.py added this in fieldsets
('Permissions', {'fields': ('is_admin', 'groups',)}),

and now in admin I can link users to permission groups


text:
Q: Django: Searchable form field for ManyToMany relationship Say I have model A which has a ManyToMany attribute joining it to model B. When a user creates a model A, via some forms, they are appropriately presented with a MultipleChoiceField containing all model B objects.
Now, there are a lot of model B objects. Is there a way to make thi s MultipleChoiceField searchable? Ideally I'd like to have something like this:

Where each [+] represents a choice in some particular attribute of B.
How could I go about achieving this?


text:
Q: Encrypted external drive accessible w/o password after backup/restore I've got a 4TB LaCie Rugged drive that I want to use as my main encrypted backup drive for my Mac (Mojave).
Previously I was using a 2TB WD My Passport drive and I wanted to transfer all content (Time Machine backups and regular manual backups of images and various things) to the new drive.
The steps I took to do this were:

*

*Formatted the LaCie drive to Mac OS Extended (Journaled, Encrypted) and set an encryption password

*Copied all files from the WD drive to the LaCie drive using SuperDuper v3.3.1, set to "Backup - All files" mode.

After 1., when plugging in the LaCie drive, it asked for a password to access it (which I stored in keychain for convenience).
However, after 2., when plugged in the LaCie drive to another Mac laptop, it allowed access without asking for an encryption password!
I initially thought that SuperDuper reformatted the drive to not be encrypted, but in Disk Utility the LaCie drive still shows up as Mac OS Extended (Journaled, Encrypted)
Why is the LaCie drive accessible without password even though it's supposed to be encrypted?
Is there a way to reenable the encryption of the LaCie drive?
As the backup took about 35 hours to complete, I'd prefer to not do it again :/

Edit: I noticed that when trying to enable TM I couldn't select to use the drive encrypted, and when trying to use it decrypted instead it threw an error This Core Storage logical volume is already decrypting.. After some reading here and here I tried running the diskutil cs list command, which gave the following result:
Encryption Type:         AES-XTS
Encryption Status:       Unlocked
Conversion Status:       Converting (backward)
Reversion State:         Decrypting
----
Conversion Progress:     6%

which means that the drive is actually in the process of decrypting. Not exactly sure why or what triggered this (might have misunderstood things earlier and tried to use it as a decrypted TM drive by mistake), but it seems I have to let it run through the decryption process fully before I can encrypt it again. (it's a 4TB drive so guess it'll take days :/ ).
I'll post an update once the drive has been re-encrypted again to see if the original issue still persists.
Edit 2: Re-encrypting didn't work and would've taken many times longer than just starting over from scratch, which is what I did instead. Now the drive is encrypted again it's properly asking for pw when plugged in to a new computer.


text:
Q: Is there a way to import/export tasks from different CQ instances? I have two instances of CQ and between them I want to be able to import/export tasks.
For example:
On instance 1 I can see all tasks by going to http://instance1/libs/cq/taskmanagement/content/taskmanager.html#/tasks/Delta
On instance 2 I can see all tasks by going to http://instance2/libs/cq/taskmanagement/content/taskmanager.html#/tasks/Delta
There might be some scenarios where I want to take all tasks from instance2 and add them as additional tasks into instance1 (on top of the tasks it may already have).
Is this possible to do?

A: Yes, you can do this with Package Manager.  The tasks are stored as nodes in the JCR repository, so you can create a package that filters the task nodes you want to migrate from one instance to another.  For example, you could define a package with this filter definition to include all tasks:
/etc/taskmanagement/tasks

If you don't want all tasks, you may need to define the filter(s) more narrowly to pick only the ones you want to include.
For example:
/etc/taskmanagement/tasks/2015-05-04/Delta/TheTaskYouWantToMigrate

Use the browser when defining the filter to find the tasks you want to include.

See Working with Packages for details on using the Package Manager.  This Tutorial also shows how to create the package and add filters.  Once you've created a package with the filters for the tasks you want to include, then build the package and download it.  On your other instance upload the package you built and install it.  You will then see the tasks one your first instance replicated onto the second instance.

A: Additionally to what Shawn said, you also can use replication mechanisms to do the work for you, and replicate the desired nodes between any two instances.


text:
Q: SQL Friends List Creation I'm unsure of the direction on how to actually insert a SQL command to create a "friendship" between two users. I have created the tables in PHPMyAdmin I'm at a loss for what to do in order to create a friends list similar to the links below.  Let me know if you need more information.

*

*Buddy List: Relational Database Table Design

*Facebook database design?
PHP Query:
if(!empty($_POST))
{
$searchParams=$_POST['search'];
$appUser = $_POST['username'];

//check if username and or email is already registered
$query = " SELECT 1 FROM Users WHERE username = :user OR email = :email";
//now lets update what :user should be
$query_params = array(
    ':user' => $searchParams,
    ':email'=> $searchParams,
);

try {
    // These two statements run the query against your database table.
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{

}

//check results of above query and determine if username or email already exists, output results
$row = $stmt->fetch();
if ($row) {

    echo '{"success":2}';

$currentUser = mysqli_result(mysqli_query("SELECT UserID FROM Users WHERE username = $appUser"),0);
$addedUser = mysqli_result(mysqli_query("SELECT UserID FROM Users WHERE username = $searchParams"),0);

   $query2 = "Insert INTO Friends (IDUser,FriendID) VALUES (:username,:friend)";

   $query_params = array(
    ':username' => $currentUser,
    ':friend' => $addedUser
    );

 $stmt   = $db->prepare($query2);
 $result = $stmt->execute($query_params);

  echo '{"success":1}';
}
}
 else
{

}

My tables are as follows:
User:

Friends:

Current User table data:

A: Assuming you have, say, data in your user table like this:
insert into users (iduser, username) values (1, 'amy');
insert into users (iduser, username) values (2, 'bill');
insert into users (iduser, username) values (3, 'chris');

And assuming that you are representing a "friendship" between users via a record in your friends table, you would create a friendship like so:
insert into friends (iduser, friendid) values (1, 2);

This would establish a relationship between user id 1 (amy) and user id 2 (bill).
Then, to subsequently find all the friends of a user, you'd do something like this:
select username from users u
                  inner join friends f on f.friendid = u.iduser
where f.iduser = 1

This would give you the names of all friends of amy.
In response to your comment about dynamically adding friends based on their names, you could do something like this.  Here amy is logged into your site, so to simplify the query we will assume that you already have access to her user id of 1.
insert into friends (iduser, friendid)
select 1, iduser from users where username = :friendusername;


text:
Q: Stored procedure is not working? My codebehind for delete looks like this:
 protected void delete(object sender, GridViewDeleteEventArgs e)
 {
     sc.connection();
     //string st = "delete";
     int id = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].FindControl("lblpro2"))).Text);
     SqlCommand cmd = new SqlCommand("maniputale", sc.con);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@action", "delete");
     cmd.Parameters.AddWithValue("@mysid", 6);
     //cmd.Parameters.Add("@action", SqlDbType.VarChar,50).Value= st;
     //cmd.Parameters.Add("@mysid", SqlDbType.Int).Value = id;
     cmd.ExecuteNonQuery();
}

And the stored procedure is:
 ALTER PROCEDURE maniputale
 (
    @mysid int = null,
    @myproducts nvarchar(20) = null,
    @mydescription varchar(50) = null,
    @myprice int = null,
    @mybrand varchar(20) = null,
    @mymid int = null,
    @action varchar = null
 )
 as
 Begin
     set NOCOUNT ON;

     if @action = 'insert'
     Begin
         Insert into sub_catTbl(products,description,price,brand,mid)
         values(@myproducts,@mydescription,@myprice,@mybrand,@mymid)
     End

     else if @action = 'select'
     Begin
         select * from sub_catTbl
     End

     else if @action = 'update'
     Begin
         update sub_catTbl set products=@myproducts,description = @mydescription,price =@myprice,brand=@mybrand,mid=@mymid
     End

     else if @action = 'delete'
     Begin
         delete from sub_catTbl where  sid=@mysid;
     End

 End

But it's not working. It neither shows any change nor shows an error.
IS there any way to check if the stored procedure is executing just like we have linebreaker to check .cs files?

A: You can run your SP in SSMS and debug like you would your c# code. However, if you just run it manually it will most likely be failing and you will see an error returned; if your SP is throwing an error it doesn't return to your web application be default.
Here's what you get when debugging:

You can step in/out/over etc like any other code - very useful in situations like this.