text:
Q: how to open and resuse fragment (depending Item) from an item clicked on a ListView fragment tab How to popup a new fragment and reuse it (depending on the item selected ) When an item from the ListView is clicked. I already tried to use OnItemClickListener() instead of OnClickListene
public void onItemClick(AdapterView parent, View view, int position, long id)
but it is not working either,  any help would be appreciated
please refer to the screenshot attached
Thanks
-- Fragment ListView Class--

public class WorkOutFragmentForearm extends Fragment {

    private String[] exercisesForearmNames; private String[] exerciseForearmType;
    private String[] exerciseForeamNumber;

    private int[] image = { R.drawable.forearm,

    };

    private ArrayList<WorkOutListNameListExercises> mForearmsArray;

    private RecyclerView mForearmRecyclerView; private ForearmAdapter mAdapter;

    @Override public void onCreate(Bundle savedInstanceState) {

        Resources res = getResources();

        // Initialize array from info form XML strings exercisesForearmNames =
        res.getStringArray(R.array.exercisesForearmNames); exerciseForearmType =
        res.getStringArray(R.array.exerciseForearmType); exerciseForeamNumber =
        res.getStringArray(R.array.exerciseForeamNumber);

        mForearmsArray = new ArrayList<>();

        for (int i = 0; i < exercisesForearmNames.length; i++) {
        WorkOutListNameListExercises s = new WorkOutListNameListExercises();

            s.setName(exercisesForearmNames[i]);
            s.setExerciseType(exerciseForearmType[i]);
            s.setExerciseNumber(exerciseForeamNumber[i]); s.setImageId(image[i]);
            mForearmsArray.add(s); }

        super.onCreate(savedInstanceState);

    }// end Main

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup
    container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.workout_recycler_forearm, container,
        false); mForearmRecyclerView = (RecyclerView)
        view.findViewById(R.id.recycler_view);

        mForearmRecyclerView.addItemDecoration(new
        SimpleDividerItemDecoration(getResources()));
        mForearmRecyclerView.setLayoutManager(new
        LinearLayoutManager(getActivity())); updateUI();

        // -------------------------------------------------------------------------
        ---------- // When Back Button is clicked
        view.setFocusableInTouchMode(true); view.requestFocus();
        view.setOnKeyListener(new View.OnKeyListener() { @Override public boolean
        onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    // Display Drawer when back button is clicked if drawer not // display
                    not go back without FragmentTransaction Code
                    MainActivity.mDrawerLayout.openDrawer(Gravity.LEFT);

                    return true; } else {

                    return false; } } });

        return view;

    }// end Main

    private void updateUI() { mAdapter = new ForearmAdapter(mForearmsArray);
    mForearmRecyclerView.setAdapter(mAdapter); }

    // Inner Class private class ForearmHolder extends RecyclerView.ViewHolder {

        private WorkOutListNameListExercises mForearm; public ImageView mImageView;
        public TextView mNameTextView; public TextView mTypeNumberTextView;

        public ForearmHolder( View itemView){ super(itemView);

            mImageView = (ImageView) itemView.findViewById(R.id.imageView);
            mNameTextView = (TextView)
            itemView.findViewById(R.id.textview_name); mTypeNumberTextView =
            (TextView) itemView.findViewById(R.id.textview_type_number);

           itemView.setOnClickListener(new View.OnClickListener() {

               @Override public void onClick(View view) {

Bundle bundle = new Bundle();

                if (mForearm.getName().equals(exercisesForearmNames[0])) {

FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction(); Fragment
fragmentItem1 = new FragmentItem1(); fragmentItem1.setArguments(bundle);
fragmentTransaction.add(R.id.my_frame_list, fragmentItem1);
fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();

                    Toast.makeText(getActivity(),mForearm.getName() + "Item 1",
                    Toast.LENGTH_SHORT).show(); }

                });//end  View.OnClickListener

        }// end Method

        public void bindData(WorkOutListNameListExercises s) { mForearm = s;

            mImageView.setImageResource(s.getImageId());
            mNameTextView.setText(s.getName());
            mTypeNumberTextView.setText(s.getExerciseType() + ":" +
            s.getExerciseNumber());

        }

    }// end Inner Class

    // Inner Class private class ForearmAdapter extends
    RecyclerView.Adapter<ForearmHolder>

    { private ArrayList<WorkOutListNameListExercises> mForearmsArray;

        public ForearmAdapter(ArrayList<WorkOutListNameListExercises>
        WorkOutListNameListExercises) { mForearmsArray =
        WorkOutListNameListExercises;

        }

        @Override public ForearmHolder onCreateViewHolder(ViewGroup parent, int
        viewType) { LayoutInflater layoutInflater =
        LayoutInflater.from(getActivity()); View view =
        layoutInflater.inflate(R.layout.workout_items_list_info, parent, false);
        return new ForearmHolder(view);

        }

        @Override public void onBindViewHolder(ForearmHolder holder, int position) {

            WorkOutListNameListExercises s = mForearmsArray.get(position);
            holder.bindData(s);

        }

        @Override public int getItemCount() { return mForearmsArray.size();

        } }// end Inner Class

}// end Class

WorkOutListNameListExercises.java
public class WorkOutListNameListExercises { private String ExreciseName; private
String ExerciseType; private String ExerciseNumber; private int ExerciseImageId;

    public String getName() { return ExreciseName; }

    public void setName(String ExreciseName) { this.ExreciseName = ExreciseName; }

    public String getExerciseType() { return ExerciseType; }

    public void setExerciseType(String ExerciseType) { this.ExerciseType =
    ExerciseType; }

    public String getExerciseNumber() { return ExerciseNumber; }

    public void setExerciseNumber(String ExerciseNumber) { this.ExerciseNumber =
    ExerciseNumber; }

    public int getImageId() { return ExerciseImageId; }

    public void setImageId(int ExerciseImageId) { this.ExerciseImageId =
    ExerciseImageId; } }

A: Okay! So you are using a recyclerview and on the itemview you have also added an onClickListener. Also you are creating bundle there. Well you are 99% already there!
You haven't added anything into the bundle. To add some values into it do
bundle.putString("key1","value1");

You can pass an Array as well as an ArrayList using putStringArray() and putStringArrayList()
We don't need to check whether its the first, second or the third item the user is clicking on. Do this in the bindData() which is already providing us the position of the item, using this position we will pass the appropriate values to the fragment. So our code will look like this.
public void bindData(WorkOutListNameListExercises s) {

itemView.setOnClickListener(new View.OnClickListener() {

   @Override
     public void onClick(View view) {
       Bundle bundle = new Bundle();
       bundle.putString("forearmName",s.getName());
       bundle.putString("forearmType",s.getType());
       bundle.putString("forearmNumber",s.getNumber());

       FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
       Fragment fragmentItem1 = new FragmentItem1();
       fragmentItem1.setArguments(bundle);
       fragmentTransaction.add(R.id.my_frame_list, fragmentItem1);
       fragmentTransaction.addToBackStack(null);
       fragmentTransaction.commit();

       //Your Toast message!
    }
  }
}

Now on the FragmentItem1 to reuse it. Do this in the onCreate
private String exercisesForearmName, exerciseForearmType, exerciseForeamNumber;
@Override
public void onCreate(Bundle savedInstanceState) {
Bundle bundle=this.getArguments();
exercisesForearmNames=bundle.getString("forearmName");
exerciseForearmType=bundle.getString("forearmType");
exerciseForearmNumber=bundle.getString("forearmNumber");
}

now just assign the values to the view which you intend to in the onCreateView()
Done. Hope this helps.


text:
Q: MVC5 - Block Controller OutputCache for specific Action I have a controller where the class has
[OutputCache(NoStore = true, Duration = 0)]

The controller has an child action. This doesn't need anything to do with OutputCache. Is there any way to tell this action not to use the class value?
The alternatives seems to be to set the attribute on all non-child actions, or to create a separate controller for the child actions.
I'd quite happily keep the same cache settings on the child action, except that child actions don't support NoStore, so you get an error. [OutputCache(Duration=0)] is also invalid.
To address the point that no caching is the default, so why set this in the first place? This changes the headers the client receives from Cache-Control: private to
Cache-Control: private, no-store, max-age=0
Pragma: no-cache

I.e. a conforming user agent won't cache it locally. Note this is for an intranet site where someone might lose their access device, rather than an Internet site.

A: OutputCache is an inheritable attribute. That means you can override the behavior of it when set on a controller by simply adding to one of your actions with something different. For example:
[OutputCache(Duration = 3600)]
public class MyController : Controller
{
    [OutputCache(Duration = 60)]
    public ActionResult Foo()
    {
        return View();
    }

    public ActionResult Bar()
    {
        return View();
    }
}

The Bar action will be cached for 1 hour based on the controller-level setting, while Foo will be cached for just 1 minute.
That said, I'm not sure what you're trying to do here. Using NoStore = true, Duration = 0 effectively disables caching, so you don't really need to do anything with a child action at that point to have it not cached, as the controller specifies already that nothing inside really is going to be cached. Logically, you would rather add OutputCache to actions in that controller you do want to cache, but then at that point, disabling cache on the controller-level makes no sense: that's effectively the default anyways.

A: I'm in similar situation. In my case I'm trying to register the OutputCache attribute as global filter and it is giving me the same error when a View includes child action. What I ended up doing is creating a custom attribute inheriting OutputCacheAttribute. And have it skip any actions decorated with ChildActionOnly attribute. Assuming all your child actions are decorated with such.
public class NoCacheAttribute : OutputCacheAttribute
{
    public NoCacheAttribute()
    {
        base.NoStore = true;
        base.Duration = 0;
    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(ChildActionOnlyAttribute), false).Any()) return;

        base.OnActionExecuting(filterContext);
    }
}

Update:
Better yet, use filterContext.IsChildAction to detect child
public class NoCacheAttribute : OutputCacheAttribute
{
    public NoCacheAttribute()
    {
        base.NoStore = true;
        base.Duration = 0;
    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.IsChildAction) return;

