text:
Q: recursion: cut array of integers in two parts of equal sum - in a single pass Using recursion, find an index that cuts an array in two parts so that both parts have equal sum.
Cut means to cut like with a knife. All the cells with index <= to the result must be equal in their sum to the all the cells with index > to the result. No cells can be left off or be part of both sides.
The arrays contains arbitrary integers (i.e. positives, negatives, and zeros).
If there is no such index return -1.
You are not allowed to allocate heap objects.
You must do it in a single pass.
You must do it with recursion (i.e. cannot use loop constructs).
Can be in any language or pseudocode.
Forgot to add this: You cannot modify the array

A: Here's a way to do it that takes advantage of Ruby's ability to return multiple values.  The first value is the index for the split (if it exists), the second is the sum of each half (or the sum of the whole array if no split is found):
def split(arr, index = 0, sum = 0)
  return -1, arr[index] if index == arr.length - 1
  sum = sum + arr[index]
  i, tail = split(arr, index + 1, sum)

  if i > -1
    return i, tail
  elsif sum == tail
    return index, sum
  end
  return -1, arr[index] + tail
end

Calling it like this:
p split([1, 1, 2])
p split([1])
p split([-1, 2, 1])
p split([2, 3, 4])
p split([0, 5, 4, -9])

Results in this:
[1, 2]
[-1, 1]
[1, 1]
[-1, 9]
[0, 0]

EDIT:

Here's a slightly modified version to address onebyone.livejournal.com's comments.  Now each index in the array is accessed only once:
def split(arr, index = 0, sum = 0)
  curr = arr[index]
  return -1, curr if index == arr.length - 1
  sum = sum + curr
  i, tail = split(arr, index + 1, sum)

  if i > -1
    return i, tail
  elsif sum == tail
    return index, sum
  end
  return -1, curr + tail
end

A: Iterating with recursion is a trivial transformation, so we'll assume you know how to do that.
If you use your "one pass" to build your own array of "sum to this index", and can make another pass on that array, I could see how to do it. Just iterate through that second array and subtract sum[x] from sum[last]. If you ever find a situation where the result = sum[x] you return x. If you don't then return -1.
As Neil N mentioned, if you define "pass" very loosely for recursion, such that the entire recursion can actually visit indices multiple times, then you could dispense with the second array.

After thinking about this a bit, I suspect the idea is to get you to only visit every array element once (in order), and to use recursion's built-in stack property to get rid of the need for any second array.
What you do is write your recursive routine to save off it's current index's array value in a local, add that value to a passed in "sum_of_array" value, then call itself on the next highest index (if there is one). If there isn't a next highest index, it saves the sum into a global, which is now available to every stacked recursive call. Each routine finishes by checking its sum against the global sum. If it is half, then it returns its index. Otherwise it returns -1. If a non -1 was returned from a call to itself, this last step is skipped and that value is returned. I'll show in pseudo-Ada
Total_Sum : integer;

