text:
Q: MVVM Understanding Issues A list of my questions towards mvvm, you don't need to answer on your own, links which help me further are always appreciated:

*

*If I have a Mainpage.xaml file and I'm using a viewmodelclass which code should be in the Mainpage.xaml.cs file? Nothing?

*Should that piece of code be in the Mainpage.xaml.cs file:
Viewmodel base = new Viewmodel();

*If I implement ICommands how can I access for example a textbox.text on the Mainpage.xaml?

*ICommands completely replace the Button.Click event? Don't they?

A: *

*
If I have a Mainpage.xaml file and I'm using a viewmodelclass which
  code should be in the Mainpage.xaml.cs file? Nothing?

You need to understand what's is view's and what viewmodel's responsibility. Codebehind is part of view, so only code that is covered by view's responsiblity should be in code behind.
Sometimes databinding to viewmodel is hard in xaml (e.g. PasswordBox) Then you can use codebehind to get the password or catch changes and set property in viewmodel. You should not validate the password agains't server in codebehind.
Sometimes it's difficult to define animations in xaml. Feel free to create or trigger them in C# (but in that case you wont be able to edit then in Expression Blend)
It's ok to use evens like Loaded / Unloaded in codebehind, e.g. I use them to call Activate/Deactivate methods in my viewmodels.
This is codebehind sample, that does not violate the view and viewmodel separation of concerns:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Closing += MainWindow_Closing;
    }

    MainWindowViewModel ViewModel
    {
        get { return (MainWindowViewModel)DataContext; }
    }

    void MainWindow_Closing(object sender, CancelEventArgs e)
    {
        var canExit = ViewModel.ShowConfirmExitDlg();
        if (!canExit) e.Cancel = true;
    }
}

In other words, sometimes you have to use codebehind. There are people that are saying that you should never use it, but be pragmatic and use it, when it helps you.

*
Should that piece of code be in the Mainpage.xaml.cs file: Viewmodel base = new Viewmodel();

yep, that's ok. However you should use d:DataContext in xaml in order to let Visual Studio Designer know what datacontext you are using so it could provide you with intellisense and design time support. There is a lot of ways how to set instantiace viewmodel and set it to datacontext. It's up to you whatever you choose.

*
If I implement ICommands how can I access for example a textbox.text on the Mainpage.xaml?

Create string property in viewmodel and databind the textbox.text to it. Use DelegateCommand, where you can pass method that has access to the property:
public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        LoginCommand = new DelegateCommand(Login);
    }

    public DelegateCommand LoginCommand { get; private set; }

    public string Username { get; set; }
    public string Password { get; set; }

    private void Login()
    {
        if (Username == "user" && Password == "user")
        {

        }
    }
}

just FYI, there is also another way of passing parameter to command: check CommandParameter feature [link]

*
ICommands completely replace the Button.Click event? Don't they?

Almost. The same rules as in answer to first question applies also here.

A: *

*I try to keep the code behind to a minimum. I still tend to put the form closing logic in there.

*Many people use dependency injection to do this externally from the WPF Form.

*You can use data binding to a property on your viewmodel for textbox.text (that uses INotifyPropertyChanged) and modify it in the ViewModel. The form will automatically update to reflect any changed.

*Yes, it abstracts the code from the form to the viewmodel.
There are some great videos on YouTube which explains these concepts in detail.
Hope this helps.

A: I think your questions indicate that you have not really started to dig too deep into WPF with MVVM yet.
Most "Getting Started" tutorials will address your questions.
My favorite tutorial is WPF Apps With The Model-View-ViewModel Design Pattern by Josh Smith.
That one will give you an valid answer to all questions. Do not forget to also download the code example of the article to get the fully working demo application! :-)

A: *

*Ideally, yes. But in most of cases it's hard to follow

*Not in every case. If your ViewModel's constructor does not accept arguments, you can write it in xaml:
<Window.Resources>
    <local:ViewModel x:Key="viewModel" /> <!-- this row will automatically create instance of ViewModel class-->
</Window.Resources>

If view model class accepts arguments, then yes, you will have to write:
ViewModel base = new Viewmodel(yourArgs);
this.DataContext = base;

in code-behind.

*If you want to follow MVVM, bind TextBox's Text property to Viewmodel property:
<TextBox Text="{Binding MyText}" />

and in ViewModel:
private string _myText;
public string MyText
{
    get { return _myText; }
    set
    {
        if (_myText != value)
        {
            _myText = value;
            // NotifyPropertyChanged("MyText"); if needed
        }
    }
}

Then you could use RelayCommand or DelegateCommand (google it) to operate with text of your TextBox inside ViewModel.

*Yes. Command allows also to pass parameter to ICommand (for example, when you will use RelayCommand)

Hope, it helps.

A: This question might get deleted for not being specific enough but here goes anyway....

If I have a Mainpage.xaml file and I'm using a viewmodelclass which
  code should be in the Mainpage.xaml.cs file? Nothing?