        base.OnActionExecuting(filterContext);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to execute Python functions using Hypothesis' composite strategy? I am trying to execute a function decorated with Hypothesis' @strategy.composite decorator.
I know I can test functions using the @given decorator, such as -
from hypothesis import given
from hypothesis import strategies as st

@given(st.integers(min_value=1))
def test_bar(x):
    assert x > 0

with pytest using - pytest <filename.py>.
But in the case of a function with the @strategy.composite decorator like -
from hypothesis import strategies as st
from hypothesis import given
import pytest

@st.composite
def test_foo(draw):
    arg1 = draw(st.integers(min_value=1))
    arg2 = draw(st.lists(st.integers(), min_size=arg1, max_size=arg1))
    print(arg1, " ", arg2)
    assert(len(arg2) == arg1)

I am unable to execute the tests in a similar way.
When using pytest I am unable to execute the tests (using python to execute the python file does nothing) -
[reik@reik-msi tests]$ pytest testhypo.py
==================================== test session starts ====================================
platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1
rootdir: /home/reik/tests
plugins: hypothesis-5.16.0, lazy-fixture-0.6.3
collected 1 item

testhypo.py F                                                                         [100%]

========================================= FAILURES ==========================================
_________________________________________ test_foo __________________________________________

item = <Function test_foo>

    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_call(item):
        if not hasattr(item, "obj"):
            yield
        elif not is_hypothesis_test(item.obj):
            # If @given was not applied, check whether other hypothesis
            # decorators were applied, and raise an error if they were.
            if getattr(item.obj, "is_hypothesis_strategy_function", False):
>               raise InvalidArgument(
                    "%s is a function that returns a Hypothesis strategy, but pytest "
                    "has collected it as a test function.  This is useless as the "
                    "function body will never be executed.  To define a test "
                    "function, use @given instead of @composite." % (item.nodeid,)
                )
E               hypothesis.errors.InvalidArgument: testhypo.py::test_foo is a function that returns a Hypothesis strategy, but pytest has collected it as a test function.  This is useless as the function body will never be executed.  To define a test function, use @given instead of @composite.

/usr/lib/python3.8/site-packages/hypothesis/extra/pytestplugin.py:132: InvalidArgument
================================== short test summary info ==================================
FAILED testhypo.py::test_foo - hypothesis.errors.InvalidArgument: testhypo.py::test_foo is...
===================================== 1 failed in 0.06s =====================================

I tried adding the function call test_foo() but I got the same error.
Then I tried adding @given above the function and got a different error -
========================================== ERRORS ===========================================
________________________________ ERROR at setup of test_foo _________________________________
file /usr/lib/python3.8/site-packages/hypothesis/core.py, line 903
      def run_test_as_given(test):
E       fixture 'test' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

/usr/lib/python3.8/site-packages/hypothesis/core.py:903
================================== short test summary info ==================================
ERROR testhypo.py::test_foo

if I do @given() - note the extra braces, instead, I get another error -
========================================= FAILURES ==========================================
_________________________________________ test_foo __________________________________________

arguments = (), kwargs = {}

    def wrapped_test(*arguments, **kwargs):
>       raise InvalidArgument(message)
E       hypothesis.errors.InvalidArgument: given must be called with at least one argument

/usr/lib/python3.8/site-packages/hypothesis/core.py:234: InvalidArgument
================================== short test summary info ==================================
FAILED testhypo.py::test_foo - hypothesis.errors.InvalidArgument: given must be called wit...

I tried wrapping the code inside another function -
from hypothesis import strategies as st
from hypothesis import given
import pytest

def demo():
    @st.composite
    def test_foo(draw):
        arg1 = draw(st.integers(min_value=1))
        arg2 = draw(st.lists(st.integers(), min_size=arg1, max_size=arg1))
        print(arg1, " ", arg2)
        assert(len(arg2) == arg1)

but that did not work either -
[reik@reik-msi tests]$ python testhypo.py
[reik@reik-msi tests]$ pytest testhypo.py
==================================== test session starts ====================================
platform linux -- Python 3.8.3, pytest-5.4.3, py-1.8.1, pluggy-0.13.1
rootdir: /home/reik/tests
plugins: hypothesis-5.16.0, lazy-fixture-0.6.3
collected 0 items

=================================== no tests ran in 0.00s ===================================

(I also tried putting the demo function call at the end of the file, but that did not change the testing behaviour in any way)
The Hypothesis quick start guide says that calling the function would work, but it clearly does not. (To be fair, the documentation does not specify how to run tests with @composite)
How do I test the functions that are decorated with @strategy.composite? I do not have to use pytest - I would prefer not having to use it actually, but it seemed the easiest way to test the functions (which were decorated with @given) so I decided to go that route.

A: @st.composite is a helper function for defining custom strategies, not tests.
What you're trying to do can be accomplished by using @given and st.data():
@given(st.data())
def test_foo(data):
    x = data.draw(st.integers())
    ...

https://hillelwayne.com/post/property-testing-complex-inputs/ gives a good overview of how these techniques are used.

A: I had the same issue. Here is a minimal and complete working example of using @composite.
@dataclass
class Container():
    id: int
    value: str

@st.composite
def generate_containers(draw):
    _id = draw(st.integers())
    _value = draw(st.characters())
    return Container(id=_id, value=_value)

@given(generate_containers())
def test_container(container):
    assert isinstance(container, Container)
    assert isinstance(container.id, int)
    assert isinstance(container.value, str)


text:
Q: проверка сохранения файла php Найдена одна особенность в счетчике скачиваний файлов.
При нажатии кнопки "отмена" в диалоге сохранения файла счетчик все равно накручивается (чем тогда этот счетчик отличается от счетчика кликов по ссылке?).
Примерный код:
if (isset($_GET['file'])) {
    $filename = $_GET['file'];

    $conn = mysqli_connect("localhost", "root", "", "test");

    if (!$conn) {
        die("Connection failed: " . mysql_connect_error());
    }

    $select = "SELECT counter FROM test_counter WHERE name='$filename'";
    $result = mysqli_query($conn, $select);

    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $counter = $row['counter'];
        $counter += 1;
        send_file();
        $update = "UPDATE `test_counter` SET `counter`=$counter WHERE name='$filename'";
        $result = mysqli_query($conn, $update);
    }
    else
        $result = mysqli_query($conn, "INSERT INTO `test_counter`(`name`, `counter`) VALUES ('$filename', 1)");

    mysqli_close($conn);

}

function send_file() {
    $file = __DIR__.'\\download.php';
    header('X-SendFile: ' . realpath($file));
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
}

Собственно вопрос в том, можно ли как-то проверить, что пользователь действительно сохранил файл (а не нажал "отмена"), сделав что-то вроде (ну или каким-то другим способом):
$dialog = send_headers();

if ($dialog->get_result() == OKAY) {
    update_counter();
}

A: Решил проблему, используя загрузку по частям в PHP.
Выглядит примерно следующим образом:
// send file (it shows save file dialog)
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($filepath));
header('Content-Disposition: filename='.$filename);
flush();

$file = fopen($filepath, "r");

while(!feof($file))
{
    // send the current file part to the browser
    print fread($file, round($download_rate * 1024));
    // flush the content to the browser
    flush();
    // sleep one second
    sleep(1);
}

// if all are right and file was downloaded
if (feof($file)) {
    update_current_counter_or_insert_new_one_in_DATABASE();
}

fclose($file);

Эта ссылка помогла при поиске решения.