function Split (Subject : Integer_Array; After : Integer := 0; Running_Sum : Integer := 0) is
begin
   Running_Sum := Running_Sum + Subject(After);
   if (After < Subject'last) then --'// comment Hack for SO colorizer
      Magic_Index : constant Integer := Split (Subject, After +  1, Running_Sum);
      if (Magic_Index = -1) then
         if (Total_Sum - Running_Sum = Running_Sum) then
            return After;
         else
            return -1;
         end if;
      else
         return Magic_Index;
      end if;
   else
      Total_Sum := Running_Sum;
      return -1;
   end if;
end Split;

This code should have the properties that:

*

*Calling it with just an array will return the described "split" index, or -1 if there isn't one.

*It only reads from any element in the source array once

*It reads the source array elements in strict index order.

*No extra structured data storage (array) is required.

A: public static Int32 SplitIndex(Int32[] array, Int32 left, Int32 right, Int32 leftsum, Int32 rightsum)
{
    if (left == right - 1)
    {
        return (leftsum == rightsum) ? left : -1;
    }

    if (leftsum > rightsum)
    {
        return SplitIndex(array, left, right - 1, leftsum, rightsum + array[right - 1]);
    }
    else
    {
        return SplitIndex(array, left + 1, right, leftsum + array[left + 1], rightsum);
    }
}

The method is called as follows.
Int32[] a = { 1, 2, 3, 1, 6, 1 };

Console.WriteLine(SplitIndex(a, -1, a.Length, 0, 0));

This can be reduced to use only a single sum and targeting zero.
public static Int32 SplitIndex(Int32[] array, Int32 left, Int32 right, Int32 sum)
{
    if (left == right - 1)
    {
        return (sum == 0) ? left : -1;
    }

    if (sum > 0)
    {
        return SplitIndex(array, left, right - 1, sum - array[right - 1]);
    }
    else
    {
        return SplitIndex(array, left + 1, right, sum + array[left + 1]);
    }
}

The method is now called as follows.
Int32[] a = { 1, 2, 3, 1, 6, 1 };

Console.WriteLine(SplitIndex(a, -1, a.Length, 0));

A: Take a look at the following, using only 1 index, assume array's indexes are 1-based:
int recursion(index, rightvalue, leftvalue, array)
{
if array=[] then
{
    if rightvalue=leftvalue then return index
    else return -1
}
else
{
    if rightvalue <= leftvalue
    { recursion(index+1, rightvalue+array[1], leftvalue, array[2..len(array)] }
    else
    { recursion(index, rightvalue, leftvalue+array[len(array)], array[1..len(array)-1] }
}

int main_function(array)
{
    return recursion(1, 0, 0, array)
}

A: My version:
# Returns either (right sum from the currentIndex, currentIndex, False),
# or, if the winning cut is found, (sum from the cut, its index, True)
def tryCut(anArray, currentIndex, currentLeftSum):
   if currentIndex == len(anArray):
      return (0, currentIndex, currentLeftSum==0)

   (nextRightSum, anIndex, isItTheWinner) = tryCut(anArray, currentIndex + 1, currentLeftSum + anArray[currentIndex])

   if isItTheWinner: return (nextRightSum, anIndex, isItTheWinner)
   rightSum = anArray[currentIndex] + nextRightSum
   return (rightSum, currentIndex, currentLeftSum == rightSum)

def findCut(anArray):
   (dummy, anIndex, isItTheWinner) = tryCut(anArray, 0, 0)
   if isItTheWinner: return anIndex
   return -1

Note: if the index returned is 5, I mean that sum(anArray[:5]) == sum(anArray[5:]). The "extremes" are also valid (where the sum of an empty slice is meant to be zero), i.e. if the sum of the whole array is zero, then 0 and len(anArray) are also valid cuts.

A: Here's an implementation in Erlang, since I'm learning it and this seemed like an interesting challenge. Idea shamelessly cribbed from Pesto's solution.
find_split(List) -> {Idx, _Sum} = find_split(List, 1, 0), Idx.
find_split([Head], _Idx, _Sum) -> {-1, Head};
find_split([Head|Tail], Idx, Sum) ->
  case find_split(Tail, Idx + 1, Sum + Head) of
    {-1, Tailsum} when Sum + Head == Tailsum -> {Idx, Sum + Head};
    {-1, Tailsum} -> {-1, Head + Tailsum};
    Ret -> Ret
  end.

A: Haskell:
split' _ s [] = (-1, s)
split' idx s (x:xs) | sidx >= 0   = (sidx, s')
                    | s * 2 == s' = (idx - 1, s)
                    | otherwise   = (-1, s')
    where (sidx, s') = split' (idx + 1) (x + s) xs

split = fst . split' 0 0

Your rules are somewhat misleading. You require that no objects are to be allocated on the heap, but IMHO there is no solution where the algorithm does not have space requirements of O(n), i.e. the stack grows linearly with the length of the list and tail calls are not possible because the function has to inspect the return values from the recursive call.

A: Code in C/C++/Java:
function cut(int i, int j, int s1, int s2, int a[])
{
    if(i==j && s1==s2)
        return i;
    else if(i==j && s1!=s2)
        return -1;
    else if(s1>s2)
        return cut(i, j-1, s1, s2 + a[j-1]);
    else
        return cut(i+1, j, s1 + a[i+1], s2);
}

Call using the following syntax:
cut(0, array.length, 0, 0, array);


text:
Q: Looping array of object into array of object javascript so i have two arrays of object like this:
var lab =[
  { label: '1', value: 42 },
  { label: '2', value: 55 },
  { label: '3', value: 51 },
  { label: '4', value: 22 }
  ];

var val = [ { label: '1', value: 42 },
  { label: '2', value: 55 },
   ];

lab.forEach(labs=>{
    val.forEach(vals=>{
        labs["columns"]=vals.value
    })
})
console.log(lab)

i try to get the value like this
[ { label: '1', value: 42, columns: {42,55} },
  { label: '2', value: 55, columns:{42,55} },
  { label: '3', value: 51, columns: {42,55} },
  { label: '4', value: 22, columns: {42,55} } ]

but after i ran the code i get the value that i am not wanted like this:
[ { label: '1', value: 42, columns: 55 },
  { label: '2', value: 55, columns: 55 },
  { label: '3', value: 51, columns: 55 },
  { label: '4', value: 22, columns: 55 } ]

where do i did wrong actually on the loop..

A: Does this do what you want?

const lab = [
  { label: '1', value: 42 },
  { label: '2', value: 55 },
  { label: '3', value: 51 },
  { label: '4', value: 22 },
];
const val = [
  { label: '1', value: 42 },
  { label: '2', value: 55 },
];

// we get an array of stuff that the OP wants to add,
// as apparently it is identical for each object.
const columns = val.map(obj => obj.value);

const a = lab.map(labs => {
  return {
    // shallow copys for every item.
    ...labs,
    columns: [...columns],
  };
});

console.log({ a });
.as-console-wrapper { min-height: 100%!important; top: 0; }

map array method takes a function returns a new array where each element was updated by calling that function with element as it's argument.
This answer uses two calls of map, same amount as your answer, however in your answer map calls are nested, so the inner map would be called for each element, while it's result will be always the same, in my answer we call it once.

A: i have figured it out by using map function
var lab =[
  { label: '1', value: 42 },
  { label: '2', value: 55 },
  { label: '3', value: 51 },
  { label: '4', value: 22 }
  ];

var val = [ { label: '1', value: 10 },
  { label: '2', value: 55 },
   ];

const a = lab.map((labs)=>{
    let ab={
        label:labs.label,
        value:labs.value,
        columns:val.map((vals)=>{
        return vals.value
    })
    }
    return ab

})
console.log(a)

hope it will help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Give an example of a measurable space Give an example of a measurable space (Ω,F) and a function X: Ω → R such that X^2 : ω  → X2(ω) is F-B(R)-measurable whereas X is not?

A: Hint: a characteristic function (i.e. the indicator function) of a set $A$ is measurable iff $A$ is measurable. Take a non-$F$-measurable set (so, $F$ should not be the whole $2^{\Omega}$) and modify (affinely) its characteristic function to take values $-1$ and $1$. Then a square is $1$, so it is measurable as a constant function, while the original function is not measurable.


text:
Q: Summing the first $n$-terms of the series whose general term is $nx^{n-1}$ I suppose several of you know some fancy ways to establish the formula for the sum of the first $n$ terms of the geometric series $$1+x+x^{2}+x^{3}+ \ldots $$
Can you share below some of your fave ways to sum the first $n$ terms of the series
$$ 1 + 2x+ 3x^{2} + \ldots $$
Naturally,  for $x \neq 1$, one way to attain the goal is to take the derivative of both sides of $$\sum_{k=0}^{n-1} x^{k} = \frac{x^{n}-1}{x-1}.$$
Another possibility is to apply something that the authors of certain handbook of discrete and  combinatorial math called "the perturbation method": if $S(n):= \sum_{k=1}^{n} kx^{k-1}$, then
$$ S(n) + (n+1)x^{n} = 1 + \sum_{k=2}^{n+1} kx^{k-1}$$
which can be rewritten as
$$ S(n) + (n+1)x^{n} = 1 + \sum_{k=1}^{n}(k+1)x^{k}.$$
Thus,
$$ (1-x)S(n) = \frac{x(x^{n}-1)}{x-1} + 1 - (n+1)x^{n}$$
or
$$S(n) = \frac{nx^{n+1}-(n+1)x^{n}+1}{(x-1)^{2}}.$$
What other cool ways to sum $1+2x+ \cdots + nx^{n-1}$ do you know or have heard of? Have you ever seen a "proof without words" of the result in question?
Thanks in advance for your attention.

A: $1 + 2x + 3x^2 + \cdots + nx^{n-1}$
= $1 + x + x^2 + \cdots + x^{n-1} $
$+ x + x^2 + \cdots + x^{n-1} $
$+ x^2 + \cdots + x^{n-1} $
$+ \cdots + x^{n-1}$
$= \dfrac{x^n-1}{x-1}$
$+\dfrac{x^n-x}{x-1}$
$+\dfrac{x^n-x^2}{x-1}$
$+\cdots + \dfrac{x^{n}-x^{n-1}}{x-1}$
$=\dfrac{nx^n-(1+x+x^2+\cdots+x^{n-1})}{x-1}$
$=\dfrac{nx^n-\dfrac{x^n-1}{x-1}}{x-1}$


text:
Q: PostgreSQL performance tuning under heavy load My Server has following resources :
[postgres@srv2813 ~]$ free -m
             total       used       free     shared    buffers     cached
Mem:         15929      15118        810        142         12        219
-/+ buffers/cache:      14885       1043
Swap:         8031       2007       6024

[postgres@srv2813 ~]$ cat /proc/cpuinfo | grep processor | wc -l
    8

[root@srv2813 postgres]# sysctl kernel.shmall
kernel.shmall = 4194304
[root@srv2813 postgres]# sysctl kernel.shmmax
kernel.shmmax = 17179869184

and My PostgreSQL conf :
default_statistics_target = 100
maintenance_work_mem = 1GB
checkpoint_completion_target = 0.9
effective_cache_size = 12GB
work_mem = 32MB
wal_buffers = 16MB
shared_buffers = 3840MB
max_connections = 500
fsync = off
temp_buffers=32MB

But its getting "too many connection" error. The nginx_status page of the webserver shows around 500 active connections when this happens. The server hosts an api severver, so every "http request" invariably initiate a database "read". Its not a "write" heavy thing, but very "read" heavy.
Its possible that i maxed out our sever, but still i expected a little more from a 16G/8 core box considering the "read only" nature of the application. Can i push the PostgreSQL in any other possible direction?

A: PostgreSQL is process based vs thread based so it does not generally work well with a lot of connections.
I would look at using something like PgBouncer. PgBouncer is a lightweight connection pooler for PostgreSQL.


text:
Q: How to see benefit effect of BJT current mirror in the load? I don't arrive to see benefit effect of BJT current mirror in the load.
I would get twice ic (ic1+ic2 = 3mA) with the same sources (both with phasing =0). But here I(RL) = -29µA.

link
Origin diagram :

The VB(Q3)-REF1 is 0V :

The VB(Q3)-REF1 is 52mV with V1 180° phasing :

Replacing with RC


text:
Q: Unable to build release APK when using ProGuard I have an Android project created in Eclipse with ADT bundle. I want to export a release APK using ProGuard but keep getting errors.
I know this has to do with the Google Play Services library because when I remove it from the project it exports the APK successfully.
The project.properties looks like this:
proguard.config=proguard-android.cfg
target=android-17
android.library.reference.1=../google-play-services_lib

The proguard-android.cfg looks like this:
-libraryjars  <java.home>/lib/rt.jar
-printmapping proguard-android.map
-dontwarn
-dontoptimize
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**

I have added the keep class definition because when I run it I get the following errors:
Proguard returned with error code 1. See console.

[2019-10-09 06:34:32 - AndroidApp] Proguard returned with error code 1. See console
[2019-10-09 06:34:32 - AndroidApp] Note: there were 1030 duplicate class definitions.
[2019-10-09 06:34:32 - AndroidApp]       You should check if you need to specify additional program jars.
[2019-10-09 06:34:32 - AndroidApp] Unexpected error while performing partial evaluation:
[2019-10-09 06:34:32 - AndroidApp]   Class       = [com/google/android/gms/d/f]
[2019-10-09 06:34:32 - AndroidApp]   Method      = [a(ILandroid/app/Activity;Landroid/support/v4/app/Fragment;ILandroid/content/DialogInterface$OnCancelListener;)Z]
[2019-10-09 06:34:32 - AndroidApp]   Exception   = [java.lang.IllegalArgumentException] (Can't find any super classes of [com/google/android/gms/d/g] (not even immediate super class [android/support/v4/app/DialogFragment]))

Can anyone give me any help as to what the errors mean and how to get it working?


text:
Q: Setting size on JLabel displaces other components in java I am setting a JLabel for the error messages in my program, so initially the label is empty label.setText(""), but when there is an error it should change to something like label.setText("Error, you have entered invalid data...").
If I use setSize(x,y) on the label, it forces other components to displace when error message takes place. But using setPreferredSize(Dimension(x,y))doesn't impact them.
Q1. Why is that?
Q2. What is the difference between setSize(x,y) and setPreferredSize(Dimension(x,y))
Q3. Does it have to do anything with layout?
Thank you in advance for explanation!
P.S. I am using GridBagLayout for positioning my components on the JPanel.

A: Don't use the setSize method.
setSize is called by LayoutManagers, like GridBagLayout, to lay out child components.  When you call setSize explicitly, you are fighting with the GridBagLayout.  Eventually, GridBagLayout will undo your setSize call, when it calls setSize for its own purposes.
In other words, any call to setSize eventually will be wiped out by the parent layout.
setPreferredSize will not be wiped out.  Most LayoutManagers, including GridBagLayout, do their best to respect a component's preferred size.
However, you should not be calling setPreferredSize.  Components already have a preferred size by default, and it is almost certainly better than any numbers you can come up with.  For instance, a JLabel's default preferred size is the size which is just large enough to accommodate its text, icon, and borders.
Computing a preferred size is harder than you might think.  How many pixels does text use?  How many pixels high is a 12 point font?  12 points is not 12 pixels.  12 points is 12⁄72 inch.  How many pixels is that?  It depends on the user's monitor and graphics resolution.  All of this is known to the Swing rendering system, and JLabel uses all of that information to determine its default preferred size.  You should not try to reinvent all of that work, and you should not try to replace that work with something simpler, as it will be inadequate.
If you just let the JLabel keep its preferred size, GridBagLayout will do its best to accommodate that.  If the window itself does not have room to display the JLabel's new text, you probably should call the window's pack() method after changing the text.
Update: This appears to be an XY problem—you really want a message that you can show and hide.
You want your layout to be big enough to accommodate your message text as soon as you create it.  This is typically done with a CardLayout, which lets you place several components on top of each other, with only one of them visible at any given moment.  Since you want to show no text at all, initially, you would add an empty JLabel as the first component in the CardLayout, so it is shown by default:
JLabel label = new JLabel("Error, you have entered invalid data...");

CardLayout messageLayout = new CardLayout();
JPanel messagePane = new JPanel(messageLayout);
messagePane.add(new JLabel(), "blank");
messagePane.add(label, "message");

// Do not add label directly to your user interface.
// Add messagePane instead.
mainWindow.add(messagePane);

// ...

// Show message
messageLayout.show(messagePane, "message");

// ...

// Hide message
messageLayout.show(messagePane, "blank");

"message" and "blank" are never seen by the user.  They are just unique identifiers for each component ("card") in the CardLayout.  You can make them anything you want.

A: The setSize() function sets the size not based on any LayoutManager. Thats why you should always use setPrefferedSize() when working with a LayoutManager. setPrefferedSize() firstly tries to be conform with the LayoutManagers dimensions if then possible Java tries to set the size of the Label according to your setPrefferedSize() input.
So yes, it does have anything to do with layout. If possible, you should only use setPrefferedSize() as you are working with layout managers.


text:
Q: Maven -Standard i would like to work with Maven after we used ANT.
i have few questions:

*

*As per my understanding it is much easier to work with Maven if i will have a common structure directory layout and therefore i will be able to build this and other project more easily. what is the standard and how you recommend to perform it?

*I have few sub-applications and many modules under each of them .
Assuming our application named A1,A2,A3,A4, and using SVN (from scratch) as our source control. do you recommend putting the name of the application as a prefix in SVN so it will be built easier?
@scm.it.att.com: port \ A1 \ (branches,trunk,tags)\ or without the A1 .// in order to have fluent build with Maven.

*which one are recommended?
@scm.it.att.com:port \<release_name>\branches\module or @scm.it.att.com:<port>\branches\module\<release_name>
in terms of building it with Maven standards. we need to build only a specific module and not the entire repo.

A: thanks for the input, for question 3,clarification-
of course the question is which are a better method-
svn:.../ module_name /branches/release_name
or
svn:.../ branches/ release/ module_name( list of all the modules within the same release) /
at the first option , each module show under his branches what are the releases it was part of and allow to go to that specific source code for a specific release comparing the second module which contains-  under one release,  all the modules  built in that release. and then you can peek one module and see the source code.
the question is : what is the best way to implement&organize it in the SVN in terms of intuitive Maven build?
thanks !!!


text:
Q: pattern matching with same variable I have a doubt about the pattern matching in SML. In the book "Programming Language Pragmatics (Second edition)" I read that in SML when you use the pattern matching in a function, the same variable can not appear more than once. The explanation is that pattern matching is used to check if the function can be found in a defined pattern, and not to check if variables are in relation to each others. But it has confused me: why something like this could not be implemented?
Here is an example:
fun Eq nil = false
| Eq (e) = false
| Eq x::x::resto = true //Error
| Eq x::y::resto = false

This snippet of code check if the first two elements of a list are equal.
So, why the third line of the code is wrong? Thank you.

A: Pattern matching only compares compile-time constants and does simple variable assignment otherwise. You can't do a variable comparison via pattern matching. You need to remove the third line and extend the 4th line to
Eq x::y::resto = x = y

Pattern matching also happens in order. Since Eq e actually matches everything, it should be your final clause.


text:
Q: How to insert layout within another layout at runtime What is the best way to insert a layout inside another layout at runtime.  Specifically I have a FrameLayout that contains a ListView.  This is defined in one mainlayout.xml file, and I have another layout file defining the header in header.xml.
1) How do I include the headerlayout.xml defined layout inside the definition of mainlayout.xml.(static case) ie without copying everything inside but referencing the other definition.
2) How could I dynamically add header layout into specific spot in mainlayout.xml at runtime?
   I know about inflating and all that, just not sure how to attach it to the spot where I want it in the mainlayout. Since I am not including whole definition in mainlayout.xml how to I have a placeholder there and set it dynamically in the right spot after inflation.  (dynamic case).

A: Static case. Inside your mainlayout.xml:
<include layout="@layout/header" id="@+id/header" />

Another solution which ca be both static and dynamic is using ViewStub
<ViewStub android:id="@+id/stub"
          android:inflatedId="@+id/subTree"
          android:layout="@layout/mySubTree"
          android:layout_width="120dip"
          android:layout_height="40dip" />


text:
Q: Is highcharts.js capable of formatting integer timestamps into dates? I am getting series of numbers from server in pairs of date and value. Dates are unix timestamps.
Should I map these timestamps on my own or Highcharts.js can do it for me somehow?
Clarification:
This is not a question about how to show Unix Epoch timestamp with Highcharts. This is a question about possibilities of Highcharts.js to consume correct data in timestamp format and automatically translate it to Date, without any work on my side.

A: Highcharts is a library that servers only to visualize data - not to process it. You have to provide it with the format of timestamp specified in the API (@ewolden provided a link to it in his comment under your question).

A: In Highcharts, you can format the Unix Timestamp this way :
xAxis: {
        type: 'datetime',
        labels: {
            formatter: function() {
                return Highcharts.dateFormat('%a %d %b %H:%M:%S', this.value);
            }
        }
}

Of course, this parameter : '%a %d %b %H:%M:%S' lets choose what part of the datetime you want to display in the axis.


text:
Q: How can I optimise a set of VBA functions that parse String and Variant types How can I optimise these functions? They work but I need it to be much faster.
Actual working (slow):
  Function IsInArray(value As String, arr As Variant) As Boolean
        Dim length As Integer
        Dim found As Boolean

        length = UBound(arr)
        found = False
        i = 0
        While Not found And i < length
            If arr(i) = value Then
                found = True
            End If

            i = i + 1
        Wend
        If found Then
            IsInArray = True
        Else
            IsInArray = False
        End If
    End Function

This gets number of rows in specific list:
Function GetNumberOfRows(list As String) As Integer

    Dim numRows As Integer
    Dim row As Integer
    Dim column As Integer

    row = 2
    column = 2
    numRows = 0

    While (Worksheets(list).Cells(row, column).value <> "")
        numRows = numRows + 1
        row = row + 1
    Wend

    GetNumberOfRows = numRows

End Function

This replace values in a range
Sub ReplaceValue(oldValue As String, newValue As String, list As String)

    Dim numRows, numColumns As Integer
    Dim row, column As Integer

    numRows = GetNumberOfRows(list)
    numColumns = 9

    row = 2
    While row <= numRows + 1

        column = 3
        While column <= numColumns + 3

            If Worksheets(list).Cells(row, column).value = oldValue Then
                Worksheets(list).Cells(row, column).value = newValue
            End If

            column = column + 1
        Wend

        row = row + 1
    Wend
End Sub

P.S.
This is fast but isn't to spec as if I'm searching for "aa", it will say TRUE if "aab" is in array. However it might be instructive to include it here as an example of 'fast'.
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

A: With regard to IsInArray, Filter won't work, but Join works just fine.  This assumes that the accent grave character is not in the array (not a grave concern!):
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    jn = "`" & Join(arr, "`") & "`"
    IsInArray = InStr(1, jn, "`" & stringToBeFound & "`") > 0
End Function

A: For the first one:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Not sure I understand what you are tyring to do with the second one, assuming you just want to know the number of used rows:
Function GetNumberOfRows(list As String) As Integer

    GetNumberOfRows = Worksheets(list).UsedRange.Rows.Count -1

End Function

Or if you want specifically the rows in the second column:
Function GetNumberOfRows(list As String) As Integer

    GetNumberOfRows = Worksheets(list).Cells(rows.count,"B").End(xlUp).Row

End Function

Third one:
Sub ReplaceValue(oldValue As String, newValue As String, list As String)

Worksheets(list).UsedRange.Replace What:=oldValue, Replacement:=newValue, LookAt:=xlWhole, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

End Sub

A: For the function GetNumberOfRows, you're passing a worksheet name as an argument? Try this:
Function GetNumberOfRows(list As String) As Integer

    GetNumberOfRows = Worksheets(list).UsedRange.Rows.Count - 1

End Function

I added '-1' if you don't want to count the header (you're function started counting at row 2)

A: To check if in array:
Function IsInArray(value As String, arr As Variant) As Boolean

    If Not IsArray(arr) Then
        'the argument arr is not an array, return false
        IsInArray = False
        Exit Function
    End If

    IsInArray = (InStr(1, "||" & Join(arr, "||") & "||", "||" & value & "||", vbTextCompare) > 0)

End Function

To get the number of rows:
Function GetNumberOfRows(list As String) As Integer

    With Sheets(list)
        GetNumberOfRows = WorksheetFunction.Max(0, .Rows.Count - WorksheetFunction.CountBlank(.Columns("B")) - 1)
    End With

End Function

To replace values:
Sub ReplaceValue(oldValue As String, newValue As String, list As String)

    With Intersect(Sheets(list).UsedRange, Sheets(list).Range("C:L"))
        .Replace oldValue, newValue, xlWhole
    End With

End Sub


text:
Q: Unsupported Media Type after request I want to make POST request from Angular client. I have this Spring endpoint:
    @RestController()
public class HomeController {

  @PostMapping(value = "/payment/{unique_transaction_id}")
  public ResponseEntity<WpfResponse> handleWpfMessage(@PathVariable("unique_transaction_id") String unique_transaction_id,
      @RequestBody WpfPaymentsDTO transaction, HttpServletRequest request) throws Exception {

    /// ....
    MessageProcessor messageProcessor = processors.getOrDefault(transaction.getTransaction_type(), defaultProcessor);
    return ResponseEntity.ok(messageProcessor.processMessage(merchant, contract, terminal.get(), transaction, request));
  }
}

I use this typescript code:
save(main: MainForm, hash: string): void {
    const headers = new HttpHeaders();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');
    this.http.post('http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74', JSON.stringify(main), { headers }).subscribe();
  }

But when I run the code I get:
HttpErrorResponse {headers: HttpHeaders, status: 415, statusText: "Unsupported Media Type", url: "http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74", ok: false, …}error: nullheaders: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}lazyInit: ƒ ()lazyUpdate: nullnormalizedNames: Map(0) {}__proto__: Objectmessage: "Http failure response for http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74: 415 Unsupported Media Type"name: "HttpErrorResponse"ok: falsestatus: 415statusText: "Unsupported Media Type"url: "http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74"__proto__: HttpResponseBase

Do you know how I can solve this issue?
WpfPaymentsDTO:

public class WpfPaymentsDTO {

    private String transaction_id;

    private String transaction_type;

    private String currency;

    private Integer amount;
    .....
}

A: Give the content type in the PostMapping as so :
@PostMapping(path = "/payment/{unique_transaction_id}", consumes = "application/json", produces = "application/json")

Here "application/json" is just a sample. You can give the suitable type.

A: Check that you have Jackson added and configured in your Spring application. Refer to this question:
415 Unsupported MediaType for POST request in spring application


text:
Q: Как получить запросом POST Set-cookie используя retrofit2? RegistrationBody.class:
public class RegistrationBody {

    public String email;
    public String first_name;
    public String last_name;
    public String password;
}

RegistrationResponce.class:
public class RegistrationResponse {

    public String cookie;
}

Запрос:
@POST("/signup/")
    Call<RegistrationResponse> registerUser(@Body RegistrationBody registrationBody);

Для авторизации пользователя я передаю POST-запросом поля email, first_name, last_name, password. Этот запрос должен возвратить мне Set-cookie, но не возвращает:
requestInterface = Controller.getApi();
                RegistrationBody registrationBody = new RegistrationBody();
                registrationBody.email = email;
                registrationBody.first_name = firstName;
                registrationBody.last_name = lastName;
                registrationBody.password = newPassword;
                requestInterface.registerUser(registrationBody).enqueue(new Callback<RegistrationResponse>() {
                    @Override
                    public void onResponse(Call<RegistrationResponse> call, Response<RegistrationResponse> response) {
                        Log.d("myLogs", "Response" + response.raw().headers());
                    }

                    @Override
                    public void onFailure(Call<RegistrationResponse> call, Throwable t) {
                        Log.d("myLogs", "response onFailure");
                        Log.d("myLogs", "Throwable: " + t.toString());
                    }
                });

AddCookiesInterceptor.class:
public class AddCookiesInterceptor implements Interceptor {
    public static final String PREF_COOKIES = "PREF_COOKIES";
    private Context context;

    public AddCookiesInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {

        Request.Builder builder = chain.request().newBuilder();

        HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<String>());

        String cookiestring = "";
        for (String cookie : preferences) {
            String[] parser = cookie.split(";");
            cookiestring = cookiestring + parser[0] + "; ";
        }
        builder.addHeader("Cookie", cookiestring);

        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
        }

        return chain.proceed(builder.build());
    }
}