Not just MainPage, any other window or control class as well (with some exceptions that I won't go into here). You should be able to create, run and unit test your entire application without creating a single view. The viewmodels are your application, the views are simply the loosely-bound graphical UI representation presented to your users when you're running your application in a way that requires user interaction (i.e. not unit testing).

Viewmodel base = new Viewmodel();

This is a somewhat complex topic but the high-level answer is "use a dependency injection framework". Adding MVVM Lite to your project via NuGet will automatically set this up for you with a very simple framework, otherwise Google is your friend.

If I implement ICommands how can I access for example a textbox.text
  on the Mainpage.xaml?

You add a string property to your view model with a getter and setter and you bind the textbox's Text property to that.

ICommands completely replace the Button.Click event? Don't they?

In general, yes. The "correct" way to use WPF is to bind commands to your command handlers. Things like event handlers were added for the same reason that property getters and setters were added i.e. to help ease the transition from the old WinForms way of doing things. Just because the framework supports it doesn't mean it's the right way to go about things.


text:
Q: mongodb match all conditions with a single array element I have an array of tests like this,
{

    "tests" : [

        {
            "testId" : "1",
            "details" : {
                "status" : "Completed"
            }
        },
        {
            "testId" : "2",
            "details" : {
                "status" : "InProgress"
            }
        },
        {
            "testId" : "3",
            "details" : {
                "status" : "Completed"
            }
        },
    ]
}

I want to search for complete tests with id as 1 or 2.
So I wrote a match query like this
{
  $match : { $and : [ { "tests.testId" : { $in : [1, 2] } }
                    ,{ "tests.details.status" : "Completed" }
                   ]
          }
}

The problem with this query is it fetches all documents with Ids as 1 or 2 even though the status is not Completed. For example the above query fetches these two documents
        {
            "testId" : "1",
            "details" : {
                "status" : "Completed"
            }
        },
        {
            "testId" : "2",
            "details" : {
                "status" : "InProgress"
            }
        },

What I need is to the query to search for a parituclat array element for both the condition.
I also tried with $elemMatch. It still doesn't work. Any help is much appreciated.

A: We can use aggregate pipeline with $filter to return the matched array elements only
try this
db.collection.aggregate([
  {
    $match: { // to filter the documents
      $and: [
        {
          "tests.testId": { $in: ["1", "2"] }
        },
        {
          "tests.details.status": "Completed"
        }
      ]
    }
  },
  {
    $project: { // then use this $project stage to use the $filter operator in it
      tests: {
        $filter: { // this is to filter the tests array
          input: "$tests",
          as: "test",
          cond: {
            $and: [
              {
                $in: [
                  "$$test.testId", ["1", "2"]
                ]
              },
              {
                $eq: [
                  "$$test.details.status",
                  "Completed"
                ]
              }
            ]
          }
        }
      }
    }
  }
])

you can test it here Mongo Playground
hope it helps

Note, If testId is of type ObjectId, then you have to use ObjectIds not strings in the aggregate pipeline

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swapping two ranges I am trying to write code for swapping two ranges:
Sub SwapRanges()
  Dim range1 As Range
  Dim range2 As Range
  Dim holder As Range

  range1 = Range("D7:D12")
  range2 = Range("E7:E12")
  holder = Range("F7:F12")

  Set holder = range1
  Set range1 = range2
  Set range2 = holder
End Sub

but get run-time error 91.

A: The cause of the error is that you are not using the Set command when assigning ranges. In addition, understand that this code:
Set holder = range1
Set range1 = range2
Set range2 = holder

only changes the ranges referred to by the variables holder, range1, and range2. It doesn't actually copy the data contained in those references from one range to another.
The code below will perform the actual copying while also addressing the run-time error.
Sub SwapRanges()
  Dim range1 As Range
  Dim range2 As Range
  Dim holder As Range

  Set range1 = Range("D7:D12")
  Set range2 = Range("E7:E12")
  Set holder = Range("F7:F12")

  range1.Copy holder
  range2.Copy range1
  holder.Copy range2
End Sub

A: I would try this way (sorry, non tested - writing from a Chrombook :)
Sub SwapRanges()
  Dim range1 As Range
  Dim range2 As Range
  Dim holder() as variant

  Set range1 = Range("D7:D12")
  Set range2 = Range("E7:E12")

  holder = range1
  range1 = range2
  range2 = holder
End Sub

A: Instead of coping you can just say:
       holder=range1
       Range2=range1
       Holder=range2
Not realy related to the question pnuts answered it but I thought this would be helpful for your application.


text:
Q: Recursive Alternative/Merge Linked List Function with Multiple Linked List as Arguments? I'm having trouble working with recursive linked list function with multiple linked list arguments.
So far I have came up with below, with a single linked list and works fine.
def recursive_ll(ll):
    if ll == None:
        return None
    elif ll.next == None:
        return LN(ll.value)
    else:
        return_ll = LN(ll.value, recursive_ll(ll.next))
        if return_ll.value == return_ll.next.value:
            return_ll = return_ll.next
    return return_ll

Result will be:
ll = list_to_ll(['x','g','f','n'])
print(str_ll(recursive_ll(ll)))

x->g->f->n->None

But I am really confused with how I can create recursive linked list function with multiple linked lists as arguments.
For example, def recursive_ll(ll): will be def recursive_ll(ll, ll2):
And returned result would be
ll = recursive_ll(['a','x','b','e'])
ll2 = recursive_ll(['d','f','m'])

a->d->x->f->b->m->e->None

Again, desired result below, combined from two linked list:
a->d->x->f->b->m->e->None

Any help/suggestions will be much appreciated!

A: You should use classes instead of simple functions as helpers. And accept any iterable as the source for a linked list. If you implement iterators on the linked list class, that would allow trivial conversion between any iterable and a linked list.
The linked list class could be:
class LL:
    class iter:
        def __init__(self, ll):
            self.cur = ll.front
        def __iter__(self):
            return self
        def __next__(self):
            if self.cur is None:
                raise StopIteration()
            val = self.cur.value
            self.cur = self.cur.next
            return val

    def __init__(self, l):
        self.front = last = None
        for v in l:
            ln = LN(v)
            if last is None:
                self.front = ln
            else:
                last.next = ln
            last = ln

    def __str__(self):
        answer = ''
        for val in self.iter_elt():
            answer += str(val) + '->'
        return answer + 'None'

    def __repr__(self):
        return str(self.__class__) + ':' + str(self)

    def __iter__(self):
        return LL.iter(self)

This immediately allows:
>>> print(LL('abcd'))
a->b->c->d->None
>>> list(LL('abcd'))
['a', 'b', 'c', 'd']

Once this is done, you can declare a Recursive Linked List as a subclass of a Linked List which allows to extract the elements in a merge order if it contains Linked Lists.
You should first add a new method iter_elt in LL class that just calls iter and use that in __str__ to ease the subclassing:
class LL:
    ...
    def __str__(self):
        answer = ''
        for val in self.iter_elt():
            answer += str(val) + '->'
        return answer + 'None'
    ...
    def iter_elt(self):
        return self.__iter__()

Because now, it is enough to override iter_elt in RLL, and build an iterator that will scan its sublists repeatedly calling iter_elt on them if possible else iter, until all are exhausted. Code could be:
class RLL(LL):
    class iter:
        def __init__(self, rll):
            self.iters = LL(i.iter_elt() if hasattr(i, 'iter_elt') else iter(i)
                            for i in rll)
            self.cur = self.iters.front
            self.prev = None
        def __iter__(self):
            return self
        def __next__(self):
            try:
                elt = next(self.cur.value)
                self.prev = self.cur
                self.cur = self.cur.next
                if self.cur is None:
                    self.cur = self.iters.front
                    self.prev = None
            except StopIteration:
                self.cur = self.cur.next
                if self.cur is None:
                    if self.prev is None:
                        raise
                    self.cur = self.iters.front
                    self.prev = None
                else:
                    if self.prev is None:
                        self.iters.front = self.cur
                    else:
                        self.prev.next = self.cur
                elt = self.__next__()
            return elt

    def iter_elt(self):
        return RLL.iter(self)

A: I totally agree with @Serge Ballesta that you should create a LinkedList class to do this, here's how it could be done the procedural way you're doing things.
Also note that it's not done recursively—but rather "pythonically".
from itertools import chain, zip_longest

class LN:
    def __init__(self, value, next=None):
        self.value = value
        self.next  = next

def list_to_ll(l):
    if l == []:
        return None
    front = rear = LN(l[0])
    for v in l[1:]:
        rear.next = LN(v)
        rear = rear.next
    return front

def iterate(ll):
    while ll is not None:
        yield ll.value
        ll = ll.next

def str_ll(ll):
    return '->'.join(str(v) for v in iterate(ll)) + '->None'

def alternate(ll_1, ll_2):
    _NULL = object()
    chained = chain.from_iterable(zip_longest(iterate(ll_1), iterate(ll_2),
                                              fillvalue=_NULL))
    return list_to_ll(list(v for v in chained if v is not _NULL))

if __name__ == '__main__':

    ll_1 = list_to_ll(['a','x','b','e'])
    ll_2 = list_to_ll(['d','f','m'])

    print(str_ll(alternate(ll_1, ll_2)))  # -> a->d->x->f->b->m->e->None


text:
Q: Install Package From Upstream I am trying to install latest version of Apache2 (2.4.52) without compiling from source and all that headache. I saw Ubuntu CVE and there is this version available but in Upstream I tried to do Pin install but that's not working.
/etc/apt/apache2::
Package: apache2
Pin: version 2.4.52
Pin-Priority: 990

Ubuntu Version
Distributor ID: Ubuntu
Description:    Ubuntu 21.10
Release:        21.10
Codename:       impish

But still apt upgrade or apt-get upgrade can't find this new version

A: Fixes for CVE-2021-44790
are available for these releases provided in your table on https://ubuntu.com/security/CVE-2021-44790
That means the package 2.4.48-3.1ubuntu3.2 available for Ubuntu 21.10 contains the fix you're after.
Packages are not upgraded to later versions; fixes get back-ported to the existing packages (unless it's more work to backport what's required & re-test, compared to just using a newer package & re-testing everything impacted by the upgraded package - that is rare)


text:
Q: Windows7 error (0xc0000005) in many applications even after format and reinstall multiple times Windows7 SP1 x64
I had to format my PC and reinstall windows7 because of a small issue some days ago, i was able to do so without much problem.
Almost everything worked fine except for a small thing so i decided to format and reinstall windows again.
Now many software (even from microsoft) give an error 0xc0000005 when try to run it.

*

*Software from microsoft

*Third party software
Applications like chrome don't show transparent icons when downloading, all have a black square in the background, so there is definitely something weird going on.
I tried to find the error in the event viewer, and it think this is it, but not sure.
When i re-downloaded the same exact software and saved it on C: instead of D:, since it worked so i thought it was a disk error/corruption (even if most software except some DO work fine) but it was not the case.
I tried the following solutions:

*

*Format system partition and reinstall windows 7 multiple times.

*Run sfc /scannow.

*Test the ram memory.

*Restore windows 7 (even if it's a new installation) to it's most previous point.

*Do a disk check on D: unit.

*Disable DEP. (can't do this for microsoft software like C++ redistributables)

None worked or found a problem.
I am at my wits end, i tried everything and NOTHING works.
How can an OS suddenly fail to open files out of nowhere when it worked previous times it was installed?
Machines execute the exact same code, it is beyond logic and common sense that reinstalling a OS that had almost everything working fine a day ago just chose not to work properly out of the blue, no matter how many times re-install it!.
And it's even more illogical that it do not show any kind of error when try to examine the problem.

A: Well it does not seem like a disk error.
Try installing Windows 8.1 or 10 and if the applications work than it is clear that it is an operating system problem
If you try to call Microsoft they will just tell you are using an unsupported system but here is the trick try searching on Google for 'Windows thin pc' or 'Windows 7 embedded standard'. You will be surprised to know that these are official variations of windows 7 that are still being supported by Microsoft! There maybe some update that fixes your problem and if you call Microsoft and tell them your problem, they have no other option but to solve your problem.
I hope this helps.
Thanks.

A: The Event Viewer error is not indicative of any issue and can be
safely ignored.
It comes from an error in the Windows 7 SP1 DVD/ISO creation process that caused a WMI registration to remain in the DVD/ISO.
Since this registration is designed to work only during the DVD/ISO
creation process, it fails to run on a live system and causes these
events.
If you want to prevent these events from getting,follow the steps mentioned
in the Microsoft article
Event ID 10 is logged in the Application log after you install Service Pack 1 for Windows 7 or Windows Server 2008 R2.
For correctly installing Windows 7, follow my steps from the post
Windows 7 Windows update error 80072EFE.
Then download and install any hardware drivers that were supplied by
the manufacturer of your computer.
If you have done the above steps and the problems still arrive, I would
consider the possibility of a hardware issue. I gather that this computer
came with Windows 7, so is pretty old, so a hardware issue is possible
after a demanding operation such as installing Windows.
I suggest running
MemTest86
overnight, for as many passes as you the time.
Publish online (DropBox, OneDrive etc.) the HTML report file for us
to have a look at.
This tests more than just the memory; also testing incidentally
the CPU and the memory controller.


text:
Q: What is better to use: Action vs ActionListener? Myself, I always use ActionListener as swing event-handler (e.g. button-click), and it is the most common listener I've seen in most swing applications.
However, Some Swing professionals here in stackoverflow often advise to use Action rather than ActionListener. What benefits I get from doing so?

A: An Action is preferred if you need to share functionality across components. From the docs

if you have two or more components that perform the same function, consider using an Action object to implement the function.

but also says

An Action object is an action listener that provides not only action-event handling, but also centralized handling of the state of action-event-firing components such as tool bar buttons, menu items, common buttons, and text fields. The state that an action can handle includes text, icon, mnemonic, enabled, and selected status.


text:
Q: enable browser scrollbar working I have html like below

and the scrollbar will show when "bottom" is overflow.
Since bottom div is under top div, scrolling is not working.
My target is that mouse cannot directly click on any element in "bottom" div, but can use mouse wheel and drag scrollbar to achieve "bottom" scrolling.

A: Don't use z-index if you just want to make the whole div unclickable, remove those z-indexs and add pointer-events: none to your bottom div.
Like:

I don't know what's the use of this

A: Replace overflow: hidden;
Also add  style="overflow:hidden;"  in the parent div.


text:
Q: Using the Law Quadratic Residues I'm looking to find if $\bigg(\frac{1210}{41}\bigg)$ so is 1210 a quadratic residue modulo 41.
So I have $\bigg(\frac{1210}{41}\bigg)=\bigg(\frac{21}{41}\bigg)=\bigg(\frac{3}{41}\bigg)\bigg(\frac{7}{41}\bigg)$
Taking the question in parts i get $\bigg(\frac{3}{41}\bigg)\bigg(\frac{41}{3}\bigg)=(-1)^{20}=1 \rightarrow \bigg(\frac{2}{3}\bigg)=-1$
Using this i then have $-\bigg(\frac{7}{41}\bigg)=-\bigg(\frac{7}{41}\bigg)\bigg(\frac{41}{7}\bigg)=(-1)^{60}=1 \rightarrow -\bigg(\frac{41}{7}\bigg)=-\bigg(\frac{6}{7}\bigg)=1$
So i get -1 therefore 1210 is not a Quadratic Residue modulo 41.
Is this the correct answer for this question and correct method?

A: $$\left(\frac3{41}\right)=\left(\frac{41}3\right)=\left(\frac23\right)=-1$$
$$\left(\frac7{41}\right)=\left(\frac{41}7\right)=\left(\frac{-1}7\right)=-1$$


text:
Q: How to use a customized AppBar I would like to get an effect as the one shown on the picture (extracted from some application that uses it): an AppBar that holds a custom layout.

How could this be achieved? can it be done with a customization of the AppBar? or should I use a regulalr layout simulating being an AppBar?
Thank you!

A:     <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:layout_scrollFlags="scroll|enterAlways"
    app:layout_collapseMode="pin">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- This is a centered logo -->
        <ImageView
            android:id="@+id/toolbar_logo"
            android:src="@drawable/logo"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_marginRight="?attr/actionBarSize"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="4dp"
            android:layout_gravity="center" />

        <!-- This is a centered title -->
        <!--
        <TextView
            android:id="@+id/toolbar_title"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_marginRight="?attr/actionBarSize"
            android:layout_gravity="center"
            android:gravity="center_vertical"
            android:visibility="gone"
            android:text="@string/app_name"
            android:textColor="@color/white"
            style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"
            />
            -->

        <!-- This is a custom left side button -->
        <!--
        <ImageButton
            android:id="@+id/btn_settings"
            android:layout_width="?attr/actionBarSize"
            android:layout_height="?attr/actionBarSize"
            android:layout_marginRight="?attr/actionBarSize"
            android:layout_gravity="start|center_vertical"
            android:visibility="invisible"
            android:src="@drawable/ic_settings_white_24dp"
            style="@style/Widget.AppCompat.ActionButton" />
            -->

        <!-- This is a custom right side button -->
        <!--
        <ImageButton
            android:id="@+id/btn_search"
            android:layout_width="?attr/actionBarSize"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="end"
            android:src="@drawable/ic_magnify_white_24dp"
            style="@style/Widget.AppCompat.ActionButton" />
            -->

    </FrameLayout>
</android.support.v7.widget.Toolbar>

Custom Toolbar and call this layout in main layout.Can use any layout inside it

A: You Can Use Whatever Layout You Desire As normally you do everywhere, The Structure Example below can be a good Guide:

< android.support.design.widget.CoordinatorLayout
  ... >

  <DrawerLayout >
  ...
  </DrawerLayout>

     <android.support.design.widget.AppBarLayout
     ... >

       <android.support.design.widget.CollapsingToolbarLayout
       ... >

         <FrameLayout
         ... >
         // ---- WHATEVER LAYOUT YOU WANT

         </FrameLayout>

         <android.support.v7.widget.Toolbar
         .../ >

         <android.support.design.widget.TabLayout
         .../>

       </android.support.design.widget.CollapsingToolbarLayout>

     </android.support.design.widget.AppBarLayout>

  <android.support.v4.widget.NestedScrollView
  ... />

  <android.support.v4.view.ViewPager
  .../>
</android.support.v4.widget.NestedScrollView>

Note: The FrameLayout I put in the code, Literally Can be Anything, A RelativeLayout, A LinearLayout, etc...


text:
Q: MySQL problem - COMPLETE server overrun! Please advise This is my first question here so please don't be tough on me... :P
I usually tend to google my way to a solution but now I'm in a hurry and have used up all the resources I had...
because my website is a commercial one, it would be fair to go ahead and pay someone to help me but... I have some financial problems myself, this was the 3rd month of payment to my dedicated server, still it was only the first month since my site was actually up... I have made it all by myself because I cannot afford paying anyone, and have no ads on it because I don't think I would be getting anything now and the ads would just be useless...although I intend in using ads later in my site's life, i don't get a dime from the (at least for my budget) expensive server rent... :(
This is my problem:
I have a dedicated server which has been going great until a few days ago when my traffic started going up...for a few days, i keep getting emails from my cpu status monitor from my server...
it's like stuck at full throttle and I'm trying to find out why and repair the problem!...
I'm really desperate so please help me!
here are my latest stats (though they've been like this for like 4 days...)
08:02:35 up 12 days, 14:39,  0 users,  load average: 25.82, 25.98, 25.92
I use stat counter, I think they are pretty accurate (the code is on every page so these are my website's global results)...
My stats are:
Page Loads  Unique Visits
10,367              1,843

My main pages are index.php and videos.php (i run a video site btw)
the index and videos.php pages are always using around 140-150-160% of the cpu
i mean huh?
they're using more than 100%? like loaning or what?
what they both do is:
(mainly the videos page, the index is just a simplified version of it)
check -and take if passed- a query and a page number.
query a database, take results from a table and show them
I use mysql_connect for everything i take from mysql.
I heard of permanent connections in mysql as being a possible solution to a large number of queries, but also read about a lot of cons to this method caused by security issues...
please advise?
my database is myisam engined
I have 2 main tables: games and videos.
Along them are around 5-6000 tables used for storing comments...
 games table:    9   columns
 id - primary
 name - fulltext - used by my search

 videos table:    17 columns
 indexes:
 id-primary
 title,tags-fulltext-used by search

the rest of the tables are used for comments but they dont have any index except the id field.
they only keep the comment and the date in themselves.
when i load a search page, all data is taken from the db:
search for keywords, take the most relative and then echo all data related to the matched items.
when opening a video page, all comments from a certain db are loaded and displayed in a box.
what is the best thing I can do to reduce processing power use?
also, my support team just emailed me:

we have increased the table-cache to 12000 , please check now how it goes .And also it is better to get a my.cnf file which is most suitable to your working environment , here the mysql variables are set to the default values .

I just read something about the my.cnf file on google but nothing related to my case...
Could someone please indicate me what should my my.cnf file contain? related to my sittuation?
I have my server information here, but it takes some space... how can I close it somehow and you only open if you want to read? without using links?
should i just post it here like this?
Please, if a moderator reads this and can collapse it somehow, please do so!
Server Information:
-------------------------------------------------------

Processor Information
Total processors: 6

Processor #1

Vendor
    AuthenticAMD

Name
    AMD Phenom(tm) II X6 1055T Processor

Speed
    2800.000 MHz

Cache
    512 KB

Processor #2

Vendor
    AuthenticAMD

Name
    AMD Phenom(tm) II X6 1055T Processor

Speed
    2800.000 MHz

Cache
    512 KB

Processor #3

Vendor
    AuthenticAMD

Name
    AMD Phenom(tm) II X6 1055T Processor

Speed
    2800.000 MHz

Cache
    512 KB

Processor #4

Vendor
    AuthenticAMD

Name
    AMD Phenom(tm) II X6 1055T Processor

Speed
    2800.000 MHz

Cache
    512 KB

Processor #5

Vendor
    AuthenticAMD

Name
    AMD Phenom(tm) II X6 1055T Processor

Speed
    2800.000 MHz

Cache
    512 KB

Processor #6

Vendor
    AuthenticAMD

Name
    AMD Phenom(tm) II X6 1055T Processor

Speed
    2800.000 MHz

Cache
    512 KB

Memory Information

Memory for crash kernel (0x0 to 0x0) notwithin permissible range
Memory: 7917400k/8912896k available (2575k kernel code, 208164k reserved, 1304k data, 212k init)

System Information

Linux nrgysrv1.hostrprv1.com 2.6.18-194.32.1.el5 #1 SMP Wed Jan 5 17:52:25 EST 2011 x86_64 x86_64 x86_64 GNU/Linux

Physical Disks

SCSI device sda: 2930277168 512-byte hdwr sectors (1500302 MB)
sda: Write Protect is off
sda: Mode Sense: 00 3a 00 00
SCSI device sda: drive cache: write back
SCSI device sda: 2930277168 512-byte hdwr sectors (1500302 MB)
sda: Write Protect is off
sda: Mode Sense: 00 3a 00 00
SCSI device sda: drive cache: write back
sd 0:0:0:0: Attached scsi disk sda
SCSI device sdb: 2930277168 512-byte hdwr sectors (1500302 MB)
sdb: Write Protect is off
sdb: Mode Sense: 00 3a 00 00
SCSI device sdb: drive cache: write back
SCSI device sdb: 2930277168 512-byte hdwr sectors (1500302 MB)
sdb: Write Protect is off
sdb: Mode Sense: 00 3a 00 00
SCSI device sdb: drive cache: write back
sd 3:0:0:0: Attached scsi disk sdb
sd 0:0:0:0: Attached scsi generic sg0 type 0
sd 3:0:0:0: Attached scsi generic sg1 type 0

Current Memory Usage

             total       used       free     shared    buffers     cached
Mem:       7920256    7873744      46512          0      61148    6980096
-/+ buffers/cache:     832500    7087756
Swap:      4192956        184    4192772
Total:    12113212    7873928    4239284

Current Disk Usage

Filesystem            Size  Used Avail Use% Mounted on
/dev/sda3             1.4T  636G  645G  50% /
/dev/sda1              99M   18M   77M  19% /boot
tmpfs                 3.8G     0  3.8G   0% /dev/shm
/dev/sdb1             1.4T  291G 1016G  23% /backup
/usr/tmpDSK           485M   11M  449M   3% /tmp

----------------------------------------------------

I think this is all the information I have.
If you have mercy on me, please help!...
thanks a million billion times!hot

A:
the index and videos.php pages are always using around 140-150-160% of the cpu i mean huh? they're using more than 100%? like loaning or what?

No, the load is expressed as one unit per CPU, so if your server has four CPUs, a load of 1.00 (or 100%) means that one CPU is at full load and the other three are idling (or two are at 50% load and the other two at 0%, or any similar combination) and a load of 4.00 (or 400%) would mean that all the CPUs are at full capacity.

I use mysql_connect for everything i take from mysql. I heard of permanent connections in mysql as being a possible solution to a large number of queries, but also read about a lot of cons to this method caused by security issues... please advise?

Why should it be a security issue? Maybe it can be a performance issue if misused, but definitely not a security issue.
From what you're writing it seems you're quite a novice on relational database and perhaps web development, the first step I suggest is to buy a database book and learn how they work and how to use them, then a good book on PHP. Otherwise, you will be programming by coincidence and will never resolve your issues.
By the way, if you're new (and you know it) you should give a read to the FAQs, How to ask and Editing help.

A: First, isolate the problem. There's no point in tuning MySQL if the root cause of the problem is in your php code.
Your support said they "increased the table-cache to 12000", so they probably increased the value for table_open_cache from 400 (default) to 12000. (You probably shouldn't have 6000 tables. Reconsider that design.)
For MySQL, study these sections of the MySQL docs.
Tuning Server Parameters

When tuning a MySQL server, the two
  most important variables to configure
  are key_buffer_size and
  table_open_cache. You should first
  feel confident that you have these set
  appropriately before trying to change
  any other variables.

Preconfigured Option Files

MySQL provides a number of
  preconfigured option files that can be
  used as a basis for tuning the MySQL
  server. Look for files such as
  my-small.cnf, my-medium.cnf,
  my-large.cnf, and my-huge.cnf, which
  are sample option files for small,
  medium, large, and very large systems.

Server System Variables
Server Status Variables
You should also have a local or remote system for testing.

A: I think the problem is you have a separate table for each video. All the comments (or whatever) should be stored in the SAME table with a video_id or similar attached to them to link them back to the video in question.


text:
Q: How to pass numbers as arrays - Guzzle I am trying to pass an array of numbers in a multipart to my api. In my api, i check if the numbers are in array form and validate. However, i send my phone numbers in array form but then my api doesn't validate it as an array.
What am i doing wrong in sending my numbers as array
 $request = $client->post($target_url, [
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => 'info',
                ],

                [
                    'name' => 'phone',
                    'contents' => [
                        0 => '+44234234292',
                        1 => '+0234823421'
                    ])
                ],

];

A: As per guzzle docs, 'content' cannot contain arrays, you can pass the array as a json_encoded data or you can send it as
'json' => [0 => '+44234234292',  1 => '+0234823421']


text:
Q: How to link a version of a Git repository with a version of one another Git repository I have two Git repositories, one for the versioning of my application and the other for the versioning of the DB schema.
I would like to use a continuous integration and deployment system, so I need to link each version of the application with the corresponding version of the DB schema, so that the CI system can pull the right application and DB versions and deploy them.
Is there any way to do this thing with Git?
Thank you

A: One approach could be to tag revisions in each repo that need to be linked together.
Then, in your CI system you could pull from the repositories based off of tag.
See https://git-scm.com/book/en/v2/Git-Basics-Tagging for more details on tagging
See Download a specific tag with Git for details on how to pull from a tag.

A: Finally the solution I'm using is to link the Maven version of the DB Schema project into the pom.xml of the DAL of the web application.
This way the web application includes the right entities from the right DAL, and the DAL is related to the right DB schema by means of the Maven version.


text:
Q: AMN and math logic notation I'm not sure this is appropriate for stackoverflow, but I don't know where else to ask. I'm studying the B-Method for proving consistence in requirement specifications, and I have an issue with the logic math notation when specifying the pre conditions of the operations.
Simplifying the original problem, I have a variable which is a subset flights of the cartesian product between  FLIGHT_NO x TIME x TIME, where for each member (no,td,ta), no means the number of the flight, td the time of departure and ta the tme of arrival. How can I get, using math logic notation, the element of  flights that has the biggest value of td?

A: Do you want to get such an element, or to test that an element you have satisfies this property? I am asking because the second seems a sensible precondition to an operation. I don't know the B-Method specifically; I've looked at some documents, but can't find a quick reference, so this may be wrong in some details.
The second should look like this (prj2 is used for the second projection):
HasGreatestTd(flight) = flight \in flights \and \forall flight' (flight' \in flights => prj2(flight) >= prj2(flight'))

Then the first is:
flightWithGreatestTd = choice({flight | HasGreatestTd(flight)})

A: Forgive my ignorance, I'm not familiar with the B-Method. But couldn't you use the uniqueness quantifier? It'd look something like:
there exists a time td such that for all times td', td > td'
and
for all td, td', td'', if td > td'' and td' > td'' then td == td'
This, of course, assumes that there is exactly one element in the set. I can't really tell if the B-Method allows for the full power of first order logic but I assume you could come close to this.

A: It is possible to define functions in B. Functions have constant values and are to be listed in the ABSTRACT_CONSTANTS clause, and defined in the PROPERTIES clause. I try to explain how you can use this construct to solve your problem.
Follows a small excerpt where

*

*a shortcut for the cartesian product giving flight information is introduced;

DEFINITIONS
    FLIGHT_INFO == FLIGHT_NO * TIME * TIME

*four constants are declared, the first three are "accessors", and the last maps a non-empty set of flight informations to the flight information with the largest departure time.

CONSTANTS
    flight_no, flight_departure, flight_arrival, last_flight

*Then these constants are typed and defined as total functions. Note that the last function must take as input a non-empty set. Here I used to different approaches to specify these functions. One is definitional (with an equality), and the other is axiomatic.

PROPERTIES
    // typing
    flight_no: FLIGHT_INFO --> FLIGHT_NO &
    flight_departure: FLIGHT_INFO --> TIME &
    flight_arrival: FLIGHT_INFO --> TIME &
    last_flight : POW1(FLIGHT_INFO) --> FLIGHT_INFO &
    // value
    flight_no = %(no, dt, at).(no |-> dt |-> at : FLIGHT_INFO | no) &
    flight_departure = %(no, dt, at).(no |-> dt |-> at : FLIGHT_INFO | dt) &
    flight_arrival = %(no, dt, at).(no |-> dt |-> at : FLIGHT_INFO | at) &
    !fs.(fs : POW1(FLIGHT_INFO) =>
       last_flight(fs) : fs &
       !(fi).(fi : FLIGHT_INFO & fi : fs =>
          flight_departure(fi) <= flight_departure(last_flight(fs)))


text:
Q: Using any material-ui component results in error in the  component App.js contains the following:
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
import TextField from '@material-ui/core/TextField';

class App extends Component {

  render() {
    return (
      <TextField id="time" type="time" />
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

This error is returned in the browser console and nothing is rendered:
The above error occurred in the <WithStyles(ForwardRef(TextField))> component:
    in WithStyles(ForwardRef(TextField)) (created by App)
    in App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/docs/error-boundaries.html to learn more about error boundaries. react-dom.development.js:16013:13

TypeError: react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext is not a function main.js line 1932 > eval:9:55
    useTheme webpack:///./node_modules/@material-ui/styles/esm/useTheme/useTheme.js?:9
    makeStyles webpack:///./node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js?:233
    WithStyles webpack:///./node_modules/@material-ui/styles/esm/withStyles/withStyles.js?:65
    React 22
        updateForwardRef
        beginWork
        performUnitOfWork
        workLoop
        callCallback
        invokeGuardedCallbackDev
        invokeGuardedCallback
        replayUnitOfWork
        renderRoot
        performWorkOnRoot
        performWork
        performSyncWork
        requestWork
        scheduleWork
        scheduleRootUpdate
        updateContainerAtExpirationTime
        updateContainer
        render
        legacyRenderSubtreeIntoContainer
        unbatchedUpdates
        legacyRenderSubtreeIntoContainer
        render
    <anonymous> webpack:///./leadmanager/frontend/src/components/App.js?:57
    js http://localhost:8000/static/frontend/main.js:97
    __webpack_require__ http://localhost:8000/static/frontend/main.js:20
    <anonymous> webpack:///./leadmanager/frontend/src/index.js?:2
    js http://localhost:8000/static/frontend/main.js:109
    __webpack_require__ http://localhost:8000/static/frontend/main.js:20
    <anonymous> http://localhost:8000/static/frontend/main.js:84
    <anonymous> http://localhost:8000/static/frontend/main.js:87

If <TextField id="time" type="time" /> is replaced with
Test
 the application runs with no problems. The same error results when using other components such as checkboxes.
What is causing this error and how to use material-ui components?


text:
Q: Match [Char] to instance of Read I have a problem with a user-defined data structure and the instance of Read
First here is my data structure
data Nat = Null | Succ Nat

My function for read is defined like this
readNatNat :: String -> Nat
readNatNat xs   |first == '(' = readNatNat (tail xs)
                |first == ' ' = readNatNat (tail xs)
                |firstFour == "Succ" = (Succ (readNatNat(drop 4 xs)))
                |firstFour == "Null" = Null
                |b `elem` [0..] = toNatInt(b)
                 where b = (read(xs)::Int)
                    first = head xs
                    firstFour = take 4 xs

toNatInt :: Int -> Nat
toNatInt x | x==0 = Null
       | x<0 = error "Unter Null gibts kein Int 2 Nat"
       | otherwise = Succ(toNatInt(x-1))

readNatNat as standalone function works as expected, but when I want to use it with instance of Read and try to load it i get the following exception
Couldn't match type `[Char]' with `Int'
Expected type: Int -> ReadS Nat
  Actual type: String -> Nat
In the expression: readNatNat
In an equation for `readsPrec': readsPrec = readNatNat
In the instance declaration for `Read Nat'
Failed, modules loaded: none.

Programming the other instances like Enum,Eq,Show etc. was quite straightforward.
I understand that Read expects an Int, but i don't know why ;)
I thought Read is the opposite of show and takes a String and parses it into my data structure.
I defined Show like this
instance Show Nat where
     show (Succ a) = showsRealSucc(Succ a)
     show Null = show "Null"

showsRealSucc :: Nat -> String
showsRealSucc Null = "Null"
showsRealSucc (Succ a) = (if a/= Null then ("Succ ("++showsRealSucc(a)++")")
                                      else "Succ Null")

For your understanding of Nat:
Its a representation for natural numbers, so when I type readNatNat "3" the output is
"(Succ(Succ(Succ Null)))"
Thanks in advance!!

A: readsPrec takes a precedence parameter
readsPrec    :: Int -> ReadS a
type ReadS a = String -> [(a,String)]

so
readsPrec    :: Int -> String -> [(a,String)]

readsPrec takes an additional Int parameter to indicate the precedence in the surrounding context, so for example if you were reading Just Null the surrounding precedence is 10, function application.
In your case, I think you could just use the utility function readParen :: Bool -> ReadS a -> ReadS a to handle that:
instance Read Nat where
readsPrec prec = readParen prec natReads where
  natReads xs = [(readNatNat xs,"")]

readsPrec is supposed to be a mini-parser

*

*If the parse fails, you should return [], not cause an error.

*You should return the remainder of the input in the remaining String part

*(There should be a list of possible parses)

3. List of successes and
2. Return the remainder:
This workaround wouldn't be true to how readsPrec is supposed to work. The list [(a,String)] should consist of possible parses and remainder strings, so that readsPrec 5 "Null,Null,Succ Null]" should be [(Null, ",Null,Succ Null]" ]. As I've tried to hint there, the remainder of the unconsumed input can be used while parsing a list of values etc.
Important:
If you don't do this, you're much more likely to get erroneous results from read "[Null,Succ Null]".
It's rare that there would be more than one possible parse, but for example, if you had decided to show your Nat values as "0+1+1" you would need to produce for that input, the list [(Null,"+1+1"), (Succ Null, "+1"), (Succ (Succ Null), "") ]
This means you should check the number of brackets on your way in and out, so that you can return the appropriate amount in the remainder string: readsPrec 3 "((Succ (Succ Null)))))" should be [(Succ (Succ Null), "))"].
1. Don't cause an error, return []
If the input isn't a valid Nat, you need to return []. I spot three problem lines:
  where b = (read(xs)::Int) -- could crash

  first = head xs  -- could crash

  | x<0 = error "Unter Null gibts kein Int 2 Nat" -- crashes

You should really convert these into a check followed with an answer of [].
Parse recursively
Sadly, I think it means you need to rewrite the parser somewhat. The good news is that it's essentially recursive, and readParen False can do most of the work for you. A useful helper function would be
fmapPairs :: (a -> b) -> [(a,String)] -> [(a,String)]
fmapPairs f pairs = [(f a,xs) | (a,xs) <- pairs]

so that you could fmapPairs Succ (readParen False) the remainder when you'd found "Succ". Let me know if you need more than this hint to finish the job (which I think you've shown you're capable of, and is a nice exercise now that you know more about what readsPrec).


text:
Q: How to make sure, that grub always starts the default entry after a timeout? When booting the Ubuntu system went wrong and the user is forced to cut off power, there is a feature, that disables automatic selection of grub menu upon next boot.
Normally this is a nice feature to have, but sometimes it gets triggered when I power on the system remotely via WOL.
Is there any way to disable it?


text:
Q: PyQt5: How to set a priority to a pyqtSignal? 1. Background info
I'm working in Python 3.7. The python Qt version Pyqt5 enables you to fire custom pyqt signals. For example:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class MyClass(QObject):
    mysignal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.mysignal.connect(self.bar)
        return

    def foo(self):
        self.mysignal.emit("foobar")
        return

    @pyqtSlot
    def bar(self, mystr):
        print("signal received: {0}".format(mystr))
        return

2. The problem
PyQt starts an event listener loop in the main thread: it waits for incoming events on a queue and processes them one-by-one. Most of these events are user-invoked things like pushing a button, clicking something, ...
If you fire pyqt signals programatically, as in the foo() function above, you also push events onto this queue (I think). That shouldn't be a big deal, unless you fire too many pyqt signals in a short burst. The queue is overwhelmed and user events don't get processed in time. The user sees a freezed GUI. Yikes!

3. Solution
One way to tackle this problem could be assigning low priorities to programatically fired pyqt signal. Is this possible? How?
If not - do you know other ways to solve the problem?

A: In the case of direct connections (sender and receiver in the same thread), the slot will be directly called when you emit your signal.
So, in your example, you can replace your emit by a direct call to self.bar.
But, if your slot is too long, the event loop has to wait before it will be able to process the user events.
If your UI is freezing when you call your slot, that means you should use another thread to let the event loop process user events.


text:
Q: How to have correct page numbering with twoside=false in PDF (produced from bookdown)? I have simple bookdown document:
---
title: Page number problem
documentclass: book

site: bookdown::bookdown_site
output:
  bookdown::pdf_book: default

papersize: a4
geometry: 'left=0.8in, right=0.4in, top=0.5in, bottom=1in, twoside=false'

header-includes:
- \usepackage[fontsize=14pt]{scrextend}
- \pagestyle{plain}

---

# Header 1

Some text on page 2

\newpage

# Header 2

Some text on page 3

I expect the following page numbering:

*

*title (not numbered)

*contents (numbered)

*chapter 1 (numbered)

*chapter 2 (numbered)

but got two No 1 pages:

What am I doing wrong or missed?

A: This is standard behavior of the LaTeX book and report classes, though I cannot point you to the relevant documentation right now. For onside documents the titlepage is treated like an un-numbered cover page. If you want to start the actual page numbering at 2, you can add \stepcounter{page} before the TOC. One way to achieve this would be to add
include-before:
- \stepcounter{page}

to your YAML header.


text:
Q: react-native: display superscript text in Text component I have the following text:

Answer the following Question:
 (a+b)2=?

I want to do the following with this text:

*

*parse it tag by tag, so that I can render each of the tag in a custom way. I could, very well, achieve that using this library: https://github.com/Thomas101/react-native-fence-html.

*while parsing the superscript/subscript tags, render the content in proper fashion. This is where I'm stuck right now.

What I'm doing right now, is that I put the entire text (from start to end) in a Text component; and each span and br tags are also rendered as Text components nested within the parent Text component (the one for the div tag).
How do I render the superscript/subscript text?
Note: I did find a solution here: Superscript Text in React Native
But, creating a View inside a Text component needs the View to have fixed dimensions, and that is something not achievable.

A: One option would be to convert the HTML to Markdown first and then render the markdown. I believe for both of those actions there are libraries available.


text:
Q: MapReduce in python to calculate average characters I am new to map-reduce and coding, I am trying to write a code in python that would calculate the average number of characters and "#" in a tweet
Sample data:

1469453965000;757570956625870854;RT @lasteven04: La jeune Rebecca
#Kpossi, nageuse, 18 ans à peine devrait être la porte-drapeau du #Togo à #Rio2016 hyperlink;Twitter for Android 1469453965000;757570957502394369;Over 30 million women
footballers in the world. Most of us would trade places with this lot
for #Rio2016 ⚽ hyperlink;Twitter for iPhone

fields/columns details:
 0: epoch_time  1: tweetId  2: tweet  3: device

Here is the code that I've written, I need help to calculate the average in the reducer function, any help/guidance would be really appreciated :-
updated as per the answer provided by @oneCricketeer
import re
from mrjob.job import MRJob

class Lab3(MRJob):

def mapper(self,_,line):

    try:
        fields=line.split(";")
        if(len(fields)==4):
            tweet=fields[2]
            tweet_id=fields[0]
            yield(None,tweet_id,("{},{}".format(len(tweet),tweet.count('#')))
    except:
        pass

def reduce(self,tweet_id,tweet_info):
    total_tweet_length=0
    total_tweet_hash=0
    count=0
    for v in tweet_info:
        tweet_length,hashes = map(int,v.split())
        tweet_length_sum+= tweet_length
        total_tweet_hash+=hashes
        count+=1

    yield(total_tweet_length/(1.0*count),total_tweet_hash/(1.0*count))

if __name__=="__main__":
    Lab3.run()

A: Your mapper needs to yield a key and a value, 2 elements, not 3, therefore outputting both average length and hashtag count should ideally be separate mapreduce jobs, but for this case you could combine them because you're processing the entire line, not separate words
# you could use the tweetId as the key, too, but would only help if tweets shared ids
yield (None, "{} {}".format(len(tweet), tweet.count('#')))

Note: len(tweet) includes spaces and emojis, which you may want to exclude as "characters"
I'm not sure you can put _ in a function definition, so maybe change that too

Your reduce function is syntactically incorrect. You cannot put a string as a function parameter, nor use += on a variable that wasn't already defined. Then, an average calculation would require you to divide after you've totalled and counted (so, one returned result per reducer, not per value, in the loop}
def reduce(self,key,tweet_info):
    total_tweet_length = 0
    total_tweet_hash = 0
    count = 0
    for v in tweet_info:
        tweet_length, hashes = map(int, v.split())
        total_tweet_length += tweet_length
        total_tweet_hash += hashes
        count+=1
    yield(total_tweet_length / (1.0 * count), total_tweet_hash / (1.0 * count))  # forcing a floating point output


text:
Q: In python, why does calling a string, "X", display it in ASCII, but calling "print X" display it in unicode? I've got a list of strings, along the lines of list=[a,b,c,d,e].
When I call list[2], the string c is displayed as ASCII; when I call print list[2], however, it's displayed as unicode. Why does this discrepancy exist?

A: This is mainly because strings in Python 2 are not text strings but byte strings.
I suppose you are in a REPL environment (a Python console). When you evaluate something in the console, you get its printed representation which is the same as calling print repr() on the expression:
l = ['ñ']
l[0] # should output '\xc3\xb1'
print repr(l[0]) # should output the same

This is because your console is in UTF-8 mode (if you get a different representation for ñ it is because your console uses some other text representation) so when you press ñ you are actually entering two bytes 0xc3 and 0xb1.
repr() is a Python method that always returns a string. For primitive types, this string is a valid source to rebuild the value passed as parameter. This case it returns a string with a sequence of bytes that recreates another string with the ñ encoded as UTF-8. To see this:
repr(l[0]) # should print a string within a string: "'\\xc3\\xb1'"

So when you print it (which is the same as just evaluating in the console), you get the same string without the outer quotes and the escaped characters properly replaced. I.e:
print repr(l[0]) # should output '\xc3\xb1'

But, when you print the value, i.e: print l[0], then you send those two bytes to the console. As the console is in UTF-8 mode, it decodes the sequence and translate it to only one character: ñ. So:
print l[0] # should output ñ

If you want to store text strings, you must use the modifier u before the string. This way:
text = u'ñ'

Now, when evaluating text you will see its Unicode codepoint:
text # should output u'\xf1'

And printing it should recreate the ñ glyph:
print text # should output `ñ`

If you want to convert text into a byte string representation, you need an encoding scheme (such as UTF-8):
text.encode('utf-8') == l[0] # should output True

Similarly, it you want the Unicode representation for l[0], you'll need to decode those bytes:
l[0].decode('utf-8') == text # should output True

All this said, notice in Python 3, default strings are indeed Unicode Strings and you need to prefix the literal notation with b to produce byte strings.

A: It's because those two ways of displaying a string use different routes to get to the final result. x by itself in the REPL will invoke repr(x) and display that, but print(x) will invoke str(x) and display that instead. Classes are allowed to define __repr__ and __str__ separately, so they don't always return the same value.
>>> x = u"a"
>>> x
u'a'
>>> print x
a
>>> repr(x)
"u'a'"
>>> str(x)
'a'
>>>


text:
Q: Need approach for Setting value to a property based on numerous conditions I have many properties spread across a number of classes. Values to these properties need to be assigned based on a number of conditions (around 5 to 8 for each property). I am looking for an alternative for numerous 'if else' conditions.
I have come across 'Rule Engine' off late but AFAIK it can be used for validating the rules.
Any design suggestion would be of great help.

A: I'm not sure whether this is a "better" solution for you, but I'll try to explain.

Value to these properties need to be assigned based on a number of conditions (around 5 to 8 for each property).

I think you mean that you always need to write this, which is annoying:
if (condition1 && condition2 && condition3 && condition4 && condition5) {
    Property1 = Value1;
}

if (condition1 && condition2 && condition3 && condition4 && condition5) {
    Property2 = Value2;
}
// ...

I think maybe this method can solve your problem?
public static void SetValueForPropertyIf<T>(Predicate<object>[] conditions, ref T property, T value) {
    foreach (var predicate in conditions) {
        if (!predicate(null)) {
            return;
        }
    }
    property = value;
}

And you can just call the method with a list of lambda expressions, ignore the argument (because it's always null), a variable to be passed by reference, and a value to set if all the conditions are met.
However, this only works for variables because I'm pretty sure properties cannot be passed by reference (with the ref keyword). So you have to declare your properties like this:
private int someVariable;

public int SomeVariable {
    get {return someVariable;}
    set {someVariable = value;}
}

And if you don't like the parameter of the Predicate delegate not being used, define your own delegate!
public delegate bool MyDelegate();

Here is an example of how to use this method, in case you didn't understand what I meant.
class MyClass {
    private int someVariable;

    public int SomeVariable {
        get {return someVariable;}
        set {someVariable = value;}
    }

    public MyClass() {
        someVariable = 10;
        MyDelegate[] conditions = {
            (() => 7 < 10),
            (() => 77 == 77),
            (() => "Sweeper is awesome".Contains("Sweeper")),
            (() => String.IsNullOrEmpty(""))
        };
        SetValueForPropertyIf(conditions, ref someVariable, 20);
    }
}

In this class's constructor, I first created some conditions, which are all true. Then I call the method with these conditions. Note that I used someVariable (The field) instead of SomeVariable (The property) as the ref parameter.
And then you can print SomeVariable:
MyClass mc = new MyClass();
Console.WriteLine(mc.SomeVariable);

The output is 20. Hooray!


text:
Q: Wildfly issue or bug with rerendering composite component - NoSuchMethodException io.undertow.servlet.spec.PartImp.() I have a problem with using a composite component. When the component needs to be rerendered (because i have panels which are shown / hidden based on a user action) I got following error. (He wants to restore a class by creating a new instance of it with the default constructor, but he can't find / execute that constructor because it doesn't exist ? But I don't understand why he wants to do this and why it fails...):
I tried to run exactly the same code with wlp (websphere liberty profile) and there it works as a charm so I'm suspecting a problem in undertow !
=> when I look at the implementation of that class I don't find a default constructor in the class ( PartImpl code ) So it's logic that he can't create it, but why does he want to restore / create an instance of that server specific class ??

**java.lang.InstantiationException: io.undertow.servlet.spec.PartImpl
      io.undertow.servlet.spec.PartImpl.() **

This class is a Wildfly class (undertow is used by Wildfly) I suppose
While debugging I found out this code:

*

*this: StateHolderSaver@30209

*classname: io.undertow.servlet.spec.PartImpl

*result: null (throws exception below)
try {
    toRestoreClass = loadClass(className, this);
}
catch (ClassNotFoundException e) {
    throw new IllegalStateException(e);
}

if (null != toRestoreClass) {
        try {
            result = toRestoreClass.newInstance();
        }
        catch (InstantiationException e) {
            throw new IllegalStateException(e);
        }

Here is the error:
ERROR javax.enterprise.resource.webcontainer.jsf.context  - java.lang.IllegalStateException: java.lang.InstantiationException: io.undertow.servlet.spec.PartImpl
at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:153)
at javax.faces.component.ComponentStateHelper.restoreState(ComponentStateHelper.java:303)
at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1629)
at javax.faces.component.UIOutput.restoreState(UIOutput.java:286)
at javax.faces.component.UIInput.restoreState(UIInput.java:1420)
at com.sun.faces.application.view.FaceletPartialStateManagementStrategy$2.visit(FaceletPartialStateManagementStrategy.java:379)
at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.restoreView(FaceletPartialStateManagementStrategy.java:366)
at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:138)
at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:123)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:591)
at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:151)
at org.ocpsoft.rewrite.faces.RewriteViewHandler.restoreView(RewriteViewHandler.java:102)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:353)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:353)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:353)
at org.omnifaces.viewhandler.OmniViewHandler.restoreView(OmniViewHandler.java:104)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:353)
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:199)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:123)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:226)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at be.raes.web.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:22)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at be.raes.web.filter.SecurityFilter.doFilter(SecurityFilter.java:129)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at be.raes.web.filter.LanguageResolverFilter.doFilter(LanguageResolverFilter.java:49)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.jrHandle(ServletInitialHandler.java)
at sun.reflect.GeneratedMethodAccessor245.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.__invoke(DelegatingMethodAccessorImpl.java:43)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:498)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Some important last part:
Caused by: java.lang.InstantiationException: io.undertow.servlet.spec.PartImpl
at java.lang.Class.newInstance(Class.java:427)
at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:150)
... 86 more

Caused by: java.lang.NoSuchMethodException: io.undertow.servlet.spec.PartImpl.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 87 more

Here is my component code:
<cc:interface componentType="fileComponent">
<cc:attribute name="label" type="java.lang.String"/>
<cc:attribute name="value" type="java.lang.Object"/>
<cc:attribute name="action" method-signature="void listener()"/></cc:interface>

<cc:implementation>
<uc:component id="#{cc.clientId}"
              composite="true">

    <uc:fileUpload id="fileUpload"
                   label="#{cc.attrs.label}"
                   value="#{cc.file}"
                   action="#{cc.uploadFile}"
                   render="#{cc.clientId}"
                   displayed="#{empty cc.fileContainer}"
                   accept="image/png,
                           image/jpeg"/>

    <uc:component id="fileContainer"
                  label="#{cc.attrs.label}"
                  displayed="#{not empty cc.fileContainer}">

            <h:commandLink ajax="true">
                <p:fileDownload value="#{cc.downloadFileContainer}"/>
            </h:commandLink>

        <o:commandScript name="action"
                         actionListener="#{cc.attrs.action}"
                         render=":#{cc.clientId}"
                         execute=":#{cc.clientId}"/>

    </uc:component>

</uc:component>

Component class:
@FacesComponent("fileComponent")
public class FileComponent extends UIInput implements NamingContainer {
@Override
public String getFamily() {
    return UINamingContainer.COMPONENT_FAMILY;
}

@Override
public Object getSubmittedValue() {
    return getFileContainer();
}

public FileContainer createFileContainer() {
    return new FileContainer();
}

public void uploadFile() throws IOException {
    FileContainer fileContainer = createFileContainer();

fileContainer.setFileName(FilenameUtils.getName(getFile().getSubmittedFileName()));
    fileContainer.setContent(Utils.toByteArray(getFile().getInputStream()));

    setFileContainer(fileContainer);
}

public void downloadFileContainer() throws IOException {
    Faces.sendFile(getFileContainer().getContent(), getFileContainer().getFileName(), true);
}

public Part getFile() {
    return (Part) getStateHelper().eval("file");
}

public void setFile(Part file) {
    getStateHelper().put("file", file);
}

public FileContainer getFileContainer() {
    return (FileContainer) getStateHelper().eval("filecontainer", getValue());
}

public void setFileContainer(FileContainer fileContainer) {
    getStateHelper().put("filecontainer", fileContainer);
}

}
JSF file (usage of component):
... <mc:fileComponent value="#{bean.fileContainer}" /> ...

Backing bean
@ViewScoped
@Named("bean")
public class Bean implements Serializable {
  private FileContainer fileContainer;
  //getters & setters etc
}

components.taglib.xml:
 ...<tag>
    <tag-name>fileComponent</tag-name>
    <component>
        <resource-id>components/fileComponent.xhtml</resource-id>
    </component>
    <attribute>
        <name>id</name>
    </attribute>
    <attribute>
        <name>label</name>
    </attribute>
    <attribute>
        <name>value</name>
        <required>true</required>
    </attribute>
    <attribute>
        <name>action</name>
    </attribute>
</tag>...

Tech Stack: (java 8 & EE7 & primefaces 6.1 & Wildfly 10.1)
Thank you for the help


text:
Q: Converting xml attribute double quotes to single quotes (utility needed, pref java) I have a seriously annoying problem. My company uses castor to marshall and unmarshall xml. I'm working on integrating with another company and it looks like their xml parser requires attributes to be single-quoted. Castor is hardcoded to use double quotes. Whoops!
Does anyone know of a utility (preferrably a java library) which can safely convert these quotes?
Simple regexps are not a preferred solution because it will become extremely complicated and buggy when trying to fix escaped double quotes and unescaped single quotes inside the attribute values themselves. Plus I'd rather not spend the time writing and debugging such a util if one already exists.
Thanks
Alastair

A: I don't think you're going to find an off-the-shelf serializer that does this. My suggestion (if you can't persuade your business partner to adopt XML standards) would be to find an open-source serializer (e.g. the Saxon one) and customize it.


text:
Q: How to get list of child nodes? Below, I have attached an image with some console output. What I would like to do is, grab all the numbered nodes (so, 0 and 1, but there could be more or less), and put them into an array (like [0, 1]).
Is this possible?

A: Use .toArray().
var listOfNodes = $list.toArray();

EDIT: As was pointed out by SterlingArcher, there's a better option in ES6 in the form of Array.from.
var listOfNodes = Array.from($list);

A: You can use a simple for-loop
To go through these arrays just don't use forEach, with that you will go through every property but you want the numbers only
Jquery uses a combination of arrays and associative array (objects in Javascript)
So it has auto incremented keys and words as keys


text:
Q: A question about the differentiability conditions for a fractional power Now consider the fractional power $$f(x)=z^{m/n}=|z|^{m/n}(\cos \frac{mArgz}{n}+i \sin \frac{mArgz}{n})$$
Since $f(x)$ satisfies the Cauchy-Riemann equations, and is therefore differentiable, we can obtain its derivative as follows
$$ f'(z)=\frac {m}{n}r^{m/n}\left(\cos \frac{m
Arg z}{n}+\sin \frac{mArgz}{n}\right)\frac {1}{z}= \frac {m}{n} \frac {f(z)}{z}   $$
if we confine $f(x)$ as a single-valued function.
Please tell me why the condition $z \neq 0$ can be dropped in the calculation of $f'(z)$ if $m/n$ is a nonnegative integer.


text:
Q: Is it right to combine past and present in the same sentence? I am defining an instrument but am not sure if it is correct to combine past and present tense at the same time:

Ssdd is the first ever instrument, launched in 1998, which was
  specifically
       designed to measure the gmn at Ka-band at global scale.

Is the usage of is and was correct?

A: No, it's not right to mix tenses. The sentence is in any case somewhat muddled. I would reword it thus:

Ssdd, launched in 1998, was the first instrument specifically designed to measure the GMN, at Ka-band, at the global scale.


text:
Q: Specify font size of javascript alert box message I have to show the message on alert box with font size - 6. I have done like below.
     var str = "Formatting some text.";
     str = str.fontsize("6").fontcolor("#006400").bold();
     alert(str);

But the output get as
Formatting some text.
Please help to correct the issue

A: I think No as per my knowledge as this is controlled by the browser
You would have to use a JavaScript based dialog windows alternative like jQuery UI Dialog.
there is another alternative to jQuery UI Dialog box is sweetalert

A: It is possible to set bold text at alert()

alert("  .")

jsfiddle http://jsfiddle.net/7YgLB/10/

A: Use this code. It will help
HTML

Formatting some text.

JavaScript
$( function() {
  $( "#Custom_Alert" ).dialog();
} );


text:
Q: what is the use off adding ResponseHandler hi what is the exact use of adding ResponseHandler, have a look at my code once
 ResponseHandler<String> responseHandler = new BasicResponseHandler();
          SetServerString = Client.execute(httpget, responseHandler);

may be it check response code like 200,400.. if so what they do for each resonse code thanks in advance

A: ResponseHandler does not return status code, but it returns response body as string if response status code is around 2xx, in case your response status code is >= 300 HttpResponseException is thrown


text:
Q: How to find the dihedral angle of shapes in higher dimensions? The dihedral angle of a tetrahedron (e.g side length of 1) is quite straightforward, splitting up into smaller triangles and eventually using simple trigonometry, we get 70.5 degrees. However, whilst searching for a similar method for the 5-cell (4 dimensional analogue of a tetrahedron), the calculations relied on:
$arccos$ ($d^{-1}$), where d is the dimension of the shape.
For example for the tetrahedron, we get $arccos$ ($3^{-1}$) which of course is 70.5 degrees. This only works with the simplex series. Where does this formula come from ?
How do we go about calculating the dihedralangles of 4d shapes (let's focus on just regular polytopes, and preferably avoid using vectors)

A: For a regular simplex in $d-$space, look at the centroid $G$ of an arbitrary $d-2$ face $s_{d-2}$. Furthermore, there is a pair of vertices, call them $V_i$ and $V_j$, which are from the total $d$ simplex, but not from the $d-2$ face $s_{d-2}$
(they are what's left of the vertices of the $d$ simplex when you remove all the vertices of the $d-2$ face $s_{n-2}$). This centroid is the center of the $d-2$ face $s_{d-2}$, which itself is a $d-2$ regular simplex obtained as the intersection of
the pair of adjacent $d-1$ regular simplicial faces $V_i\,s_{d-2}$ and $V_j\,s_{d-2}$ of the $d$ simplex. Because
the $d$ simplex is regular, all of its faces are also regular simplices of various dimensions.
Hence, each segment $A_iG$ and $A_jG$ is perpendicular to the
$d-2$ affine subspace spanned by the $d-2$ simplex $s_{d-2}$. Moreover, these two segments are equal in length, i.e.
$V_iG = V_jG = h_{d-1}$ because they are the heights of two congruent regular simplices of dimension $d-1$, namely $V_is_{d-2}$ and $V_js_{d-2}$.
Therefore, the triangle $V_iV_jG$ is isosceles, where $V_iG = V_jG = h_{d-1}$ and $V_iV_j=1$.
The dihedral angle you are interested in is then $$\angle \, V_iGV_j \, = \, \theta$$

If you denote by $G_i$ and $G_j$ the centroids (centers) of the $d-1$ simplices
$V_i  \, s_{d-2}$ and $V_j\,s_{d-2}$ respectively, then $G_i \in V_iG$ and $G_j \in V_jG$, as well as
$V_iG_j \, \perp \, V_jG$ and $V_jG_i \, \perp \, V_iG$.
The segments $V_iG_j$ and $V_jG_i$ are congruent heights in the
isosceles triangle $V_iV_jG$ and the triangle $V_iG_jG$ is right-angled, so
$$\cos(\theta) \, =\, \cos(\angle \, V_iGV_j) \, =\, \cos(\angle \, V_iGG_j) \, =\, \frac{G_jG}{V_iG}$$
and by the reflection symmetry of the isosceles triangle $V_iV_jG$, the two segments $G_iG = G_jG$ so
$$\cos(\theta) \,  =\, \frac{G_iG}{V_iG}$$
Observe that in the latter equality, $V_iG$ is the height of the regular $d-1$ simplex $V_i\,s_{d-2}$ that connects the vertex $V_i$ with the center $G$ of the
opposing regular $d-2$ simplex $s_{d-2}$. Moreover, the point $G_i$ is the center of the $d-1$ simplex $V_i \, s_{d-2}$.
Now everything boils down to calculating the ratio in which the center $G_i$ of a regular $d-1$ simplex $V_i\,s_{d-2}$ splits the height $V_iG$ connecting $V_i$
with the center of the regular $d-2$ simplex $s_{d-2}$:
We will do this by showing how it works in one dimension higher ($d-1$ regular face of a $d$ regular simplex, instead of the current $d-2$ regular face of a $d-1$ regular simplex)
and use it as an induction step
in $d$, calculating the ratio in which the center $G_d$ of the total regular simplex $s_{d}$ splits the height $V_iG_j$. In the current notations,
$G_d = V_iG_j \, \cap \, V_jG_i$. The triangles $V_iG_iG_d$ and $V_iG_jG$ are right-angled and similar, so
$$\frac{G_jG}{V_iG} = \frac{G_iG_d}{V_iG_d} = \cos(\theta)$$
But by the fact that the traigle $V_iV_jG$ is isosceles, $$G_jG = G_iG \,\,\,\, \text{ and } \,\,\,\, G_iG_d = G_jG_d$$
which yields the ratio
$$\frac{G_iG}{V_iG} = \frac{G_jG_d}{V_iG_d} = \cos(\theta)$$
Let me flip it
$$\frac{V_iG_d}{G_dG_j} = \frac{V_iG}{GG_i} = \frac{1}{\cos(\theta)}$$
I claim that $$\frac{V_iG_d}{G_dG_j} = d$$
The ratio $\frac{V_iG}{GG_i}$ is a ratio that comes from the analogous situation one dimension lower, i.e.
the position of the canter $G_i$ of the $d-1$ regular simplex
$V_i \, s_{d-2}$ on the height $V_iG$ of this same simplex. If, by induction, we assume that it has been shown that
$$\frac{V_iG_i}{G_iG} = d-1$$ then $$\frac{V_iG}{GG_i} = \frac{V_iG_i + G_iG}{G_iG} = \frac{V_iG_i}{G_iG} + 1 = d - 1 + 1 = d$$
Hence
$$\frac{V_iG_d}{G_dG_j} = \frac{V_iG}{GG_i} = d = \frac{1}{\cos(\theta)}$$ and there you have that
$$\cos(\theta) = \frac{1}{d}$$ and consequently the dihedral angle you are after is
$$\theta = \arccos\left(\frac{1}{d}\right)$$
The beginning of the inductive step can start with $d=2$, in which case we have that we have an equilateral triangle, where the ratio is known to be $\frac{1}{2}$.


text:
Q: How to avoid asynchronous nature of scrollToVisibleRect causing intermittent timing issues I am writing a Cocoa UI and am calling NSView's scrollRectToVisible repeatedly in a short space of time as a result of the user holding down a certain key (and hence repeatedly firing events on the main queue).
Through logging I can see that successive keyDown() events are firing prior to the scrollRectToVisible having completed its prior changing of the visibleRect. This is resulting in the subsequent scrollRectToVisible being called with incorrect inputs (namely the wrong starting visibleRect) and is leading to non-sensical UI behaviour. This happens about 50% of the time which I guess is to be expected dealing with an asynchronous problem.
How can I address this?
One way I can think of is by somehow turning scrollRectToVisible into a synchronous call. The problem is that it is an AppKit API and the method returns immediately with a boolean indicating whether it is going to scroll or not.

A: Try putting the code in the view that responds to the -keyDown:.
This example controls the scrolling with a timer instead of the repeated keyDowns from holding the key.
I couldn't get the UI unwanted behavior, so I don't know if this will help.
- (BOOL)acceptsFirstResponder {
    return YES;
}
- (BOOL)canBecomeKeyView {
    return YES;
}
- (void)keyDown:(NSEvent *)theEvent {
    if (timer == nil) {
        timer = [NSTimer scheduledTimerWithTimeInterval:0.01
                                                 target:self
                                               selector:@selector(doScroll:)
                                               userInfo:nil
                                                repeats:YES];
    }
    NSLog(@"event %@ with Timer%@", theEvent, timer);
}
- (void)keyUp:(NSEvent *)theEvent {
    [timer invalidate];
    timer = nil;
    NSLog(@"keyUp timer:%@", timer);
    NSLog(@"event %@", theEvent);
}
- (void)doScroll:theTimer {
    NSEvent * current = [NSApp currentEvent]; //use this to parse
    NSLog(@"current press %@", current);
    [self scrollRectToVisible:NSMakeRect(self.visibleRect.origin.x + 10,
                                         self.visibleRect.origin.y + 10,
                                         self.bounds.size.width,
                                         self.bounds.size.height)];
}


text:
Q: How to resolve error while trying to publish 2013 workflow via designer. Probably a workflow manager backend user account issue? I am getting error while publishing the 2013 workflow via designer. Also, under sharepoint designer if I try to delete any workflow then the page just refreshes and the workflow does not get deleted.
I checked the services.msc and found that the workflow backend service was stopped. (this happened as the password of the user under which this serivce was running had changed).
So, the network admin changed the service user to LOCAL SYSTEM and started the service.
Now, the workflow backend service is started. We have also ran the iisreset.
However, I am still getting the same error:-
System.IO.InvalidDataException: A response was returned that did not come from the Workflow Manager. Status code = 503: Service Unavailable
Service Unavailable
HTTP Error 503. The service is unavailable.
Client ActivityId : ee94689c-4e08-b055-fe9c-268d7a94
Please find attached snapshot.
Is the error as a result of the change in service user? Can you tell me what priviledges should the account running the workflow backend service must have?

UPDATE 1
We have tried to set the account to farm admin and also tried to set it to site admin. Now, for a new web application, I can delete workflows. However, for existing site, I am  not able to delete the existing workflows.. Also, I am not able to publish workflows (present under new and previous sites) and the error is same as described earlier.

A: Open IIS and make sure identify of the WorkflowMgmtPool is correct, you can re-type the identify. Then  make this pool is started.
Check and reenter credentials for:-
Open Services.msc, find Service Bus Message Broker service and Windows Fabric Host Service. Make sure they are running. If not, firstly, start Windows Fabric Host Service, then start Service Bus Message Broker service. If Service Bus Message Broker service is started, stop and re-start it.
Reference- this forum link

A: This error occur because you have not registered the workflow correctly. Re-register the workflow and it will get solved. Also make sure you have activated the App management Service in your site features.
http://designerworkflow.blogspot.in/

A: Workflow Manager CU2 to get to 1.0 Refresh in Web Platform installer worked first time for me!
http://support.microsoft.com/kb/2902007/en-us

A: I had this same issue.
I was able to resolve it by going to IIS on my application server, editing the identity on the Workflow Management Application Pool, saving it and restarting it. I also restarted the server.


text:
Q: How is one register file enough? Let's say I'm writing some code in assembly or even in a higher level language, and I compile and run it on a linux OS.
To my best understanding, when my program is running, it uses the CPU 8-array register file, while each array is 32-bit long.
So, my program runs - and can (and does) gain access to each of these 32-bit arrays.
Now my question is this:
How is it, that my computer, and the CPU in particular, can afford to dedicate such an expensive resource - its entire SRAM cache memory, no less - to one simple C/C++ program, while surely, it has much more important things to do with it, and much more extensive, demanding processes to run on background?
I'd expect that my simple C/C++ program will get a nice slice from the RAM to run on.

A: If there are 2 tasks that both want to use the CPU, and only one CPU in the machine, then one of them will be running and the other one will be waiting. Once in a while, a timer interrupt arrives, causing the CPU to stop running the currently active job and jump to the kernel's interrupt handler.
The kernel might decide to resume the current task, or to give the other one a chance. If neither one voluntarily yields the CPU (to wait for data from disk or network for example) then the kernel will switch back and forth between them a few times per second.
The decision of exactly when to switch tasks is a delicate balance: allowing a single process to monopolize the CPU for a long time makes other processes seem non-responsive, but switching too often would make CPU caches less effective (after a switch the cache contents left behind by the old process are not likely to be useful to the new process).
So from the CPU's point of view, there's no such thing as "running in the background". There's just one running task, and everything else is just data sitting in memory waiting to be used.
Your idea of processes getting a "slice" of the CPU is not completely wrong - you're just slicing in the wrong dimension. Processes don't get slices of the register file; they get the whole CPU for slices of time. They're called timeslices.

A: You need to draw a distinction between registers and caches (and all kinds of other things involved in modern multitasking machines):

*

*Register file is indeed exclusively allocated to your program for a duration of a scheduler time slot. However, it's not such a big deal to reload it in full on a context switch - after all, you may end up reloading the whole register file on a simple function call (if your function has plenty of local variables).

*Cache is more complicated. First, it is very dependent on a particular CPU implementation - simpler/older CPUs can indeed flush the cache on a context switch, but no modern higher end CPU will do this. If cache is "physically mapped" (cache address tags correspond to physical memory locations and virtual address translation happens before cache access) then neither CPU nor OS have to do anything special on context switch. "Logically mapped" caches (the ones which use virtual addresses to tag the cache lines, so as to reduce the cache access latency a bit) will often feature additional "task tags" on each line. The OS, on context switch, will set some value to "task id" register which will be used by cache hardware to establish, whether whatever line belongs to the currently running process or should be replaced.


text:
Q: Download pdf and image files with php instead of displaying them on your desktop I have created a script that works only with some files and I would like to improve it.
In practice, this PHP script saves the uploaded file on the server disk and the file name in a mySQL database.
When I press on the download button, the script saves the name of the file into $filenameso when I use the code shown below, I'm able to download the file:
header ("Location: http://". $ _SERVER ['SERVER_NAME']. "/ FILE_DOWNLOAD /". $ filename);

The problem is that if the file is an image or a PDF and I try to open it from my browser, it opens the file instead of downloading it to my desktop.
I've looked for a solution on many forums but have had no success.
Here's an alternative that is very close to what I'm looking for:
$files_folder = $_SERVER['DOCUMENT_ROOT']. "/file_download/";
    if (is_file($files_folder.$filename))
    {
        $spliturl = explode (".", $filename);
        $file_extension = $spliturl[sizeof($spliturl)-1];
        switch(strtolower($file_extension)) {
              case "pdf": $ctype="application/pdf"; break;
              case "png": $ctype="image/png"; break;
              case "jpeg": $ctype="image/jpeg"; break;
              case "jpg": $ctype="image/jpeg"; break;
              default: $ctype = false; break;
        }
        if($ctype) {
            header("Content-Type: $ctype");
            header("Content-Disposition: $disposition; filename=".$filename);
            header("Content-Description: Download ");
            echo file_get_contents($files_folder.$filename);
        }echo "Error extension!";
    }else echo "The file does not exist!";

A: use .htaccess or PHP headers. Since i have to still allow show file in browser, but download same file on button click, i used this php code:
if(isset($_GET['file'])){
    $path = "uploads/" . $_GET['file'];
    $filename = $_GET['file'];

    if(file_exists($path)) {
        header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
        header('Accept-Ranges: bytes');  // For download resume
        header('Content-Length: ' . filesize($path));  // File size
        header('Content-Encoding: none');
        header('Content-Type: application/pdf');  // Change this mime type if the file is not PDF
        header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
        readfile($path);  //this is necessary in order to get it to actually download the file, otherwise it will be 0Kb
    } else {
        echo "File not found on server";
    }
}else{
    echo "No file to download";
}

And calling this script:
www.example.com/downloadFile.php?file=someFile.pdf


text:
Q: Comparing a class to None I have a supposedly simple situation where I am trying to sort a list that contains a mix of class instances, and None. I've implemented the lt method of the class, but I'm still getting an error:
TypeError: '<' not supported between instances of 'NoneType' and 'test_class

Here's how I'm currently doing it:
class test_class:
    def __init__(self, num):
        self.num = num

    def __lt__(self, other):
        if other is None:
            return False
        else:
            return self.num < other.num

    def __eq__(self, other):
        if other is None:
            return False
        else:
            return self.num == other.num

tc1 = test_class(1)
tc2 = test_class(2)

sorted([tc1, tc2, None])

... which produces the above-mentioned error. Could anyone kindly point out what I'm doing wrong? In some sort of idealized reality where programming languages work in a common-sense way, I would have thought that the 'if other is None' bit should handle a comparison with None.
Thanks in advance!

A: Note that your error is not
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'test_class' and 'NoneType'

but instead
...between instances of 'NoneType' and 'test_class'

The ordering matters. None does not implement a __lt__ method that knows how to compare to a test_class. However Python is smart enough to use the other class's __gt__ in this case.
class TestClass(object):
    def __init__(self, num):
        self.num = num

    def __lt__(self, other):
        if other is None:
            return False
        else:
            return self.num < other.num

    def __gt__(self, other):
        if other is None:
            return True
        return self.num > other.num

    def __eq__(self, other):
        if other is None:
            return False
        else:
            return self.num == other.num

What's more, functools.total_ordering can be used to decorate your class so you only have to define __eq__ and one of __lt__, __le__, __gt__, __ge__ and the rest will be auto generated for you.
import functools

@functools.total_ordering
class TestClass(object):
    def __init__(self, num):
        self.num = num

    def __lt__(self, other):
        if other is None: return False
        return self.num < other.num

    def __eq__(self, other):
        return isinstance(other, type(self)) and self.num == other.num
        # I refactored this to be a little nicer

Now TestClass() acts as if __gt__, __ge__, and __le__ are all defined, even though you only have to define one.