text:
Q: Probability calculation from Normal Distribution Assume that we want to perform a one-sample t-test with null hypothesis $\mathbb{E}X=0$ and an alternative $\mathbb{E}X > 0$. We have an i.i.d. sample $x=(x_1, \ldots, x_{n})$ from X. Let n=100. To simplify calculations, let us assume that we have a large enough sample to reliably estimate the variance of X from the data and apply the central limit theorem. In other words, we will assume that sample mean $\bar{x}$ is distributed under normal law with expected value \mathbb{E}X and variance that is equal to $\mathrm{\mathop{Var}}_{+}(x)/n$, where $\mathrm{\mathop{Var}}_{+}(x)$ is unbiased sample variance of x. Assume that $\mathrm{\mathop{Var}}_{+}(x)=5$.
Find value $x_{crit}$ such that probability to observe $\bar{x}\ge x_{crit}$ is equal to 0.05. (Use scipy.stats.norm.ppf.).
Solution:
$P(\bar{x} \ge x_{crit}) = P(N(0,5/100) > Xcrit = 0.05\\P(Z > \frac{x_{crit}}{5/10})\\where Z \sim N(0,1)$
$\frac{x_{crit}}{5/10} = 1.645 ~~(using~ scipy.stats.norm.ppf(0.95)$
$x_{crit} = 1.645 \times \frac{5}{10} = 0.3678 \approx 0.37$
Assume that correct $\mathbb{E}X=0.5$. Find probability to observe $\bar{x} < x_{crit}$ in this case. (Use $x_{crit}$ found previously. Take into account the correct distribution of $\bar{x}$.)
What I used is as follows:
I created a Normal distribution with $\mathbb{E}X=0.5$ and $\sigma^2 = 5/100$ and then calculated the cumulative probability distribution to calculate the required probability.
$probability = scipy.stats.norm(0.5, 5/100).cdf(0.37) \approx 0.004$
But, as you may see it is extremely small for such a large region. May someone please suggest a correction?

A: I was using the wrong sigma.
$sigma = \sqrt{5} / 10$
Using the value I got the $probability \approx 0.28$.
For the same I used:
$scipy.stats.norm(loc=0.5, scale=numpy.sqrt(5)/10).cdf(0.37) \approx 0.28$


text:
Q: Proper PHP syntax for cycleing through an array with the index I am newish to PHP and I am trying to cycle through an array and stop after 5 items.
I am using the following:
    $images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
            // Display the thumbnails and link to the medium image for each image
            foreach ( $images as $index => $image) {

                echo '

';
            }
            while ( $index < 5 );
        }

Although it does not seem to work...
Am I doing something wrong?
Thanks in advance

A: If the array has a zero based index you can do:
foreach ( $images as $index => $image) {
    if ($index == 5) break;
    echo '

';
}

Otherwise you can add your own counter:
$i = 0;
foreach ( $images as $index => $image) {
    $i++;
    if ($i == 5) break;
    echo '

';
}

What you tried is another type of loop:
$index = 0;
do {
    echo '

';
    $index++;
} while ( $index < 5 );

Or:
$index = 0;
while ( $index < 5 ) {
    echo '

';
    $index++;
}

Another alternative would be a for loop:
for($index=0; $index < 5; $index++) {
    echo '

';
}

A:    $images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
   $nm = 0;
   foreach ( $images as $index => $image) {
      if($nm < 5){
           echo '

';
         }
       $nm++;
       }

A: It should be like this:
$images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;

$i = 0;
// Display the thumbnails and link to the medium image for each image
foreach ( $images as $index => $image) {
    if ($i == 5) break;
    echo '

';
    $i++;
}

while is a loop on its own, just like foreach.

A: Given that $index is an integer you could just break out of the loop:
foreach ($images as $index => $image) {
    echo '

';
    if ($index >= 5) {
        break;
    }
}


text:
Q: Is it possible to have Oracle SSL Configuration in free version of 21C database? Is it possible to have Oracle SSL Configuration in free version of 21C database?
I followed the steps given in https://oracle-base.com/articles/misc/configure-tcpip-with-ssl-and-tls-for-database-connections
But I am getting ORA-28864: SSL connection closed gracefully error always.
Can any one help on this?


text:
Q: Pick color that's further away from white I'm getting the computed HEX of the color and background color of body like so:
function rgb2hex(rgb){
  rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

var color = rgb2hex(window.getComputedStyle(document.getElementsByTagName("body")[0]).color);
var bg = rgb2hex(window.getComputedStyle(document.getElementsByTagName("body")[0]).backgroundColor);

I need to pick one of these colors to be used as a text color on a white background. However, a problem occurs when the page background is dark and the color is light/white. Therefore, I need to intelligently pick one of these to be used as the text color.
How can I find out which one of color and bg is furthest away from #fff?

A: You need to calculate relative luminance of both colors. Color with the lower luminance, will be the one further from white. Formula for this calculation is provided in the linked article and in my code below:

{
    const getRGBLuminance = (string) => {
        const rgb = string.replace(/[^\d ]/g, '').split(' ');
        return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
    }

    const bodyStyle        = window.getComputedStyle(document.body),
          colorLuminance   = getRGBLuminance(bodyStyle.color),
          bgColorLuminance = getRGBLuminance(bodyStyle.backgroundColor);

    if (colorLuminance < bgColorLuminance) {
        console.log('Text color is further from #FFF.');
    }
    else if (colorLuminance > bgColorLuminance) {
        console.log('Background color is further from #FFF.');
    }
    else {
        console.log('Both color and background color are equally far from #FFF.');
    }
}
/* Only for demonstration */
body {
  background-color: #ACE;
  color: #000;
}


text:
Q: How is casting the column name in a SQL query different from casting the value Say for example
cast(PURCHASE_DATE as date) > '2020-01-01'
vs.
PURCHASE_DATE > cast('2020-01-01' as date format)
I have a few questions about the above:

*

*I tested these on my application and they both lead to the same result. Is there a scenario where one would fail?

*How are these two expressions different in terms of resource usage?

*Does casting a column cast every value it wants to compare, as opposed to having the right hand side of that inequality cast once to be compared with all the values in that column?

A: If you use PURCHASE_DATE as DATETIME type colum, you could use CAST(colum AS DATE) so you can obtain better usage of the type of the colum and maybe in terms of scalability. The other way you just hardcoded the date variable and not use the benefits of the data type like change time zones if you ever use that. refer to: 11.2.2 The DATE, DATETIME, and TIMESTAMP Types

A: Incidentally, you don't need to cast a date is you use it this way:
WHERE PURCHASE_DATE > '2020-01-01'

or this, for numerics:
WHERE PURCHASE_ID > '0001000'

Teradata allows a lot of implicit casting.


text:
Q: Why would my Windows XP suddenly become "not activated"? I have a Windows XP system that has been running fine for a long time. However, yesterday I rebooted it for the first time in a while, and when it came back up, it did not let me log in to the system and came up with a box saying:
Windows Product Activation
This copy of Windows must be activated with Microsoft before you can log on.
Do you want to activate Windows now?

Because the system does not have any internet access, I tried to run through the activation system by phone, but the key was rejected. I then rebooted the system again. It came up normally straight away - no activation screen, no trouble.
I have seen this on other computers before, but I have never found out why it happens. Does anyone know what could be causing this?

A: Windows Activation uses the internal identifiers of a few hardware components to guess when the operating system is being started on another computer. It happens, especially on systems that are starting to age a little, that one or more hardware components responds just a little late or in an incorrect fashion, so that is it missing from the mix of info that is used for this check. As noted above a reboot may fix this. If it keeps re-occuring, consider checking if all components are still firmly attached within the enclosure and there's no dust-build-up on or around the circuit-boards and ventilation fans.

A: You can try to login windows in safe mode, Right click on my computer click properties. Under general tab you will find an option for change product key. Click on it and contact Microsoft they will provide you product key else you need to reinstall windows.

A: Even though it doesn't have internet access (would've probably failed anyways since it failed over the phone) have you tried running a malware scanner on it?
Other possibilities are the activation dlls could have become corrupt. Running scf /scannow could fix those. If not malware then I would think your WPA.DBL file could be corrupt, I believe this is where activation state would be stored in XP.


text:
Q: How do I connect my login screen to a specific website & database to accept usernames and passwords? I am creating a login page for an app that I am working on and in order to get the login page up I followed this tutorial(http://dipinkrishna.com/blog/2012/03/iphoneios-programming-login-screen-post-data-url-parses-json-response/). I want to know why the login page that I created isn't working. I'm pretty sure it may have something to do with connecting the database to the app. Any clues on how I could do this ? I know the username and password works because I tried it on the website and it worked perfectly. Any clue as to why it won't work in the app ? Thanks for the help !
Here is a snippet of my code:
ViewController.m
- (IBAction)loginClicked:(id)sender {
    @try {

        if([[username text] isEqualToString:@""] || [[password text] isEqualToString:@""] ) {
            [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[username text],[password text]];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://thespot2g.com/login"];

            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

            NSLog(@"Response code: %d", [response statusCode]);
            if ([response statusCode] >=200 && [response statusCode] <300)
            {
                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);

                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
                NSLog(@"%d",success);
                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

                } else {

                    NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                    [self alertStatus:error_msg :@"Login Failed!"];
                }

            } else {
                if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Login Failed!"];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Login Failed." :@"Login Failed!"];
    }
}

- (IBAction)backgroundClick:(id)sender {
    [username resignFirstResponder];
    [password resignFirstResponder];

}

Here is what i get in the console after failing to login with correct credentials
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta http-equiv="content-language" content="en-US">
  <meta name="author" content="Innovatrix Labs, LLC">
  <meta name="copyright" content="The Spot2g, LLC">
  <meta name="description" content="connecting nightlife enthusiasts with their favorite venues through a real time feed of drink specials, ent, waits, cover charges, and etc!">
  <meta name="keywords" content="The Spot2g, Spot2g, Bar Specials, Drink Specials, Awesome Venues, Innovatrix Labs">
  <meta name="city" content="State College, Williamsport">
  <meta name="state" content="Pennsylvania">
  <title>The Spot2g</title>
  <link rel="shortcut icon" href="http://thespot2g.com/favicon.ico"/>
  <link rel="stylesheet" type="text/css" href="http://thespot2g.com/styles/spot2g.css"/>
  <link rel="stylesheet" type="text/css" href="http://thespot2g.com/styles/bootstrap.css"/>

Log In
 |

Register

 Follow us on twitter: @TheSpot2g !! at TheSpot2g

Venues

Arena Bar & Grill

Autoport

Bar Bleu

Brewery

Cafe 210

Champs Sports Grill

Chrome

Darkhorse

Gigi's

Gingerbread Man

Hi-way Pizza

Home Delivery Pizza

Indigo

Inferno

Kildare's

Levels

Lions Den

Mad Mex

Mt. Nittany Inn

Otto's Pub and Brewery

Phyrst

Phyrst Upstairs

Pickles

Pletcher's Beer Distributor

Rotelli's

Shandygaff

Sharkies

The Rathskellar

The Saloon

TheSpot2g

W.R. Hickey Beer Distributor

Westside Stadium Bar and Grill

Z Bar

Zeno's

Whats Going On?

 What is The Spot2g?

 Follow us on Twitter!

 Like us on Facebook!

<form action="http://thespot2g.com/login" method="post" accept-charset="utf-8">

Login to the Spot2g

        Username

<input type="text" name="login-username" value="" id="login-username"  />

        Password

<input type="password" name="login-password" value="" id="login-password"  />

<input type="submit" name="login" value="Login"  />

The Username field is required.

The Password field is required.

</form>

 Featured Venue

© 2012 The Spot2g, LLC All Rights Reserved.

Powered by Innovatrix Labs

2013-10-28 23:55:24.281 Spot2G[1069:a0b] (null)
2013-10-28 23:55:24.282 Spot2G[1069:a0b] 0

A: I'm not sure about your specific issue, but can offer up some general advice:
Use OAuth
To save users having to log in with the username & password credentials on every use of the app, you might want to look at securing your app using the OAuth security protocol. This is how Facebook, Twitter, Dropbox, Instagram, etc works.
The basis of the OAuth protocol is:

*

*User authenticates once using their user-name and password credentials.

*The authentication provider assigns a token to the app that can be used for subsequent requests.

*This token has an expiry date. It can also be revoked by the user, by visiting a site, making it secure in the event of a lost device.

You can set up your own OAuth provider on the backend and a consumer using eg GTMOAuth2. You can also use one of the above (Facebook, Dropbox, Instagram, etc) as a single-sign-on provider.
Single Sign-on:

*

*Use the client SDK (Facebook, LinkedIn, etc) or a generic OAuth library to obtain an access token.

*Send this access token to the backend.

*The backend will attempt authentication using the token. If successful, assign a session for x minutes.


text:
Q: What is the "mood" you are in when you shake your head called? You see that somebody just cannot figure out how to open a new tab (something you find easy) and you shake your head. What is this mood or feeling called?

A: You might feel 'Frustrated' by the other person's poor grasp of what, to you, is a simple concept...

frustrated frʌˈstreɪtɪd/ adjective adjective: frustrated
1.feeling or expressing distress and annoyance resulting from an inability to change or achieve something.
"young people get frustrated with the system"


text:
Q: When I close Nautilus, copy operation gets cancelled In Windows, If I copy-paste and then close the file explorer while the operation is running, the copy operation continues.
But in Ubuntu 18.04 when I close the file explorer (Nautilus), the copy operation gets cancelled.
How can I continue copying while I close Nautilus.

A: Check carefully if the file operation is really aborted, because that is not normal behaviour. Also in Ubuntu, the normal behaviour is for a file operation to continue when you close a nautilus window (either by the close button, or the hotkeys ctrl+w to close a single window, or ctrl+q to close all windows: "close the application").
Only when nautilus is fully terminated will a file operation be aborted. You can reproduce that by starting a large file operation, and then issuing the command "killall nautilus" in the terminal. This fully closes the nautilus process down, and with it ongoing file operations. When, however, you close windows or quit nautilus using the graphical user interface or standard hotkeys, nautilus remains active in the background.


text:
Q: Installing pg_profile for postgreSql I am trying to use the extension pg_profile in order to get awr-like reports in postgreSql.
In githab README file it says:
https://github.com/zubkov-andrei/pg_profile
# cp pg_profile* `pg_config --sharedir`/extension

and then:
postgres=# CREATE EXTENSION pg_profile;

But this fails with:
ERROR:  could not open extension control file "/usr/share/postgresql/11/extension/pg_profile.control": No such file or directory

and indeed I can only find pg_profile.control.tpl in under this directory (and in the zip file I downloaded from Github).
IF I try to follow the tutorial instructions saying:
https://dbtut.com/index.php/2019/03/29/postgresql-awr/

After downloading the file to the server, go the directory you
downloaded and follow the steps below. We're running the Make command.
make install

Then I get this error:
# make install
Makefile:16: ../../src/Makefile.global: No such file or directory
Makefile:17: /contrib/contrib-global.mk: No such file or directory
make: *** No rule to make target '/contrib/contrib-global.mk'.  Stop.

Any idea how to solve these?

A: I was able to run CREATE EXTENSION in PG 12.3 database but to do that:

*

*I have removed the line  PG_CONFIG = /usr/local/pgsql/bin/pg_config in Makefile:

*I have run as root:
$ make USE_PGXS=y install
      /usr/bin/mkdir -p '/usr/pgsql-12/share/extension'
      /usr/bin/mkdir -p '/usr/pgsql-12/share/extension'
      /usr/bin/install -c -m 644 .//pg_profile.control '/usr/pgsql-12/share/extension/'
      /usr/bin/install -c -m 644  pg_profile--0.1.1.sql pg_profile.control '/usr/pgsql-12/share/extension/'

And after that I could run without error:
postgres=# CREATE EXTENSION dblink;
postgres=# CREATE EXTENSION pg_stat_statements;
postgres=# CREATE EXTENSION pg_profile;

postgres=# \dx
                                       List of installed extensions
        Name        | Version |   Schema   |                         Description
--------------------+---------+------------+--------------------------------------------------------------
 dblink             | 1.2     | public     | connect to other PostgreSQL databases from within a database
 pg_profile         | 0.1.1   | public     | PostgreSQL load profile repository and report builder
 pg_stat_statements | 1.7     | public     | track execution statistics of all SQL statements executed
 plpgsql            | 1.0     | pg_catalog | PL/pgSQL procedural language
 postgres_fdw       | 1.0     | public     | foreign-data wrapper for remote PostgreSQL servers
(5 rows)


text:
Q: using return in EF transaction .net core 2.0 I am using a similar code like this and I was wondering if using return in this context is possible/acceptable as a best practice coding.
public static async void Run()
{
  using (var transaction = dbContext.Database.BeginTransaction())
  {
    [some code]
    if (list == null || list.Count == 0) return;
    [continue code]
    transaction.Commit();
  }
  catch
  {
    transaction.Rollback();
  }
}

Will the transaction either commit or rollback ?


text:
Q: more values from one table in other table under same row I have table Employers, with: ID, surname, name, language_id.
Other table is Languages, with: ID, language.
How to put if one employer speak more than one language?

A: You can create an other table with the following fields :
ID (int,primary_key)

id_Employers(int)

id_Languages(int)

And remove language_id from Employers table

A: You want to remove lanugauge_id from  Employers Table and create one new table which contain multi relation between user_id and language_id so you want to take
    YOUR NEW TABLE NAME(i.e : user_languages)

    COLUMN NAME :
    --------------------------
    1. id (int,primary_key)

    2. employers_id(int)

    3. language_id(int)

    4. create_time(DateTime)

Using this you will enter multiple entries for multiple languages from single user where you want to enter employers table primary key in employers_id and languages table primary key in language_id


text:
Q: How to print a range of lines with sed except the one matching the range-end pattern? I wonder if there is a sed-only way to print a range of lines, determined by patterns to be matched, except the one last line matching the end pattern.
Consider following example. I have a file
line  1
line  2
line  3
ABC line  4
+ line  5
+ line  6
+ line  7
line  8
line  9
line 10
line 11
line 12

I want to get everything starting with ABC (including) and all the lines beginning with a +:
ABC line  4
+ line  5
+ line  6
+ line  7

I tried it with
sed -n '/ABC/I,/^[^+]/ p' file

but this gives one line too much:
ABC line  4
+ line  5
+ line  6
+ line  7
line  8

What's the easiest way (sed-only) to leave this last line out?

A: There might be better ways but I could come up with this sed 1 liner:
sed -rn '/ABC/,/^[^+]/{/(ABC|^\+)/!d;p;}' file

Another sed 1 liner is
sed -n '/ABC/,/^[^+]/{x;/^$/!p;}' file

One more sed 1 liner (and probably better)
sed -n '/ABC/I{h;:A;$!n;/^+/{H;$!bA};g;p;}' file

A: The easiest way (I'll learn something new if anyone can solve this with one call to sed), is to add an extra sed at the end, i.e.
sed -n '/ABC/I,/^[^+]/ p' file | sed '$d'
ABC line  4
+ line  5
+ line  6
+ line  7

Cheating, I know, but that is the beauty of the Unix pipe philosphy. Keep whitiling down your data until you get what you want ;-)
I hope this helps.

A: This might work for you:
 sed '/^ABC/{:a;n;/^\(ABC\|+\)/ba};d' file

EDIT: to allow adjacent ABC sections.

A: Well, you have selected your answer. But why aren't you using /^(ABC|\+)/ ? Or am i mis-understanding your requirement?
If you want to find those + lines AFTER a search for ABC is found
awk '/ABC/{f=1;print} f &&/^\+/ { print }' file

This is much simpler to understand than crafting cryptic sed expressions. When ABC is found, set a flag. When lines starting with + is found and flag is set, print line.


text:
Q: Find closest factor to a number, of a number I am trying to automate the finding of the closest factor of a number to another number;
Example:
Closest factor of 700 to 30 is 28 (30 does not go into 700, but 28 does).
An obvious solution is just to get all the factors of 700 and do a simple distance calculation to find the nearest factor to 30, but this seems to be inefficient.
Another solution is to find all the base prime factors, like:
private List<Integer> getPrimeFactors(int upTo) {
    List<Integer> result = new ArrayList<>();
    for (int i = 2; i <= upTo; i++) {
        if (upTo % i == 0) {
            result.add(i);
        }
    }
    return result;
}

And multiplying each of these numbers together to get all the combinations, and therefore find the closest.
I am trying to programme this so it is automated.
Any better solutions?

A: You don't need to calculate all factors, but you can go in both directions from the number to find its closest number which is the factor of given number
Pseduo code will be:
n= given number(dividend);
x= second number( whose closest number is required)
i=0;
if(n%x==0) print x;
else
while(true){
   if(n%(x-i)==0){
      print x-i
      break
   }
   else if(n%(x+i)==0){
     print x+i;
       break
   }
   else i=i+1
}

A: I have my solution wrapped in a small static method:
/**
* @param target the number you want the factor to be close to
* @param number the number you want the result to be a factor of
*/
private static int getClosestFactor(int target, int number) {
    for (int i = 0; i < number; i++) {
        if (number % (target + i) == 0) {
            return target + i;
        } else if (number % (target - i) == 0) {
            return target - i;
        }
    }
    return number;
}

A:     package dummy;

    public class test {

        public static void main(String[] args) {
            int factorOff = 700;
            int factorFrom = 30;
            for (int i = 2; i < factorOff; i++) {
                if (factorOff % (factorFrom + i) == 0) {
                    System.out.println(factorFrom + i);
                    i = factorOff;
                } else if (factorFrom - i > 1 && factorOff % (factorFrom - i) == 0) {
                    System.out.println(factorFrom - i);
                    i = factorOff;
                }
            }
        }
    }

A: This should be a fast solution:
public static int findClosestFactor(int number, int closeTo) {
    int result = 1;
    int currentDist = closeTo - 1;
    // stop conditions for comparison
    boolean compareSmallFactor = true;
    boolean compareLargeFactor = true;
    for (int factor1 = (int) Math.sqrt(number); factor1 > 0; factor1--) {
        if (number % factor1 == 0) {
            if (compareSmallFactor) {
                int dist1 = Math.abs(closeTo - factor1);
                if (dist1 < currentDist) {
                    result = factor1;
                    currentDist = dist1;
                }
                // factor 1 is getting always smaller
                // so you need not compare next time, if go away from target (smaller than target)
                if (factor1 <= closeTo) {
                    compareSmallFactor = false;
                }
            }

            if (compareLargeFactor) {
                int factor2 = number / factor1;
                int dist2 = Math.abs(closeTo - factor2);
                if (dist2 < currentDist) {
                    result = factor2;
                    currentDist = dist2;
                }
                // factor 2 is getting always larger
                // so you need not compare next time, if go away from target (larger than target)
                if (factor2 >= closeTo) {
                    compareLargeFactor = false;
                }
            }

            // if both factors go away from target, you can cancel
            if (!compareSmallFactor && !compareLargeFactor) {
                break;
            }
        }
    }
    return result;
}

A: You can factorize the number, then use a powerset generator (for a multiset[1]) to search for the group of factors that get closest to the max without going over.
The powerset generator can be modified to prevent further iteration down branches that exceed the desired value (branch and bound). IE: if factors are (2,5,7,13,19). The number is 80, and you have 2*5*7 = 70. 2 * 5 * 7 * 13 = 910. There is no need to check 2 * 5 * 7 * 19 as it would clearly exceed the max.
[1] It's a good idea to treat the factorization as an multiset. For example in the case of 700, ((2,2),(5,2),(7,1)). You could treat it as (2,2,5,5,7), but it would do extra work since there's no need to find 2 * 5 = 10 more than once, but if it's not treated as a multiset, then that would happen.


text:
Q: Chrome not responding to flexbox css in my footer? I can't figure out why Chrome is not responding to my footer flexbox css the website is www.batistaelectric.com it works on my Iphone chrome browser, safari Iphone browser, Imac safari browser it even works in my chrome preview from Brackets but not on Chrome after I upload it to the server.
On Chrome browser on Imac, the footer stays inline instead of stacking in a column.

  @media only screen and (min-width: 801px) {
  .pv-header {
    width: 100%
  }
  .pv-footer {
    display: -webkit-box;
    display: -moz-box;
    display: - ms-flexbox;
    display: -webkit-flex;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
  }

          About Us

          Disclaimer

          Privacy Policy

Batista Residential Electric, INC.

This is a snapshot of how it looks on my chrome browser as you can see it's not wrapping when collapsed. So it's not seeing the flexbox css for the footer.
footer on chrome not stacking footer not wrapping

A: Are you talking about the "buttons" (li elements) in the .pv-footer div?
If so, you need to make their direct parent flex. In this case:
#nav-a ul {
    display: flex;
    flex-wrap: wrap;
}

Even then, if they are small enough to fit within the viewport width, then they still wont wrap. You would need to increase their width with something like this:
#nav-a ul li {
    min-width: 100%;
}