ReceivedCookiesInterceptor.class:
public class ReceivedCookiesInterceptor implements Interceptor {

    private Context context;
    public ReceivedCookiesInterceptor(Context context) {
        this.context = context;
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet("PREF_COOKIES", new HashSet<String>());

            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
            }

            SharedPreferences.Editor memes = PreferenceManager.getDefaultSharedPreferences(context).edit();
            memes.putStringSet("PREF_COOKIES", cookies).apply();
            memes.commit();
        }

        return originalResponse;
    }
}

Добавила клиент:
private static Context context;

    public Controller (Context context) {
        this.context = context;
    }

    public static RequestInterface getApi() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        OkHttpClient client = new OkHttpClient();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        builder.addInterceptor(new AddCookiesInterceptor(Controller.context));
        builder.addInterceptor(new ReceivedCookiesInterceptor(context));

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);
        return requestInterface;

Как исправить код, чтобы запрос возвратил мне Set-cookie? Запрос выводит следующее:
Server: nginx/1.10.3
Date: Tue, 28 Nov 2017 12:49:34 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 17
Connection: keep-alive
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin:

Использование следующего кода выдает ту же информацию:
private final OkHttpClient client = new OkHttpClient();

 RequestBody formBody = new FormBody.Builder()
                        .add("email", intent.getStringExtra("email"))
                        .add("first_name", intent.getStringExtra("firstName"))
                        .add("last_name", intent.getStringExtra("lastName"))
                        .add("password", etNewPassword.getText().toString())
                        .build();
                Request request = new Request.Builder()
                        .url("http://api.yogamy.live/signup")
                        .post(formBody)
                        .build();
                client.newCall(request).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        Log.d("myLogs", "response onFailure");
                        Log.d("myLogs", "Throwable: " + e.toString());
                    }

                    @Override
                    public void onResponse(okhttp3.Call call, Response response) throws IOException {
                        Log.d("myLogs", "Responce " + response.headers());
                    }
                });