Making the .pv-footer flex allows it's direct descendants to flex, but not nested elements like the list items (li).


text:
Q: Integrating Adsense with PHP Alright, so I don't know what's going on.
I've been trying to add Adsense to my site for the past three hours now, and it just doesn't work.
The site in discussion is www.salty.in (it's a replica of Google, but in a smart way, it's a direct Reddit replica, actually. It's used to browse Reddit, and it is simply said, a brilliant idea.
The Github is public, but I'll post my updated code. Keep in mind, I took over this project from a friend of mine.
This copy of the script is fully non-commented, so sorry about that.
http://hastebin.com/ujagutiqiy.php
Beginning at line 108, I've added the JavaScript for Adsense. This is the only place where it DOESN'T crash when I use it.

A: You have to put your adsense code inside  //adsenseCode  tag.

Below is the script file that supports Adsense

You can place this with either your site's scripts ( i.e. outside body ) or inside body

A: i recommend just to move

these lines from line 108 to line 193 before closing of body tag


text:
Q: Issue getting value of element I am facing a perplexing problem.
I have an HTML element that looks like this:
<tr id = "pracarea6196" value = "success" name = "pracarea" class = "success">

Whenever I try to get the value of the element, I get undefined:
document.getElementById("pracarea6196").value

Why would that be the case?

A: tr tags do not have a value. input tags do. Therefore, the DOM API treats this like any other attribute.
document.getElementById('pracarea6196').getAttribute('value')


text:
Q: Conscientious print to stdout from Python daemon I wrote a simple script using python-daemon which prints to sys.stdout:
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import daemon
import sys
import time

def main():
    with daemon.DaemonContext(stdout=sys.stdout):
        while True:
            print "matt daemon!!"
            time.sleep(3)

if __name__ == '__main__':
    main()

The script works as I would hope, except for one major flaw--it interrupts my input when I'm typing in my shell:
(daemon)modocache $ git clomatt daemon!!
matt daemon!!ne
matt daemon!! https://github.com/schacon/cowsay.git
(daemon)modocache $

Is there any way for the output to be displayed in a non-intrusive way? I'm hoping for something like:
(daemon)modocache $ git clo
matt daemon!! # <- displayed on new line
(daemon)modocache $ git clo # <- what I had typed so far is displayed on a new line

Please excuse me if this is a silly question, I'm not too familiar with how shells work in general.
Edit: Clarification
The reason I would like this script to run daemonized is that I want to provide updates to the shell user from within the shell, such as printing weather updates to the console in a non-intrusive way. If there is a better way to accomplish this, please let me know. But the purpose is to display information from within the terminal (not via, say, Growl notifications), without blocking.

A: A daemon process, by definition should run in the background. Therefore it should write to a log file.
So either you redirect it's output to a logfile (shell redirect or hand it over to some sys logging daemon) or you make it write to a logfile in the python code.
Update:
man write
man wall

http://linux.die.net/man/1/write, http://linux.die.net/man/1/wall

A: It probably is best practice to write to a log file for daemons. But could you not write to stderr and have the behavior desired above with inter-woven lines?

A: If it doesn't need to be an "instant" notification, and you can wait until the next time the user runs a command, you can bake all kinds of things into your bash shell prompt. Mine tells me the time and the git repository status for the directory I'm in, for example.
The shell variable for "normal user" shell prompts is PS1, so Googling for bash PS1 or bash prompt customisation will get you some interesting examples.
Here's some links:

*

*Some basic customisations

*A more complex example: git bash prompt
In general, you can include the output of any arbitrary script in the prompt string. Be aware, however, that high-latency commands will delay printing of the prompt string until they can be evaluated, so it may be a good idea to cache information. (For example, if you want to display the weather from a weather website, don't make your bash prompt go out and retrieve the webpage every time the prompt is displayed!)

A: Take a look at the logging library (part of the standard library). This can be made to route debug and runtime data either to the console or a file (or anywhere for that matter) depending on the state of the system.
It provides several log facilities, e.g. error, debug, info.  Each can be configured differently.
See documentation on logging - link
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')


text:
Q: Proper FIFO client-server connection I'm trying to write simple client and server C programs, communicating with each other in separate terminals.
The server has to create a public fifo and wait for the client. Meanwhile the client is creating his own fifo through which the server's response will come. The task of the client is sending the server a name created by the queue and get in return the result of the ls command.
I did search for an answer, for example: fifo-server-program, example-of-using-named-pipes-in-linux-bash, how-to-send-a-simple-string-between-two-programs-using-pipes. I started with the code from the third link and slowly modified it.
What I've got now, is a client taking input from the user, sending it to the server and receiving it back. But it only works once. I have no idea why. The body of main function is below. I will be grateful for any help.
EDIT:
I got it working! :D The codes are below, maybe it will help someone.
The server.c code:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int fds[2];
    char tab[BUFSIZ];
    int fd, n;

    char *myfifo = "/tmp/serwer";
    char *myfifo2 = "/tmp/client";

    pipe(fds);
    mkfifo(myfifo,0666);

    while(1)
    {
        fds[0]=open(myfifo2,O_RDONLY);
        fds[1]=open(myfifo,O_WRONLY);

        read(fds[0],tab,BUFSIZ);

        if (strcmp("klient",tab)==0) {
            printf("Od klienta: %s\n",tab);
            fd=open(tab,O_WRONLY);

            if(fork()==0)
            {
                dup2(fds[1],1);
                close(fds[1]);
                execlp("ls","ls","-l",NULL);
                close(fds[0]);
                close(fds[1]);
            }
            else
            {
                dup2(fds[0],0);
                n = read(fds[0],tab,BUFSIZ);
                write(fd,tab,n);
                close(fds[0]);
                close(fds[1]);
            }
        }
        memset(tab, 0, sizeof(tab));
        close(fd);
        close(fds[0]);
        close(fds[1]);
    }

    unlink(myfifo);
    return 0;
}

The client.c code:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int fds[2];
    char *myfifo = "/tmp/serwer";
    char *myfifo2 = "/tmp/client";

    mkfifo(myfifo2,0666);
    fds[0]=open(myfifo,O_RDONLY);
    fds[1]=open(myfifo2,O_WRONLY);

    char tab[BUFSIZ];
    memset(tab, 0, sizeof(tab));

    write(fds[1],"klient",6);
    perror("Write:"); //Very crude error check
    read(fds[0],tab,sizeof(tab));
    perror("Read:"); // Very crude error check

    printf("Odebrano od serwera: %s\n",tab);

    close(fds[0]);
    close(fds[1]);
    unlink(myfifo2);
    return 0;
}

A: Why don't you just manage both fifo's in the server? Simply changing your code to do this makes it work correctly.
If you actually want to have a client-server relationship, with a server serving many different clients, sockets would probably be a better choice.
client.cpp
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
   int client_to_server;
   char *myfifo = "/tmp/client_to_server_fifo";

   int server_to_client;
   char *myfifo2 = "/tmp/server_to_client_fifo";

   char str[BUFSIZ];
   printf("Input message to serwer: ");
   scanf("%s", str);

   /* write str to the FIFO */
   client_to_server = open(myfifo, O_WRONLY);
   server_to_client = open(myfifo2, O_RDONLY);
   write(client_to_server, str, sizeof(str));

   perror("Write:"); //Very crude error check

   read(server_to_client,str,sizeof(str));

   perror("Read:"); // Very crude error check

   printf("...received from the server: %s\n",str);
   close(client_to_server);
   close(server_to_client);

   /* remove the FIFO */

   return 0;
}

server.cpp
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

int main()
{
   int client_to_server;
   char *myfifo = "/tmp/client_to_server_fifo";

   int server_to_client;
   char *myfifo2 = "/tmp/server_to_client_fifo";

   char buf[BUFSIZ];

   /* create the FIFO (named pipe) */
   mkfifo(myfifo, 0666);
   mkfifo(myfifo2, 0666);

   /* open, read, and display the message from the FIFO */
   client_to_server = open(myfifo, O_RDONLY);
   server_to_client = open(myfifo2, O_WRONLY);

   printf("Server ON.\n");

   while (1)
   {
      read(client_to_server, buf, BUFSIZ);

      if (strcmp("exit",buf)==0)
      {
         printf("Server OFF.\n");
         break;
      }

      else if (strcmp("",buf)!=0)
      {
         printf("Received: %s\n", buf);
         printf("Sending back...\n");
         write(server_to_client,buf,BUFSIZ);
      }

      /* clean buf from any data */
      memset(buf, 0, sizeof(buf));
   }

   close(client_to_server);
   close(server_to_client);

   unlink(myfifo);
   unlink(myfifo2);
   return 0;
}