A: https://stackoverflow.com/questions/23879567/retrofit-keeps-forgeting-my-cookies-android
//First create a new okhttpClient (this is okhttpnative)
OkHttpClient client = new OkHttpClient(); //create OKHTTPClient
//create a cookieManager so your client can be cookie persistant
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager); //finally set the cookie handler on client

//OkClient is retrofit default client, ofcourse since is based on OkHttClient
//you can decorate your existing okhttpclient with retrofit's okClient
OkClient serviceClient = new OkClient(client);

//finally set in your adapter
RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("Some eNdpoint")
            .setClient(serviceClient)
            .build();


text:
Q: How to use Login View in django? I decided to customize the login form and do authentication with email. I can login with a super user account but can't do it with the simple user.
Here's the models.py file. I created a custom user manager and redefined the creation logic:

    def create_superuser(self, email, user_name, first_name, last_name, password, **other_fields):

        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError('Staff must be True')

        if other_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must be True')

        if other_fields.get('is_active') is not True:
            raise ValueError('Is active must be True')

        return self.create_user(email, user_name, first_name, last_name, password, **other_fields)

    def create_user(self, email, user_name, first_name, last_name, password, **other_fields):

        if not email:
            raise ValueError('You must provide an email')

        email = self.normalize_email(email)
        user = self.model(email = email,
                            user_name = user_name,
                            first_name=first_name,
                            last_name = last_name,
                            **other_fields)
        user.set_password(password)
        user.save()
        return user