A: It only works once because of how named pipes work.  Each time you open a named pipe for read you block until another process opens it for write.  Then you are paired up and the file descriptor connects your processes.  Once either end closes that connection that's the end of that pipe.  In order for your server to "accept another connection" it needs to move the open and close of the pipes into its main loop so it can be paired up over and over.


text:
Q: Detect orientation jquery/javascript mobile I'm trying the following to detect orientation on a mobile device.
On a windows phone it does nothing, and on android it gets caught in what seems like a loop as just alerts all the time.
is there a better way to do this? Maybe with jquery (best option), if not better javascript solution?
function doOnOrientationChange () {
  switch (window.orientation) {
    case -90:
    case 90:
      alert('landscape');
      break;
    default:
      alert('portrait');
      break;
  }
}

window.addEventListener('orientationchange', doOnOrientationChange);

A: Orientation is subject to support and device type.
Here is a very simple crude method you could experiment with that would be widely supported:
function doOnOrientationChange () {
  let landscape = ( document.body.clientWidth > document.body.clientHeight );

  alert( landscape ? 'landscape' : 'portrait' )
}

window.addEventListener('resize', doOnOrientationChange);

You could add an offset value to change the orientation result to your liking, for example you might want to clamp landscape view on certain screen resolutions that are more square.


text:
Q: Вложенные интеракторы или нет Есть 2 интерактора AuthInteractor и UserInteractor
После авторизации нужно указать(задать) текущего пользователя через UserInteractor(потому что приложение мультиаккаунтное, и можно залогинится с разных акк, после логина автоматически должен становится активным пользователем).
Сейчас, AuthViewModel отправляет команду авторизации в AuthInteractor, после получения авторизации(там есть информация об ID пользователя) AuthViewModel отправляет команду установки текущего пользователя в UserInteractor.
Такое взаимодействие правильное? Или создать третий интерактор (SuperAuthInteractor) в котором есть AuthInteractor и UserInteractor и все делать внутри SuperAuthInteractor?

A: Архитектура - это штука, которая позволяет быстрее и удобнее разрабатывать. Прикиньте на глаз, какую выгоду Вам может принести переделка логики интеракторов, и сколько такая переделка займет времени и сил. Если считаете, что оно того стоит, то делайте, иначе - оставляйте как есть.
Конкретно в случае с авторизацией, я, например, никаких выгод не вижу. Но если в любом случае планируете крупные работы с авторизацией (ее полный рефакторинг, например), то лучше создать SuperAuthInteractor. Однообразие стиля кода - это тоже плюс.


text:
Q: php array key not found if key is a variable I think this isn't supposed to happen, but I can't find why this isn't working. I'm checking user input for duplicate choices. $into_fields_count is an array of database fields mapped to the number of times selected by the user (db field => count), $into_fields_dupes gathers the duplicates.
    foreach ( $into_fields_count as $field => $count )
    {
        if ( $count > 1 ) $into_fields_dupes[$field] = $count;
    }
    if ( $into_fields_dupes )
    {
        // construct error message
        $error = ERR_MAP_DUPLICATES;
        foreach ( $into_fields_dupes as $field => $count )
        {
            $error .= "\n" . 'Datenbankfeld "' .  $artikel_fields[$field] . '" wurde ' . $count . ' mal gewählt.';
        }
        $error .= "\nBitte korrigieren Sie den Fehler vor dem Import!";
        throw new Exception($error);
    }

The problem is using the same variable $field in both foreach arrays. In the second loop the attempt to get the value for $artikel_fields[$field] throws up the notice
Notice: Undefined index: bestell_nr in /my/file/path...

However, testing for $artikel_fields['bestell_nr'] after this code does find the key. Obviously the variable contains the right string in the questionable line.
I can fix this very easily by changing the variable name in the second loop, but I want to get my head around what's happening here. Can you tell me why the code doesn't work?

A: Based upon the excellent suggestions of Marc B and Magic Lasso, you can also use the PHP function trim to remove white space characters from a string.  Here is a link to the PHP manual entry on trim.
Also, you can use one of the offshoots of this methodology to trim the whitespace from just the beginning of the string:
ltrim
Or you can trim whitespace at the end of the string using:
rtrim

A: The question as stated is misleading. The problem with finding the key in the array was not that the same variable name was used in the two foreach loops; the reason is that the key searched for had inadvertently been prefixed with a space character, and the additional space was not seen while debugging.
An answer to the question could be: If such an obscure "error" occurs, check for hidden characters in the key you are searching for. Actually @Marc B answered the question in the first comment.
I will leave the title as is, so that someone else with this issue can find the solution.


text:
Q: Olá, eu sou novo em Python, e estou tendo problema com um SyntaxError em um else
Ele aparenta estar escrito de maneira correta, mas mesmo assim esta dando erro. Não importa o que eu faça o erro continua, eu já tentei trocar por um elif, por um if, mas nada da certo. Sempre dá um SyntaxError.

A: @GabrielBellasco, o erro que consta no "else" na realidade é antes dele !
Faltou você fechar o parentêses do print. Você abriu, mas não fecho !
OBS:Ai vai uma dica.. sempre que acusar um SyntaxError, procure o erro. Quando encontrar o mesmo sublinhado como no exemplo do seu programa que é o "Else", sempre procure na linha superior pois o erro será da linha acima.
Quando estava aprendendo C, sempre tinha esses erros e tinha o mesmo problema que você !
Fica a dica para ajudar você a programar.


text:
Q: CodenameOne "Undefined symbols" error when adding native library I am trying to add the Honeywell Captuvo iOS library to my CodenameOne project as a native library. I have been through the "Generate Native Access" process and placed the .a library in the native/ios directory. However when I send the app to be built it comes back with the error:
Undefined symbols for architecture arm64:
"_OBJC_CLASS_$_EAAccessoryManager", referenced from:
      objc-class-ref in libCaptuvoSDK.a(CaptuvoReal.o)
Many thanks

A: Rereading the error message it seems I missed a key detail. You need to add the ExternalAccessory.framework to your project. To do this you need to define the build hint: ios.add_libs=ExternalAccessory.framework
Original answer below:
Is the name of the .a library preceded with the lower case word lib and does it actually end with a .a. If not make sure to rename it so it abides by these constraints.
Assuming both are OK you will need to verify the library actually has the required architecture in this case arm64.
This is explained in this question: How to check if a static library is built for 64-bit?
I would just use the second suggestion: file libFileName.a
It should include arm64 among the list of supported architectures.


text:
Q: Continuous transformation with a propertie I have this problem but I don't know how to solve it. Suppose $f: \mathbb{R}^{n} \to \mathbb{R}^{m}$ a continuous transformation that :
$$ ||f(x)-f(y) ||\geq \lambda||x-y ||$$
for all $x,y \in \mathbb{R}^{n}$ and some $\lambda > 0$.
Prove that f is bijective and have a continuous inverse.  I have done the injectivity and i'm not sure about how to show the rest.
Thanks
EDIT : Sorry, i had a $\leq$, is a $\geq$


text:
Q: Rails 5 API with front-end engine I've a Rails 5 API with devise/doorkeeper perfectly working.
I've built an engine having a front-end part with all devise views. Everything works unless the flash when warden is throwing an error. I've imported manually missing modules :
# app/controllers/concerns/api_to_web_controller.rb
module ApiToWebController
  extend ActiveSupport::Concern

  included do
    include ActionController::Helpers
    include ActionController::MimeResponds
    include ActionController::Redirecting
    include ActionView::Layouts
    include ActionController::EtagWithFlash
    include ActionController::Flash

    respond_to :html
  end
end

# app/controllers/concerns/devise_api_to_web.rb
##
# Module to integrate Devise:
#  - helpers
#  - layout
# It also redefine `redirect_to`.
# See https://github.com/heartcombo/responders/issues/222
# for more details
module DeviseApiToWeb
  extend ActiveSupport::Concern

  included do
    layout 'secret_migration/devise'

    if respond_to?(:helper_method)
      helpers = %w[resource scope_name resource_name signed_in_resource
                   resource_class resource_params devise_mapping]
      helper_method(*helpers)
    end

    def redirect_to(options = {}, response_options = {})
      super
    end
  end
end

Here is my custom SessionController
module MyEngine
  module V1
    # Override Devise::SessionsController
    class Users::SessionsController < Devise::SessionsController
      include ::ApiToWebController
      include ::DeviseApiToWeb
    end
  end
end

I got this custom after_authentication
# config/initializers/warden.rb
Warden::Manager.after_authentication do |user, auth, _opts|
  next if user.is_ok?

  throw(:warden, :message => "User not ok, contact admin")
end

Finally, the application file
module MyApp
  class Application <
opts = { key: '_my_app', domain: 'example.com', tld_length: 1 }
Rails::ApplicationRails.application.config.session_store :disabled
  config.session_store :cookie_store, opts
  config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
  config.middleware.insert_after(ActionDispatch::Cookies, ActionDispatch::Session::CookieStore,
                                 opts)

I've been able to track the data. env[warden.options] is well filled with :message => "User not ok, contact admin" but somehow, it's not passed after the redirection.
Important point, I got flash message when it's a pure devise error like Invalid Email or password..

A: I got it. It was a middleware order issue. It has to be with the following order
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use Warden::Manager

I've update my engine.rb to include the middleware at the correct place
module MyEngine
  ##
  # Engine initializers
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine
    initializer 'use action dispatch flash' do |app|
      app.config.middleware.insert_after(ActionDispatch::Session::CookieStore, ActionDispatch::Flash)

      app.config.middleware.use Rack::MethodOverride
    end
  end
end

# config/application.rb
module MyApp
  class Application < Rails::Application
    # ...
    config.middleware.insert_before(Warden::Manager, ActionDispatch::Cookies)
    # ...
  end
end

# config/environments/development.rb
Rails.application.configure do
  opts = { key: '_my_app', domain: 'lvh.me', tld_length: 2 }
  Rails.application.config.session_store :disabled
  config.session_store :cookie_store, opts
  config.middleware.insert_after(ActionDispatch::Cookies, ActionDispatch::Session::CookieStore,
                                 opts)