class UserProfile(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(('email address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    start_date = models.DateTimeField(default=timezone.now)
    department = models.CharField(max_length=150)
    company = models.CharField(max_length=150)
    head = models.CharField(max_length=150, blank=True)

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

    dashmodel = models.CharField(max_length=150, blank=True)
    role = models.CharField(max_length=150, blank=True)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name','first_name','last_name']

    def __str__(self):
        return self.user_name ```

I change the logic of login with email:

``` UserModel = get_user_model()

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserModel.objects.get(Q(user_name__iexact=username) | Q(email__iexact=username))
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
            return
        except UserModel.MultipleObjectsReturned:
            user = UserModel.objects.filter(Q(user_name__iexact=username) | Q(email__iexact=username)).order_by('id').first()

        if user.check_password(password) and self.user_can_authenticate(user):
            return user```

And here's the login view:
class LoginView(auth_views.LoginView):
    form_class = LoginForm
    template_name = 'login-test.html'
    success_url = '/dashboard/model-filter/'
    extra_context ={
        'title':'Login Form',
        'btn_label':'Login',
        'redirect_url':'register',
        'redirect_title':"Want to register?",
    }

If I'm trying to login with super user everything works perfect. But when I try to use a simple user I get the following error in the form:
"Please enter a correct email address and password. Note that both fields may be case-sensitive."
And one more noob question: how do I track the error of LoginView and all entered information in logs?

A: For your non-super user is_active=False by default, and the default AUTHENTICATION_BACKENDS reject inactive users.


text:
Q: Adding new column in between existing columns according to data in a text file I'm adding data in text files to a datatable according to the method shown below:
suppose these are the lines that I use in the 1st text file:
data1, data2

1,2

suppose these are the lines that I use in the 2nd text file:
data1, data2

3,4

I would insert them to a datatable as show below:

I have done the coding upto this point and it works successfully. The issue occurs when the 3rd text file contains data as shown below:
data1, data0, data2

5,6,7

at this instance i need to re arrange my datatable as shown below:

I tried many ways but it keeps on adding data only to the end of the datatable. Can somebody please help. I have provided my coding below:
private DataTable CreateDT1(string name, ListBox list)
    {
        DataTable dt = new DataTable();
        string[] files = new string[list.Items.Count];//text files are taken to a list box
        for (int x = 0; x < list.Items.Count; x++)
        {
            object s = list.Items[x];
            files[x] = s.ToString();
        }
        int lineno = 0;
            for (int i = 0; i < files.Length; i++)
            {
                int count = 0;
                string file = files[i];
                using (System.IO.StreamReader sr = new System.IO.StreamReader(file))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.Contains(name))//i'm filtering some lines containing a given string
                        {
                            if (i == 0)
                            {
                                if (lineno == 0)//first line in the first test file. Eg: data1,data2
                                {
                                    string[] split = line.Split(',');//splitting the line adding data to rows

                                    int result = split.Length;
                                    dt.Rows.Add();
                                    for (int x = 0; x < result; x++)
                                    {
                                        DataColumn dc = new DataColumn(x.ToString(), Type.GetType("System.String"));
                                        dt.Columns.Add(dc);
                                        dt.Rows[lineno][x] = split[x];
                                    }
                                }
                                else
                                {
                                    string[] split = line.Split(',');//splitting the other lines in 1st text file and adding data to rows
                                    int result = split.Length;
                                    dt.Rows.Add();
                                        for (int x = 0; x < result; x++)
                                        {
                                            dt.Rows[lineno][x] = split[x];
                                        }
                                }
                            }

                            else
                            {
                                if (count != 0)//for other (2nd, 3rd, ..)text files. This refers to the lines other than the 1st line(5,6,7). First line (data1, data0, data2)of these text files are not accounted here.
                                {
                                    string[] split = line.Split(',');
                                    int result = split.Length;
                                        dt.Rows.Add();
                                        for (int x = 0; x < result; x++)
                                        {
                                            dt.Rows[lineno][x] = split[x];
                                        }
                                }

                                else //this is the first line of other files
                                {
                                    string[] split = line.Split(',');
                                    int result = split.Length;
                                    if (result + 1 > dt.Columns.Count)//if existing number of columns are less than the split result of the first line, add new columns accordingly. I need help at this point
                                    {
                                        for (int x = 0; x < result; x++)
                                        {
                                            Object a = dt.Rows[0][x];
                                            if (split[x] == Convert.ToString(a))
                                            {
                                                dt.Rows[0][x] = split[x];
                                            }
                                            else
                                            {
                                                dt.Columns.Add(x.ToString() + split[x]).SetOrdinal(x + 1);
                                                //dt.Columns.Add(x.ToString() + split[x]).SetOrdinal(x);
                                                dt.Rows[0][x.ToString() + split[x]] = split[x];
                                            }
                                        }

                                        lineno -= 1;
                                        count += 1;
                                    }
                                    else
                                    {
                                        lineno -= 1;
                                        count += 1;
                                    }
                                }

                              }

                            lineno += 1;
                        }

                    }

                }

            }

        return dt;
    }

A: Columns are only added at the end, because otherwise it can mess up existing INSERT SQL queries.
You should not be concerned about how the db organizes itself - that's the whole point!
later on just query out columns at your wanted order..


text:
Q: I get ORA-13605 when trying to run SQL Tuning Advisor from SQL Developer When trying to use the SQL Tuning Advisor from SQL Developer I get this error.
Tuning advisor was working some days before.

A: The solution is very simple. The string of the query is just too long.
I'm trying to optimize a stored procedure using dynamic sql with a parameter to decide if the sql is executed or output.
I just copied the output into a fresh sql developer pane and tried to use the tuning advisor.
The problem is that the generated output has a lot of trailing blanks, I just have to remove them.

A: Try to switch your browser's language settings.
If the database is running with American/America, switch your browser to en-us. Then re-connect and run the task again.
This fixed up our SQL Tuning Advisor task which failed with the same error.


text:
Q: Adding a Doctype to the document dynamically using JavaScript I want to detect whether a doctype exists for the current document and add one if nothing exists.
I'm able to check whether a doctype exists using document.doctype. But how can i add one?

A: I don't think it's possible to change the page mode from within the page. Sorry.


text:
Q: Group items by 2 columns Let's say we have a Sqlite table containing:
name;city;age;id
Alice;New-York;25;13782749
Eve;Chicago;23;1938679
Bob;New-York;25;824697624

How to group by h=CONCAT(city,age):
h;name;id
group1;Alice;13782749
group1;Bob;824697624
group2;Eve;1938679

Instead of group1, group2, it's ok to have 1, 2, or even a hash f68ac46, c3155a0 for each group.
The closest I could get is:
select (city||age) as h, * from mytable order by h;

but I'd like a group number or a hash instead, and not display city||age  (which in my real case can be long).

A: You could enumerate the groups using dense_rank():
select dense_rank() over (order by city, age) as grpnum, name, id
from t;


text:
Q: External Monitor issues in Windows 7 BootCamp MacBook Pro So I got a monitor to use as an external for my MacBook Pro. It is an LG e2340 and I am connecting via HDMI by the way. Anyways, there are some issues I have found and I am wondering if there are any ways to remedy them.

*

*In the mid-resolution range (1000horizontal-1600h) green lines appear in the dark areas of the external screen

*In the high-resolution range(1600h-1900h) it seems like the monitor can't handle it because it is all black and the menu buttons don't work.

I tried to see how it fared in OSX and most of the same things were happening. I tried the 1080p option and it did the blank screen thing. Then I tried 1080i and what do you know it worked. I looked up what the i meant and found that it was interlaced so I went back to windows and looked through the advanced resolution options and found options for 1920x1080 (Interlaced) and it worked.
Things I have noticed though are that the refresh rate is only 30Hz so I can sometimes notice flickering, especially with Windows Glass.
So, after all of that, what do you think is wrong? Is there a way to increase refresh rate with interlaced? Or even better, how can I get 1080p to work?
Thanks a bunch
EDIT: It works with 720p so its not that its not capable of progressive. On the web page here it says Full HD 1080p = YES

A: It's probably a bad cable. Read the above comments for the discussion.


text:
Q: where is the documentation for using hidden = {true} in a react component When trying to hide an input tag in regular html you can use the following:
<input hidden />

and when you want to show the tag we use:
<input />

Apparently in the return portion of a react component you can do the following to hide an element:
<input hidden={true} />

I can't find any documentation for this.  Could someone direct me to a source?

A: Any standard or custom DOM attributes are fully supported according to the docs, just camel case them and react will put the corresponding attribute in the actual dom.
https://reactjs.org/docs/dom-elements.html
you may also find it helpful to read the intro to JSX since there may be confusion there.
https://reactjs.org/docs/introducing-jsx.html
Lastly just being nit picky <inpupt /> is a react element not a react component.
Difference between React Component and React Element


text:
Q: QGIS QgsTask finished and completed never called I'm rewriting a plugin to use QgsTask with this as my first guideline and the update mentioned in this post as a possible solution for my problem. My task runs fine in the background, but
def finished(self, result):

and
def completed(self, exception, result=None):

are never called. Anybody any ideas?
EDIT: added more code below
EDIT 2: found out that if there is an error in the method run it then actually reaches finished before it gives an error.
main_plugin.py
# Import link to Qt and QGIS
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtWidgets import QAction, QMenu, QFileDialog
from qgis.core import *
from qgis.gui import QgsMessageBar

# Import everything to create the plugin
from . import resources
from .plugin_dialog import PluginDialog
from .gdal_raster import Raster
from .task_raster import CreateRasterTask
from .task_raster import DoStuff

# Import everything to run the plugin
import sys
import os

class RasterPreparePlugin(object):
    def __init__(self, iface):
        # save reference to the QGIS interface
        self.iface = iface

    def run(self):
        self.dlg = PluginDialog()
        self.dlg.show()

        # Run the dialog event loop
        result = self.dlg.exec_()

        if result:
            layer = combobox.currentLayer()
            path = self.dlg.ui.LineEditOutputLayer.text()

            raster = Raster(layer, path, VERSION)

            okay = DoStuff(raster, self.iface)
            okay.do_subclassed_tasks()

task_raster.py
from qgis.core import (
    QgsApplication,
    QgsTask,
    QgsMessageLog,
    Qgis,
    )

MESSAGE_CATEGORY = 'CreateRasterTask'

class CreateRasterTask(QgsTask):
    def __init__(self, description, raster):
        super(QgsTask, self).__init__(description, QgsTask.CanCancel)
        self.exception = None
        self.raster = raster

    def run(self):
        test = self.raster.task()

        return test

    def finished(self, result):
        if result:
            QgsMessageLog.logMessage(
                'Task "{name}" completed'.format(
                name=self.description()
                ),
            MESSAGE_CATEGORY, Qgis.Success)
        else:
            if self.exception is None:
                QgsMessageLog.logMessage(
                    'Task "{name}" not successful but without '\
                    'exception (probably the task was manually '\
                    'canceled by the user)'.format(
                        name=self.description()),
                    MESSAGE_CATEGORY, Qgis.Warning)
            else:
                QgsMessageLog.logMessage(
                    'Task "{name}" Exception: {exception}'.format(
                        name=self.description(),
                        exception=self.exception),
                    MESSAGE_CATEGORY, Qgis.Critical)
                raise self.exception

    def cancel(self):
        QgsMessageLog.logMessage(
            'Task "{name}" was canceled'.format(
                name=self.description()),
            MESSAGE_CATEGORY, Qgis.Info)
        super().cancel()

class DoStuff:
    def __init__(self, raster, iface):
        self.raster = raster
        self.iface = iface
        self.task = CreateRasterTask('Test', self.raster)

    def do_subclassed_tasks(self):
        """Do tasks using QgsTask subclass. """
        QgsApplication.taskManager().addTask(self.task)

    def stopped(self, task):
        QgsMessageLog.logMessage(
            'Task "{name}" was canceled'.format(
                name=task.description()),
            self.MESSAGE_CATEGORY, Qgis.Info)

    def completed(self, exception, result=None):
        if exception is None:
            if result is None:
                QgsMessageLog.logMessage(
                    'Completed with no exception and no result '\
                    '(probably manually canceled by the user)',
                    MESSAGE_CATEGORY, Qgis.Warning)
            else:
                QgsMessageLog.logMessage(
                    'Task "{name}" finished'.format(
                        name=task.description()),
                    self.MESSAGE_CATEGORY, Qgis.Info)
        else:
            QgsMessageLog.logMessage("Exception: {}".format(exception),
                                    MESSAGE_CATEGORY, Qgis.Critical)
            raise exception

gdal_raster.py
# Import link to QGIS
from qgis.core import (
    QgsPointXY,
    QgsExpressionContextScope,
    QgsExpressionContextUtils,
    QgsMessageLog,
    Qgis,
    )

# Import everything to run the plugin
import osgeo.gdal as gdal
import osgeo.osr as osr
import numpy as np
import datetime
import math

class Raster(object):
    def __init__(self, layer, path, version):
        self.layer = layer
        self.path = path
        self.version = version

    def task(self):
        QgsMessageLog.logMessage('Debug 5', 'MESSAGE_CATEGORY', Qgis.Success)
        try:
            # do stuff
            return True
        except:
            return False

A: I've had the same trouble with QgsTask in the past. The issue (as far as I can work out) seems to be when tasks are run from a plugin. I've tried both tasks from a function and subclassed tasks from the python console and they both called the finished function upon completion.
As a workaround for subclassed tasks in a plugin I was using pyqtSignal in the tasks class which I would subscribe to in the main thread. I added the myObjectSignal = pyqtSignal(object) at the start of class before its initialized. I'm using an object but you could return any type eg myListSignal = pyqtSignal(list)
class SubclassedTask(QgsTask):

    myObjectSignal = pyqtSignal(object)

    def __init__(self, argument1):
        super().__init__(_description, QgsTask.CanCancel)
        self.argument1 = argument1
        self.result = None

In the run method of the class I would emit the signal if it reached the end
     def run(self):
         Caluclate the result...
         self.myObjectSignal.emit(self.result)
         return True

In the main thread I would create the class instance then subscribe to the signal in it before adding it to the task manager. This would connect to a function in the main thread that could do something with the information being returned.
        newTask = SubclassedTask(argument1)
        newTask.myObjectSignal.connect(self.completeTaskProcessing)
        QgsApplication.taskManager().addTask(newTask)

The handling method in the main thread would look like this
     def completeTaskProcessing(self,taskResult):

         print(taskResult)

I probably should have been disconnecting from the signal upon completion but I never added it and it seems to work currently so I'm not looking to touch it.


text:
Q: An abelian group $G$ is free abelian if and only if satisfies the projective property I've been reading group theory from Rotman's book "Introduction to the theory of groups" and in Chapter 10 of free abelian groups there is an exercise which am having a hard time to prove.
The exercise is the following:

An Abelian group $F$ is free if and only if it has the projective property.

Necessary definitions:

Free Abelian: An Abelian group $F$ is free abelian if it is the direct sum of infinite cyclic groups.More precisely, there is a subset $X\subset F$ of elements of infinite order called a basis of $F$ with $F=\bigoplus\limits_{x \in X}\langle x\rangle.$
Projective Property: We say that an Abelian group F has the projective property if for every two abelian groups $B,C$ and for every $\beta:B\to C$ surjective homomorphism and every $\alpha:F\to C$ homomorphism there exists homomorphism $\gamma:F\to B$ such that $\alpha = \beta \circ \gamma.$

Rotman has the proof for the $"\implies"$ direction and its understandable although for opposite direction i dont know how to start, i picked $B,C$ to be $\bigoplus\limits_{x \in F}\langle x \rangle$ and $\beta(x)=(\beta_y)_{y \in F}$ where $\beta_y = x$ if $y=x$ and $\beta_y =0$ for $y\neq x$, $\alpha(x) =(\alpha_x)_{x \in F}$ where $\alpha_x =x$ and $\alpha_y = 0 $ for $y\neq x$ and then $\gamma:F \to B$ seems to be an injection hence $F \cong \operatorname{Im}\gamma \leq\bigoplus\limits_{x \in F}\langle x \rangle$ ... is this correct? If not do you have any ideas on how am going to prove it?
Thanks in advance !

A: Let $A$ be a projective Abelian group, consider the free Abelian group $F_A$ whose basis is $\{[x],x\in A\}$, there exists a canonical projection $p:F_A\rightarrow A$ defined by $p([x])=x$. Since $A$ is projective, there exists $f:A\rightarrow F_A$ such that $p\circ f=Id_A$, we deduce that $f$ is injective and $A$ is isomorphic to a subgroup of $F_A$. A subgroup of a free Abelian group is free.
https://en.wikipedia.org/wiki/Free_abelian_group#Subgroups


text:
Q: How to modify someone else's Github pull request? Someone created a pull request on my Github repo. It mostly looks good, but I had to make a few minor changes to get it to pass my continuous integration server.
Github's on-screen instructions to "review" the request were to run:
git checkout -b otheruser-fix_somebug
git pull https://github.com/otheruser/myrepo.git fix_somebug

I then made my changes, and committed locally. However, when I went to run git push, git informed me:
fatal: The current branch otheruser-fix_somebug has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin otheruser-fix_somebug

which I did, but my changes are not showing under the pull request, but instead under a copy of the branch otheruser-fix_somebug mirrored on my Github repo and unconnected to the pull request.
How should I have called git push to get the changes to appear on the pull request?

A: What about checking out the branch from the Pull Request? Then you can do the commit there, and push to that branch directly.
git fetch
git checkout fix_somebug

add the commit with your changes
git push origin fix_somebug

A: To my knowledge, you can only do this if they grant you permission. In the past this was only possible by them adding you as a contributor on their fork, however, in September 2016, GitHub added a feature for exactly this use case, allowing the person requesting the Pull Request to give permission to the maintainer(s) of the upstream repository simply by marking a checkbox.
You can make a comment on the Pull Request, telling them that their are some issues you'd like to fix before merging the Pull Request, and stating that you'd like them to give you permission to commit to their Pull Request branch by checking the "Allow edits from maintainers" checkbox on the Pull Request, and giving them a link to the GitHub Help page about the feature, so they can see exactly how to enable it. Once they've done so, you can push to the Pull Request branch of their repository directly.

Things you can do if they haven't/won't give you write access to their pull request branch:

*

*Make comments on their Pull Request:

*

*Go to the Pull Request in your browser

*Scroll to the bottom of the "Conversation" (default) page

*Post comments describing the changes they need to make before you'll accept the PR.

*Make comments on the code in their Pull Request:

*

*Go to the Pull Request in your browser

*Clicking the "Files changed" link at the top

*Hover over a line of code that should be changed

*Clicking the little blue "+" button that appears next to it
(NB: these only appear on changed, and nearby lines)

*Post a comment and/or some code to fix what's there

*Repeat 3-5 as needed.

*Accept it as is, then fix it in your own repository

*

*Merge their branch as if there was nothing wrong with it

*Make a new commit to your repository that fixes the issues (preferably mentioning the PR by issue id in your commit message so that GitHub can tell it's related and show it in the PR's Conversation page)

A: Step 1: in your local repo add a new remote pointing to contributor's
git remote add contributor https://github.com/contributor/repo.git

You will now have two remotes - origin and conritbutor. To verify - run this: git remote -v
Step 2: fetch from new remote
git fetch contributor

Step 3: create a new branch from their changes
git checkout -b contributor-main contributor/main

(replace "main" with "master" if needed)
Step 4: Make changes, commit and push
If the contributor has "allowed changes form maintainers" when creating the PR (most do b/c it's the default option), the new commit will show up in the PR instantly
P.S. Replace "contributor" with the user's name


text:
Q: MongoDB - Aggregate / Group by array in array Assuming my cardgame matches collection has documents like these:
{
  match_id: 1,
  players: [
    {
      cards: [ "c03", "c15", "c22" ],
      result: 1
    },
    {
      cards: [ "c01", "c22", "c23" ],
      result: 0
    }
  ]
}

Now I want to determine which decks have been played and how often, meaning a list of all cards arrays, not a list of occurrences where two specific card arrays met.
I have tried this, which groups by match-ups:
db.collection.aggregate([{
  $group: {
    _id: "$players.cards",
    count: { $sum: 1 }
  }
}])

Actual Result:
[
  {
    "_id": [
      [ "c03", "c15", "c22" ],
      [ "c01", "c22", "c23" ]
    ],
    "count": 3
  },
  ...
]

Expected Result:
[
  {
    "_id": [ "c03", "c15", "c22" ],
    "count": 7
  },
  {
    "_id": [ "c01", "c22", "c23" ],
    "count": 5
  },
  ...
]

How can I get an aggregation of distinct decks irrespective of specific matches?

A: Your players field is an array, you need a $unwind stage to desconstruct the players array to multiple documents to avoid the result with _id (group) containing nested array.
db.collection.aggregate([
  {
    $unwind: "$players"
  },
  {
    $group: {
      _id: "$players.cards",
      count: {
        $sum: 1
      }
    }
  }
])

Demo @ Mongo Playground


text:
Q: FileSystemWatcher unable to start I am developing a Windows Service using C# 2010 and i am using the FileSystemWatcher.  For some reason, i am unable to start my service.
I get the following message when i try to run my service.

The -service- on Local computer started and stopped.  Some services start automatically if they are not in use in other services or programs.

This occurs when i put this piece of code :
OnStart:
FSWatcherTest.Path = ConfigurationManager.AppSettings["WatchPath"].ToString();

and then in a method:
private void InitializeComponent()
{
     this.FSWatcherTest = new FileSystemWatcher();
     ((System.ComponentModel.ISupportInitialize)(this.FSWatcherTest)).BeginInit();

       this.FSWatcherTest.EnableRaisingEvents = true;
       this.FSWatcherTest.Path = "my path";
       this.FSWatcherTest.Changed += new      FileSystemEventHandler(this.FSWatcherTest_Changed_1);
       ((ISupportInitialize)(this.FSWatcherTest)).EndInit();

}

Waiting for some possible answers. Thank you in advance!

A: This may be a security issue as the filesystemwatcher requires full trust

A: I haven't used this in a while so I may be off base, but you might be turning on the FileSystemWatcher before it's ready.
In the code above, EnableRaisingEvents is set to true in InitializeComponent (as part of designer generated code, I'm guessing).  The designer defaults that property to true expecting you to also set a valid path at design time.  But you're not setting a real path at design time (you're just using "my path").  The FSW may be throwing an exception right after EndInit() since it starts looking for "my path" and can't find it.
Since you're setting the real path in the OnStart method, you should have EnableRaisingEvents false in the designer.  Set it to true in the OnStart method after you set the path.  That's when you want it to start looking for changes.


text:
Q: setxkbmap doesn't stay and resets everytime after using Fcitx I just got this problem after manually updating my Laptop to Linux Mint 20. Before this I used Ibus together with Eurkey without any problem.
After the update I realized they both didn't work anymore. So I removed ibus and tried Fcitx. Got it to work but Eurkey still doesn't stay.
When I boot up I have to enter the command "setxkbmap eu" for the Eurkey layout to work. And as soon as I use Ctrl + Space to change the input method and then back Eurkey layout is reset to English US layout.
I haven't tried a fresh install of Linux Mint 20 yet so I'm not sure if that's the solution and even then I don't want to reinstall everything..


text:
Q: Why are space sizes increased between apostrophes in HTML On my website all of the text between the apostrophes (the words "what's" and "journalist's") have larger spacing than the rest of the text. http://heiditaylorlaw.com/about_me.html Why is this? I tried using the word-spacing tag in CSS with no luck.

A: The problem is text-align: justify;. According to w3schools:

justify   Stretches the lines so that each line has equal width (like in
  newspapers and magazines)

However, you can use text-align:left; instead of text-align: justify;.


text:
Q: scrollview with a button that expands when the button is tapped in ios I am new to IOS development, i would like to ask how i could make a scrollview with some buttons in it aligned horizontally, in which when you tab on one of the buttons the scrollview expand and displays infor data, and when you tab it again it contract or goes to the normal size again). Something like when you open grouped apps on the iphone

A: In the action of your UIButton try to change the UIScrollView's frame.


text:
Q: How can I compute the multiplicities of the projection map over a smooth projective plane curve? Suppose that $F$ is a non-singular homogeneous polynomial in $\mathbb{C}^3$ and let $X$ be its zero locus, which is well-defined in $\mathbb{P}^2$. Consider the function $\pi:X\rightarrow\mathbb{P}^1$ that sends $[x:y:z]\in X$ to $[x:y]$.
My question is: how can I compute the multiplicity of $\pi$ on its branch points? I know that these branch points happen in the points $p\in X$ such that $\dfrac{\partial F}{\partial z}(p)=0$.
My first approach was that those points would need to satisfy $F(x,y,z)=0$ and $\dfrac{\partial F}{\partial z}(x,y,z)=0$ (note that $\dfrac{\partial F}{\partial z}$ is homogeneous of degree $d-1$), and therefore they would be the intersection points of two zero loci... but then I found out that I am messing up the terms "multiplicity" here.
I cannot use the divisor theory to show this result, but to me it seems right to have that the multiplicity of every branch point is $d$; for this it would be sufficient to show that there's only one pre-image for every branch point (and since the degree of $\pi$ is $d$, $d$ would be its multiplicity).
I would welcome any help in this matter; one can see that, from my last three questions, that I'm not very proficient with this subject, so if explanations were quite clear I'd be very satisfied :)


text:
Q: Como organizar resultados da BDados Olá, estou fazendo um site de filme e gostaria de uma ajuda nessa parte.
Após conseguir conexão com a BD, quero que cada registro aparece dentro da grid que fiz.
Vou explicar melhor com fotos.

Cada filme tem seu registro contendo cada informação que desejo manipular.

Acima mostra como eu chamo meu script PHP que contem a conexão com BD.
    porém ele mostra os 2 registro no mesmo local,
    queria que o filme 1 fosse no local do 1 e assim por diante. segue a grid do layout!

Esse é o arquivo PHP
<?php
$conecta = mysql_connect("127.0.0.1", "root", "") or print (mysql_error());
mysql_select_db("bd", $conecta) or print(mysql_error());

 $filmes = mysql_query("SELECT * FROM filmes");
    while($dados = mysql_fetch_array($filmes)){

         echo $dados['nome'] . "
";
         echo $dados['sinopse'] . "
";
         echo $dados['categoria'] . "
";

    }

?>

A: Da forma que está fazendo, terá de concatenar o HTML dentro do arquivo php.
<?php
$conecta = mysql_connect("127.0.0.1", "root", "") or print (mysql_error());
mysql_select_db("bd", $conecta) or print(mysql_error());

$filmes = mysql_query("SELECT * FROM filmes");
$size = 0;
while($dados = mysql_fetch_array($filmes)){
     if($size == 0)
         echo "
";
     echo "
";
     echo $dados['nome'] . "
";
     echo $dados['sinopse'] . "
";
     echo $dados['categoria'] . "
";
     echo "
";
     if($size == 2)
         echo "
";
     $size++;
     $size = $size == 3 ? 0 : $size;
}
?>

E no seu HTML, altere para:

<?php include("get.php"); ?>


text:
Q: Getting value out of json using python I have following json text:
    "data": [
        {
            "Id": "abc",
            "Indexes": {
                "Status": 0,
            }
        },
        {
            "Id": "bcd",
            "Indexes": {
                "Status": 1,
            }
        }

]

I am trying to get Id where status = 0.
I can get this using for loop like:
 for id in test['data']:
        if data['Indexes']['Status'] == 0:
            id = id["Id"]

But is there a better one-liner way of doing this?

A: You have some problems with used variables in your code. This should work:
for data in test['data']:
    if data['Indexes']['Status'] == 0:
        # do something with data["Id"]

If you only want to get the first such item:
this_id = next(data["Id"] for data in test["data"] if data["Indexes"]["Status"] == 0)

A: You can use a list comprehension over test['data']:
results = [id['Id'] for id in test['data'] if id['Indexes']['Status'] == 0]

# results contains every such id

And if you want only the last match in the list of ids, such as your code seems to do, reverse test['data'] and get the next from a iterator made from that:
last_result = next(id['Id'] for id in reversed(test['data']) if id['Indexes']['Status'] == 0)

# last_result is the last matching id


text:
Q: FirebaseMessaging.instance.getInitialMessage() is not called in terminated state FirebaseMessaging.instance.getInitialMessage() is not called in terminated state when we click notification that contains message data like this ,instead it is displaying screen from splash screen
{
"registration_ids": [
""
],

"data": {
    "title": "Flutter9 Object Notification.3...",
    "body": "this is flutter Data Object notification test message from",
    "android_channel_id": "dgdgsdfgs",
},
"android":{
    "priority":"high"
}

}

A: Given that you not displayed how you setup your fcm , here is how to go about it
/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;

/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

/// To verify things are working, check out the native platform logs.
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  print('Handling a background message ${message.messageId}');
}

in main.dart
WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

// setup displaying notifications

channel = const AndroidNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title// description
      importance: Importance.high,
    );

    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    /// Create an Android Notification Channel.
    ///
    /// We use this channel in the `AndroidManifest.xml` file to override the
    /// default FCM channel to enable heads up notifications.
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    /// Update the iOS foreground notification presentation options to allow
    /// heads up notifications.
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

handle message  call this in your initstate
FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage? message) {
      if (message != null) {
        // do message things
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      showMessage(message: message);
    });
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;

      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
                android: AndroidNotificationDetails(
                  channel.id,
                  channel.name,
                ),
                iOS: IOSNotificationDetails(subtitle: notification.title)));
      }
    });

incase you need to navigate on receiving a message
void showMessage({required RemoteMessage message}) async {
    if (message.data['route'] == "mypage") {
      var myparams =  message.data['payload'];
      Navigator.of(context).push(MaterialPageRoute(
          fullscreenDialog: true,
          builder: (_) {
            return MyPage(
             params:myparams,
            );
          })); ...

A: With FCM, you can send two types of messages to clients:

*

*Notification messages, are sometimes thought of as "display messages." These are handled by the FCM SDK automatically.

*Data messages, which are handled by the client app. "

https://firebase.google.com/docs/cloud-messaging/concept-options
What you are trying to send is a data message, my best guess is that the firebase SDK does not recognize the data message so it does not trigger the firebase message event listener. Your notification must have a 'notification' field for firebase SDK to listen to.


text:
Q: In univariate linear regression if you are already using Ordinary Least Square, is cost function still neccesary? I have a question regarding cost function and Ordinary Least Square (OLS) in univariate linear regression.
From my understanding, in linear regression, OLS is used to find the the slope and y-intercept that minimises the sum of squared differences between the dependent and independent variables.
While for cost function, my understanding is that it is also somewhat used to find a line of best fit, by measuring the relationship performance between the dependent and independent variables.
Then if that's the case, do we still need to use cost function when we are already using OLS to plot our line? Thank you.

A: There are at least two roles for cost/loss functions in machine learning: in training and in evaluation. OLS is an estimator that corresponds to square cost in training. So if you choose OLS, you know your training cost. You may still need to specify evaluation cost for evaluating your model, and evaluation cost may differ from training cost. For a more in-depth review, see "Why is using squared error the standard when absolute error is more relevant to most problems?".


text:
Q: Can't use jquery plugin while using vueJs I'm using jQuery tabSlideOut https://github.com/hawk-ip/jquery.tabSlideOut.js
it works fine but on the pages where I use vueJs components I get $(...).tabSlideOut is not a function.
I know that using jQuery within vueJs is not recommended and this is not the case so I didn't undestand why this doesn't work.
<script src="assets/js/jquery.tabSlideOut.js"></script>
<script src="assets/js/tabSlideOut.js"></script>

$(document).ready(function() {
var left = $('#left').tabSlideOut({
  tabLocation: 'left',
  clickScreenToClose: false,
  offset: '40px',
  offsetReverse: true, // offset from bottom, not top
  // handlers: enable and disable buttons when sliding open or closed
  onOpen: function(){
      $('#open').prop('disabled',true);
      $('#close').prop('disabled',false);
  },
  onClose: function(){
      $('#open').prop('disabled',false);
      $('#close').prop('disabled',true);
  }
});
$('#top').tabSlideOut({
  tabLocation: 'right',
  action: 'hover',
  handleOffsetReverse: true,
  offsetReverse: true,
  onLoadSlideOut: true
});
});

<script src="js/app.js" charset="utf-8"></script>

Edit: Solved by including the jQuery plugin after the Vue is created, that by adding this in the created method of the Vue.
    created(){
        //...
        require('./jquery.tabSlideOut');
    }


text:
Q: Can I set display name for column while selecting from Database? Is it possible to set the display name for column while selecting from database? This could save me from writing hundrends of lines of code.  Can I do something like..
var alerts = entities.Alerts.Select(x => new
                    {
                        "Destination IP" = x.destination_ip
                    });

This LINQ later gets converted into DataSet to use with ObjectDataSource. DataGrid uses ObjectDataSource. There are DataGrids all over the project and I have to write code to set HeaderText for each column in UI.
Currently I am using BoundField just to set the HeaderText.
 <asp:BoundField DataField="destination_ip" HeaderText="Destination IP" />

I don't want to do this extra code. Any other approach would be appreciated.

A: Did you try DataAnnotations.? You can do it if you are using code first.
You can achieve it by following way:
public class MyModel
{
    [Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
    public string name{ get; set; }
}


text:
Q: Header, Nav, Container Layout without vertical scroll bar on entire page I am having a hard time with CSS. I'm trying to create a Header, Side Nav Bar and Content Pane. Below is what I need.

I have attempted to create this, but for some reason there is a scroll bar on the side making the header appear and disappear as I scroll.
The only thing that needs a scroll bar is the content pane.
Both the Nav and Content needs extend all the way to the bottom of the browser.
Here is my attempt:
        #header{
            background-color:#000000;
        }

        #nav {
            background-color:#ff6a00;
            width: 220px;
            float:left;
            min-height: 100% !important;
        }

        #section {
            background-color:#808080;
            min-height: 100% !important;
            float:left;
        }

        .scrolling-wrapper {
            width: auto;
            position: absolute;
            margin-left: auto;
            margin-right: auto;
            overflow-y: auto;
        }

Here is the HTML:

            asdasd

            asdasd

                adasd
                @RenderBody()

Everything needs to auto adjust, for example the header can be any height so nav and content needs to compensate for that. I hope that makes sense.
Can anyone please point me into the right direction to remove the scroll bar so that the 3 containers fits perfectly in the browser?
Thank you in advance.

A: I re-worked your entire solution, but it still gives the intended (I hope) output. See the jsfiddle.
The changes I made were (among others):

*

*More semantic HTML5, like using section, header, and nav elements for which they are intended (I recommend html5shiv if legacy browser support is an issue).

*More concise CSS (no !important declarations, more extensibility, etc.)
HTML:

    Hello world

Placeholder

Placeholder

Placeholder

    Hello again...

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

CSS:
body,
html {
    font-family: sans-serif;
    height: 100vh;
    margin: 0;
    padding: 0;
    overflow: none;
}

* {
    box-sizing: border-box;
}

a {
    color: gray;
}

#banner {
    z-index: 999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    background: red;
    padding: .5rem;
    height: 2rem;
}

#banner2 {
    background: orange;
    position: fixed;
    left: 20%;
    top: 2rem;
    width: 100%;
    padding: .5rem;
    height: 2rem;
    z-index: 999;
}

nav {
    position: fixed;
    height: 100vh;
    width: 20%;
    background: blue;
    margin-top: 2rem;
    padding: .5rem;
}

nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

section {
    float: right;
    width: 80%;
    padding: .5rem;
    margin-top: 4rem;
    background: green;
}

p {
    margin: 0;
    padding: 0;
}

Obviously you can make whatever style changes you want for your personal preferences and design requirements (like padding, margin, background-color, etc.)
Your spec:

Before:

After:

The downside of this is that some of the elements use fixed heights. You'll have to adjust some stuff for different font sizes, and probably use media queries to make it all responsive.

A: So after doing a ton of research, tutorials mixed with some trial and error, I finally managed to get the exact solution to my problem stipulated in this question.
The HTML is as follows:

        Header

            Nav

            Section header top

            Section header bottom

            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis ratione facilis fugiat ducimus totam laborum similique nisi repellat qui sit quisquam repellendus saepe voluptatem natus cum consequuntur. Cupiditate officia.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus voluptatum facilis doloremque tempore a perspiciatis recusandae? Sapiente quaerat voluptatum. Tenetur aliquid ut facere placeat rem minima saepe. Velit modi esse.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis ratione facilis fugiat ducimus totam laborum similique nisi repellat qui sit quisquam repellendus saepe voluptatem natus cum consequuntur. Cupiditate officia.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus voluptatum facilis doloremque tempore a perspiciatis recusandae? Sapiente quaerat voluptatum. Tenetur aliquid ut facere placeat rem minima saepe. Velit modi esse.
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis ratione facilis fugiat ducimus totam laborum similique nisi repellat qui sit quisquam repellendus saepe voluptatem natus cum consequuntur. Cupiditate officia.
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus voluptatum facilis doloremque tempore a perspiciatis recusandae? Sapiente quaerat voluptatum. Tenetur aliquid ut facere placeat rem minima saepe. Velit modi esse.

The CSS is as follows:
body,
html {
    height: 100%;
    width:100%;
    margin: 0;
    padding: 0;
}

* {
    box-sizing: border-box;
}

.container {
    position: relative;
    height: calc(100% - 31px);
}

nav {
    background: #0094ff;
    border:1px solid black;
    position: absolute;
    left: 0px;
    width: 220px;
    height: 100%;
}

section {
    background: #b6ff00;
    height: 100%;
    overflow:hidden;
    margin-left: 220px;
}

section.section-header-top{
    height:55px;
    background: #ffd800;
}

section.section-header-bottom{
    height:34px;
    background: #ff6a00;
}

section.content{
    /* The 89px is the 55px + 34px from header sections */
    height: calc(100% - 89px);
    overflow-y: auto;
}

header{
    background:blue;
    height:31px;
    border:1px solid black;
}

The code to this solution can be found here: Solution
I have learnt that you can subtract a % from a px in css which makes things a lot easier, I will reference this post to explain how that works:


text:
Q: Why is europe-west much slower than us-central on Google Cloud Platform's AppEngine? I did an experiment and installed the same application on Google Cloud Platform, with the same database, and the same buckets (for images) on 2 different locations: us-central and europe-west. However, the loading times are hugely different. I am in Spain, and surprisingly the us-central one is much faster.
Application info:

*

*region: us-central VS europe-west

*PHP 5.5

SQL (both the same):

*

*MySQL First Generation master

*MySQL 5.6

*tier: D1

*activation policy: on demand

*Preferred location: follow app

Storage (Google Buckets):

*

*Default storage class: Multi-Regional

*Location: EU (for europe-west) and US (for us-central)

Loading times (after some refreshes for caching purposes):

*

*us-central: 2.26s https://practia-delta.appspot.com/

*europe-west: 9.96s http://gamma.practia.org/
The one in europe-west is so slow it is not practical. Why this difference? Or what did I configure wrong here? Is there anything else that I should look out for in the configuration to make europe-west run as fast as us-central?

A: OK, so talking to Google Support, I found out that there indeed is a loading difference, but it is not due to the servers being in any way slower.
The difference came from a call to the CloudStorageTools API, namely CloudStorageTools.getImageServingUrl(). Accessing the API from Europe was ~100ms to ~200ms slower than from US servers for each call. As I was making more or less 15 calls on average, this led to a noticeable difference in loading times per page.
The solution in my case was to cache the call to CloudStorageTools.getImageServingUrl() on image creation and save the result in the database. Then on displaying the images, just load the Url from the database and avoid the call to the API each time.
Google Support confirmed the difference in the CloudStorageTools API access times between Europe and US was expected behaviour, although undocumented.


text:
Q: Table doesn't display Chrome I have one of the weirdest problem I've ever faced. I have a website used by  hundreds of people and I have a very strange issue. My code is the following (sample and example) :

            ID
            Date and hour
            User
            ........

        <?php
            $SQL = $db -> query("SELECT * FROM rapport where ID = $ID ORDER BY Date_heure ");
            while($ligne = $SQL -> fetch())
            {
                echo '
';
                echo "".$ligne['ID']."	";
                echo "".date('d/m/Y H:i:s', strtotime($ligne['Date_Hour']))."	";
                echo "".$ligne['User']."	";
                ........
            }
        ?>

The problem is that
 doesn't display. If I inspect the element, it appers, but there isn't anything on screen. There is something weird... Not everyone have this problem. I'm facing it, but I asked dozens of people and none of them is facing this problem. I obviously cleared my cache and everything but still this problem. Here's my .css but it looks fine :
table, th, td {
   /* border: 1px solid black;*/
    text-align: center;
}

div#DivTBody {

    width: 100%;
    position: relative;
    display: block;
    overflow-y:scroll;
    overflow-x:hidden;
    height: 350px;

}

table#tbody {

    width: 100%;

}

div#DivTHead {
    width: 100%;
}

table#THead{
    border-collapse:collapse;
    border:none;
    width: 98.8%;
}

.ID {
    width: 2%;
    text-align: center;
}
.Date_Hour{
    width: 10%;
    text-align: center;
}
.User{
    width: 15%;
}

It is working fine on IE and Mozilla. Why is there this problem and how to avoid it?

A: Try disabling your extensions in Chrome. If you are the only one facing this problem in Chrome, it must be your browser blocking content somehow.


text:
Q: How long is a 'Mario Second' and is there a reason why it seems to be shorter than a real second? In all Mario games where theres a timer (like the original Mario Bros and Super Mario Maker) the seconds on the timer... well... don't seem to be real second. It seems to be more in the range of .5 to .75 of a real second.
So how long is that second (does it vary from game to game) and is there a known reason why that timer is not set on a true second?

A: "Mario Second" differs from game to game and could be between 0.4 to 1 real world second. At least in some cases it was caused by technical specifications:

A timer's count is approximately 0.6 or 0.7 seconds (in Super Mario Bros., one in-game count lasts 0.4 seconds, which is 24 frames in 60Hz NTSC or 20 frames in 50Hz PAL, and in New Super Luigi U and the Super Mario Maker games, it lasts exactly one second). When the time limit decreases to below 100 counts, the "hurry up" jingle plays to warn that the player is running low on time and the level's music plays at a faster speed. In newer Mario games, starting with New Super Mario Bros. Wii, if Mario loses a life after hitting a Checkpoint Flag, the time limit will be reduced when he restarts the level from that point.

Source: Time Limit in Mariowiki.


text:
Q: How to show these class of morphisms are perfect In Lurie's book "Higher Topos Theory", a class $\mathsf{W}$ of morphisms in a category $\mathcal{A}$  is called perfect if

*

*Every isomorphism belongs to $\mathsf{W}$.

*it satisfies "2 out of 3 property".

*$\mathsf{W}$ is stable under filtered colimit.

*There exists a small subset $\mathsf{W}_0\subset\mathsf{W}$ such that every morphism belonging to $\mathsf{W}$ can be obtained as a filtered colimit of morphisms belonging to $\mathsf{W}_0$.

I can't show the class of isomorphism in $\mathsf{Set}$ is perfect because of the axiom 4. I think the class $\mathsf{W}$ does not form a small set. But I don't have any idea how to take a set of isomorphisms $\mathsf{W}_0$ to generate every isomorphisms.
And how about the case of the category of simplicial sets $\mathsf{Set}_\Delta$ with weak homotopy equivalences?