end


text:
Q: How to install the 'Quicktime'-Plugin (needed for youtube-songs in Tomahawk)? When I want to play a song via youtube in Tomahawk it does not play the song. A pop-up appears and asks me to find the missing plugin which is 'Quicktime'. But there is no chance to install this plugin. As far as I know I installed every codec.
OS: Ubuntu 11.10 64bit / Tomahawk 0.3.3
When I remember correctly it worked with 11.04, but I am not really sure. But it once worked. Now I cannot play youtube-songs at all.

A: It may be a bit late, but I had rather the same problem with Tomahawk version 0.5.0 under Ubuntu 12.04.
The solution is to install the phonon-backend-vlc package instead of phonon-backend-gstreamer
as they told us on the website
http://www.tomahawk-player.org/download.html

A: *

*Open Firefox.

*Load the page normally.

*Click in the Firefox menu on Tools.

*Go to Page Info.

*Click on the Tab Media.

*Scroll till you find the URI with the quicktime video (usually .mov).

*Copy and paste the URI/URL hit Enter. It will play in the browser. If you want to download it than after this you can go to the Firefox menu click on File, then on Save Page As...
As it already will give the quicktime video extension, all you need to do is put in the folder you want to download it to.
(Works under Ubuntu 12.04, after embedded quicktime vids, that worked b4, does no longer.)


text:
Q: How read original file at Akamai HD? I need to convert Flash player for videos located at Akamai HD servers to HTML 5 version. But I didn't work with Akamai in past so i total newbie in Akamai with limited time to develop.
Videos are already in MP4 format (MP4 container, H264 video). But its accesses as FLV container (it automatically transcoded at Akamai). Urls looks like http://something.akamaihd.net/file_part_4,3.,2.,mp4.csmil/.....&primaryToken=token .
What are first steps for me to access original files (i think there are some REST API)?
What additional access requirements I needed except tokens (in difference with access to FLV container)?
Thanks, for your patience with my newbie questions.

A: In order to access the original files you need to create another configuration (for instance a Progessive Media Download configuration) which will use the same origin as the AkamaiHD configuration.
If you have token requirements, you will have to implement the token logic in the new configuration too. Please note: tokens are not a requirement for an HD configuration or any other type of configuration -- they are a feature you can turn on if needed.


text:
Q: Which theorems have Pythagoras' Theorem as a special case? Loomis famously wrote hundreds of proofs of Pythagoras' Theorem (reference below), but these are all basically proofs "from below".  Today on Twitter @panlepan mentioned Carnot's theorem which has Pythagoras' Theorem as a special case and this got me thinking.   Which theorems have Pythagoras' Theorem as a special case?
@BOOK{Loomis1968,
  author =       {Loomis, E.},
  title =        {The {Pythagorean} Proposition},
  publisher =    {National Council of Teachers of Mathematics},
  year =         {1968},
  address =      {Washington},
}

A: The discrete form of the parallel axes theorem for the second moment of area for $\,n\,$ points $\,A_k\,$ with centroid $\,G\,$ and an arbitrary point $\,P\,$ is $\,\sum_{k=1}^n PA_k^2 = n \cdot PG^2 + \sum_{k=1}^n GA_k^2 \;\;(*)\,$.
Let $\,\triangle ABC\,$ be a right triangle and $\,O\,$ the midpoint of hypotenuse $\,BC\,$, known to also be its circumcenter, so $\,OA = OB = OC = \frac{1}{2} BC\,$. Then$\,(*)\,$ for $\,A_1A_2A_3 \equiv BOC\,$, $\,G\equiv O\,$ and $\,P \equiv A\,$ reduces to Pythagoras' theorem:
$$
\require{cancel}
\begin{align}
AB^2+AO^2+AC^2 = 3 \, AO^2 + OB^2+\bcancel{0}+OC^2 \iff AB^2+AC^2 &=4 AO^2 = BC^2
\end{align}
$$

A: I like to think about Pythagoras theorem as a corollary/special case of the following theorem:
Theorem: Let $X$ be a finite dimensional real Banach space such that the group of linear isometries (that is, isometries which fix $0$) of $X$ acts transitively on the unit sphere of $X$. Then $X$ is a Hilbert space.
That is, having enough rotations forces the norm to come from an inner product, and from this Pythagoras theorem follows

A: The Binet-Cauchy formula says that if $A$ and $B$ are a $n\times m$ and $B$ a $m\times n$ real matrices, respectively, and for $s\subseteq\{1,\ldots ,m\}$ with $|s|=n$ we denote by $A_s$ the $n\times n$ submatrix of $A$ obtained deleting the columns not in $s$, and by $B^s$ the $n\times n$ submatrix of $B$ obtained deleting the rows not in $s$, then
$$\det(AB)=\sum_{\begin{array}{c} s\subseteq\{1,\ldots ,m\}\\ |s=n|\end{array}} \det(A_s)\det(B^s)$$
In the case $B = A^T$, the transpose of $A$, since $B_s = (A^T)_s=(A_s)^T$ the formula gives
$$\det(AA^T) = \sum_{\begin{array}{c} s\subseteq\{1,\ldots ,m\}\\ |s=n|\end{array}} \det(A_s)\det((A_s)^T)=\sum_{\begin{array}{c} s\subseteq\{1,\ldots ,m\}\\ |s=n|\end{array}} (\det(A_s))^2$$
Since the parallelotope in $\mathbb{R}^n$ generated by the $n$ row vectors of $A$ has measure $\sqrt{\det(AA^T)}$, then the formula says that the square of the $n$-dimensional measure of an $n$-dimensional parallelotope equals the sum of the squares of the
measures of its projections onto all possible $n$-dimensional coordinate hyperplanes. If $n = 1$ this reduces to the Pythagorean theorem.

A: In a less "higher" maths fashion :
This Numberphile video somewhat says that Pythagoras theorem is a special case of Ptolemy's theorem which is a more general view of properties of a cyclic quadrilateral. But navigating between the 2 always seems some sort of tautology to me …
There is also Casey's theorem which reduces to Ptolemy's (so which could reduce to Pythagoras').
Quoting the Ptolemy's theorem Wikipedia article :

More generally, if the quadrilateral is a rectangle with sides a and b and diagonal d then Ptolemy's theorem reduces to the Pythagorean theorem. In this case the center of the circle coincides with the point of intersection of the diagonals. The product of the diagonals is then d2, the right hand side of Ptolemy's relation is the sum a2 + b2.

Later on, it is cited as a corollary theorem.

A: There's an "n-dimensional Pythagorean theorem" https://billcookmath.com/papers/2012-06_nD_pythag.pdf, saying that the square of the $k$-dimensional area of a $k$-dimensional parallelogram $P$ in $n$-space is equal to the sum of the squares of the $k$-dimensional areas of the projections of $P$ onto all $k$-dimensional planes spanned by the coordinate axes.
This theorem is in particular relevant when introducing differential forms; I learned about it from this MSE question.

A: The Law of cosines is the first that comes to my mind:
$$c^{2}=a^{2}+b^{2}-2ab\cos \gamma$$

(source: Wikipedia)
If $\gamma$ is a right angle, its cosine is 0 and all that remains is Pythagoras' Theorem.

A: Parseval identities in the theory of Fourier series and integrals.

A: The parallelogram law says that if $\mathcal{V}$ is an inner product space and $\mathbf{v},\mathbf{w} \in \mathcal{V}$, then
$$
2\|\mathbf{v}\|^2 + 2\|\mathbf{w}\|^2 = \|\mathbf{v} + \mathbf{w}\|^2 + \|\mathbf{v} - \mathbf{w}\|^2,
$$
where the norm here is the one induced by the inner product (in fact, a result of John von Neumann says that a norm is induced by an inner product if and only if the above parallelogram law holds). Its name comes from the fact that, if $\mathcal{V} = \mathbb{R}^2$ then the equality above simply tells us something about the sides lengths of a parallelogram compared to the lengths of its diagonals.
In the special case when $\langle \mathbf{v},\mathbf{w}\rangle = 0$, we have $\|\mathbf{v} + \mathbf{w}\|^2 = \|\mathbf{v} - \mathbf{w}\|^2$, so the parallelogram law simplifies to
$$
\|\mathbf{v}\|^2 + \|\mathbf{w}\|^2 = \|\mathbf{v} + \mathbf{w}\|^2,
$$
which is the Pythagorean theorem (if $\mathcal{V} = \mathbb{R}^2$).

A: The Pythagorean theorem is a limit of the general formula for spherical or hyperbolic space: $\cos(a\sqrt{\kappa})\cos(b\sqrt{\kappa})=\cos(c\sqrt{\kappa})$, where $\kappa$ is the curvature.

A: So far no one has mentioned the original generalization!
Early in Euclid's Elements, the Pythagorean theorem is stated by comparing square areas:

Book I, Proposition 47: In right-angled triangles the square on the side opposite the right angle equals the sum of the squares on the
sides containing the right angle.

Later on, the Elements generalizes this far beyond squares. First it defines similar figures, meaning any similar figures with straight line segments:

Book VI, Definition 1: Similar rectilinear figures are such as have their angles severally
equal and the sides about the equal angles proportional.

So the generalization that appears in the Elements is the Pythageorean theorem for any similar figures, as known some 2500 years ago:

Book VI, Proposition 31: In right-angled triangles the figure on the side opposite the right angle equals the sum of the similar and
similarly described figures on the sides containing the right angle.

A: This is probably the simplest: $(a+b)^2=a^2+b^2+2ab$, if you take $a,b$ elements of some inner product vector space and $(\cdot)^2$ means inner product with itself.

A: One of the most attractive generalisations is de Gua's theorem:  If a tetrahedron $ABCD$ is rectangular at $A$, then $$  |BCD|^2=|ABC|^2+|ACD|^2+|ABD|^2$$ where the absolute value signs denote area.
This can easily be proved analytically by the $p,q$ method.  One assumes,as one can, that the vertices are $(0,0,0)$, $(1,0,0)$, $(0,q,0)$ and  $(0,0,t)$--the calculations are then done in a matter of minutes.
Given the objection below, here is the hierarchy of results: The square of the measure of a measurable set in $m$-dimensional affine subspace of euclidean $n$-space is the sum of the squares of the measures of the $n \choose m$ orthogonal projections on all the $m$-dimensional coordinate subspaces of $n$-space with respect to a fixed ONB basis of the latter (Conant and Beyer).

A: Pythagoras' theorem is a special case of the three point identity for Bregman distances: Let $h$ be convex and lower semi-continuous on a Banach space - further assume differentiability of $h$ for simplicity. Then $h$ induces a Bregman distance
$$D_h(u,v) = h(u)-h(v) - \langle \nabla h(v), u-v\rangle $$
and this Bregman distance fulfills the mentioned three point equality
$$\langle \nabla h(u) - \nabla h(v),v-w\rangle = D_h(w,u) + D_h(w,v) + D_h(v,u).$$
The special case appears for $h(u) = \tfrac12\|u\|^2$ on a Hilbert space $X$ (or on $X = \mathbb{R}^2$). Here we get $\nabla h(u) = u$ and $D_h(u,v) = \tfrac12\|x-y\|^2$ and you get Pythagoras.

A: $$1=\cos^2 x+\sin^2x$$ (which can be proven without using Pythagoras) holds for arbitrary $x$ in $\mathbb C$ and yields Pythagoras for real $x$.

A: There is a generalisation of Pythagoras to the case of a non-right angled triangle. Inscribe an isosceles triangle $\triangle ADE$ in $\triangle ABC$ so that $[DE]\subseteq[BC]$ and $|\angle BAC|=|\angle ADC|=|\angle AEB|$. Set $r=|BE|$ and $s=|DC|$. (See a picture here.) Then by observing that $\triangle ABC$, $\triangle DAC$ and $\triangle EBA$ are similar, we get $\frac{a}{b}=\frac{b}{s}$ and $\frac{a}{c}=\frac{c}{r}$, which yields $$b^2+c^2=a(r+s).$$
If $\angle BAC$ is acute, then $[BE]$ and $[DC]$ overlap, so that $r+s>a$, while if $\angle BAC$ is obtuse we have $r+s<a$. And of course if $\angle BAC$ is a right angle, we get $r+s=a$ and recover Pythagoras' Theorem.
Wikipedia attributes this to Thābit ibn Qurra.

A: The law of total variance says that if $X,Y$ are real-valued random variables and $\operatorname E(X^2)<+\infty,$ then
$$
\operatorname{var}(X) = \overbrace{\operatorname{var}(\operatorname E(X\mid Y))}^{\begin{smallmatrix} \text{explained} \\ \text{component} \\ \text{of the variance} \end{smallmatrix}} {} + {} \overbrace{ \operatorname E(\operatorname{var}(X\mid Y)) }^{\begin{smallmatrix} \text{unexplained} \\ \text{component} \\ \text{of the variance} \end{smallmatrix}}
$$
A more concrete version is that in the analysis of variance, the sum of squares of residuals ("residuals" are not to be confused with "errors") plus the sum of squares due to regression equals the total corrected sum of squares (that last being the sum of squares of deviations from the sample mean).
Most statistics texts tell you that the proportion of the total variance that is "explained" is the square of the correlation between $X$ and $Y.$ (For that you need to assume $Y$ also has a finite second moment. But the validity of the identity above does not depend on $Y$ being real-valued at all, and in cases where $Y$ takes values in a set with no structure or in $\mathbb R^n$ or something else, it is still standard to call the explained proportion of the total variance $\text{"}R^2\text{"},$ even though in such cases there is no quantity called $R.$) Some textbooks go on to say that that is also the square of the cosine of an angle (one of the angles of the right triangle that is involved), and then deduce certain bounds on the correlation between $X$ and $Z$ given those between $X$ and $Y$ and between $Y$ and $Z.$
A further generalization is Brillinger's law of total cumulance, of which the following is the case $n=4{:}$
\begin{align}
\text{joint cumulant} = {} & \kappa(X_1,X_2,X_3,X_4) \\[8pt]
= {} & \kappa(\kappa(X_1,X_2,X_3,X_4\mid Y)) \\[6pt]
& {} + {} \underbrace{ \kappa(\kappa(X_1,X_2,X_3\mid Y), \kappa(X_4\mid Y)) + \cdots}_\text{4 terms} \\[2pt]
& {} + {} \underbrace{ \kappa(\kappa(X_1,X_2\mid Y),\kappa(X_3,X_4\mid Y)) + \cdots }_\text{3 terms} \\[6pt]
& {} + {} \underbrace{\kappa(\kappa(X_1,X_2\mid Y),\kappa(X_3\mid Y), \kappa(X_4\mid Y)) + \cdots}_\text{6 terms} \\[6pt]
& {} + \kappa(\kappa(X_1\mid Y),\kappa(X_2\mid Y), \kappa(X_3\mid Y), \kappa(X_4\mid Y))
\end{align}
where the sum is over the set of all partitions of the set $\{X_1,\ldots,X_n\}$ of random variables.


text:
Q: Keep image fixed when browser window shrinks. Please help! I can't figure out how to make the bg_header.png stay in place when the browser window shrinks in width less than the page width.  try it:
link text
Here is my CSS:
#body_wrap {
 width: 100%;
 z-index: 1;
 overflow: hidden;
}
#body_wrap_top {
 width: 100%;
 height: 247px;
 background: url('/img/bg_header.png') repeat-x;
 margin: 0 auto;
 overflow: hidden;
}
#body_wrap_top_logo {
 width: 844px;
 height: 247px;
 background: url('/img/bg_logo.png') no-repeat;
 position: absolute;
 right: 49%;
 overflow: hidden;
}

A: I would suggest you the following:
1) I see that you have slice the logo with the background. Slice only the logo in png format.
2) Delete the #body_wrap_top_logo div
3) create a new div before nav div, give it float and width-height of the image.
here an example of the above with inline styling.

                    10 reasons our clients
                    technology intelligence
                    ISO 9001:2000 CMMI
                    Six Sigma FAQ's

                        The UBS team is working hard to earn your trust and respect to serve as your source for the best custom folding
                        cartons in the world.

© 2010 UBS Packaging.

                    about us markets
                    innovation services
                    case studies company news
                    contact plant tour

                    client login employee login
                    FTP access UBS forms

                    careers

                    site map

                    UBS Packaging
2577 Research Drive
Corona, CA 92882-7607 USA

                    Tel: 951.273.7900
Fax: 951.273.7912

                driving directions chat live email:
                info@ubspack.com blog: http://ubspack/blogger

                <form>

                        Your Name

                        Email Address

                        Telephone

                        Message

                            UBS Newsletter

                    <input class="submit">
                </form>

                home  |  chat live  |  live person 951.273.7900

24/7 customer service

structural design

pre-press

clinical trials

start-up's

security solutions

braille

source tagging

fulfillment

contingency planning

inventory control

logistics

sheeting

ink making

printing

die making

die-cutting

foil hot stamping

gluing + finishing

windowing

quality assurance

assembly

biotech

cosmetics

electronics

entertainment

foods

gift boxes

health care

medical device

nutraceutical

personal care

pharmaceutical

specialty

our story

UBS vision

UBS mission

president's letter

zero tolerance

technology

customers

meet the team

0123456

                    We understand the importance of always having the essential tools, services and information readily available
                    for you 24/7. The team at UBS packaging is anxious and ready to provide your company with everything it takes
                    to study, analyze, prepare, engineer, design and manufacture your custom packaging all under one roof.

                    Combine all the years of experience throughout the UBS team and you will discover over 157 years of on-hands,
                    technical experience in custom folding cartons that can help you achieve the perfect packaging for your products.
                    The UBS team is ready to serve and provide you with the technical expertise you need to get your packaging right.

                    Our passion to be the best folding carton manufacturer in the world stems from the discipline and mentality of
                    "always doing right the first time" and identifying any non-conformance before it leaves our shipping dock. Quality
                    control at UBS is not one department or a designated QA staff. It's enforced by every member of the UBS team.

                                100% Quality control start to finish

                                100% Quality control start to finish

                                24/7 Customer Service & Support

                                24/7 Customer Service & Support

                                Engineering & Processing

                                Engineering & Processing

                                Structural & Concept Designing

                                Structural & Concept Designing

                                Artwork & Digital Pre-Press

                                Artwork & Digital Pre-Press

                                Plate Making & Die Registration

                                Plate Making & Die Registration

                                Die Making & Tooling Assembly

                                Die Making & Tooling Assembly

                                Ink Making & Color Matching

                                Ink Making & Color Matching

                                Printing with Flexo, UV & Waterbase

                                Printing with Flexo, UV & Waterbase

                                Die Cutting & Blanking

                                Die Cutting & Blanking

                                Foil Stamping with Emboss & Deboss

                                Foil Stamping with Emboss & Deboss

                                Folding Gluing & Conversion

                                Folding Gluing & Conversion

                                Warehousing & Shipping

                                Warehousing & Shipping

A: You might consider floating #body_wrap_top_logo to the left of its container and setting its margins to tweak its position instead of using absolute positioning.


text:
Q: Not able to inject Map into the object while testing with Mockito I am trying to test a method of hashMap using Mockito but its not working as expected.
My Class
import java.util.HashMap;
import java.util.Map;
public class Fun {

    private static Map<String,Long> map1= new HashMap<>();
    public long foo(final String test){
        if(!map1.containsKey(test)){
            return 0L;
        }
        return map1.get(test);
    }
}

My test class
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;

public class FunTest {

    private static Map<String,Long> map1 = new HashMap<>();
    private Fun classUndertest = new Fun();
    @Test
    public void testfoo(){
        map1.put("test",2L);
        long value = classUndertest.foo("test");
        Assert.assertEquals(2L, value);
    }
}

Its giving 0L instead of 2L.

A: Only reflection can help with private static field:
@ExtendWith(MockitoExtension.class)
public class FunTest {

  private Fun classUndertest = new Fun();

  @Test
  public void testfoo() throws NoSuchFieldException {
    Map<String, Long> test = Map.of("test", 2L);
    FieldSetter.setField(classUndertest, Fun.class.getDeclaredField("map1"), test);

    long value = classUndertest.foo("test");

    Assertions.assertEquals(2L, value);
  }
}