text:
Q: ValueError: x and y can be no greater than 2-D, but have shapes (2,) and (2, 1, 991) I wanna plot my Data but I get this Error. Do u know what should I do ?
fig, ax = plt.subplots(figsize=(12,8))

ax.plot(wl, dat[:], color='black')

ax.plot(wl2, dat2[:], color='green')

ax.axvline(4861.32,color='b', linewidth=1)

ax.text(4861.32 + 0.2, np.mean(dat) + 4.8*np.std(dat), "H"+ r'$\beta$', fontsize = 10, color = 'b')

ax.set_title('Spectra', fontsize = 15)

ax.set_xlabel(r'Wavelength [$\mathrm{\AA}$]',fontsize=15)

ax.set_ylabel(r'Flux [erg/cm2/cm/A]', fontsize = 15)
ax.set_xlim(3700,5000)

ax.set_ylim([np.mean(dat2) - 1.5*np.std(dat2), np.mean(dat2) + 2*np.std(dat2)])

Traceback
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [81], in <cell line: 5>()
      1 fig, ax = plt.subplots(figsize=(12,8))
      3 ax.plot(wl, dat[:], color='black')
----> 5 ax.plot(wl2, dat2[:], color='green')

File ~\anaconda3\envs\py10\lib\site-packages\matplotlib\axes\_axes.py:1632, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)
   1390 """
   1391 Plot y versus x as lines and/or markers.
   1392
   (...)
   1629 (``'green'``) or hex strings (``'#008000'``).
   1630 """
   1631 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632 lines = [*self._get_lines(*args, data=data, **kwargs)]
   1633 for line in lines:
   1634     self.add_line(line)

File ~\anaconda3\envs\py10\lib\site-packages\matplotlib\axes\_base.py:312, in _process_plot_var_args.__call__(self, data, *args, **kwargs)
    310     this += args[0],
    311     args = args[1:]
--> 312 yield from self._plot_args(this, kwargs)

File ~\anaconda3\envs\py10\lib\site-packages\matplotlib\axes\_base.py:501, in _process_plot_var_args._plot_args(self, tup, kwargs, return_kwargs)
    498     raise ValueError(f"x and y must have same first dimension, but "
    499                      f"have shapes {x.shape} and {y.shape}")
    500 if x.ndim > 2 or y.ndim > 2:
--> 501     raise ValueError(f"x and y can be no greater than 2D, but have "
    502                      f"shapes {x.shape} and {y.shape}")
    503 if x.ndim == 1:
    504     x = x[:, np.newaxis]

ValueError: x and y can be no greater than 2D, but have shapes (2,) and (2, 1, 991)

A: *

*There are currently 4 arrays of data, wl, dat, wl2, dat2.

*wl and wl2 have the following shape.

import numpy as np

wl = wl2 = np.array([0, 1])

# wl and wl2 look essentially like this
array([0, 1])

>>> wl.shape
(2,)

*

*dat looks essentially like wl and wl2, with the same shape

*dat2 does not look the same because it's a 3D array, and the shape of wl2 doesn't match dat2.

# sample data in the same shape as dat2
np.random.seed(2022)
dat2 = np.random.normal(4, 1, (2, 1, 991))

>>> dat2.shape
(2, 1, 991)

# dat2 looks like the following
array([[[3.9994721 , 3.72509858, 3.86071444, ..., 4.24822846,
         2.7409143 , 5.96405405]],

       [[3.54264793, 5.54945521, 5.68753333, ..., 5.88797684,
         3.98211438, 5.69521236]]])

*

*dat2 can't be plotted against wl2 because the shapes do not match.

*

*dat2 can be sliced (dat2[:, :, 0]) to match the shape of wl2, where 0 is 1 pair of numbers out of 991 pairs.

>>> dat2[:, :, 0]
array([[3.9994721 ],
       [3.54264793]])

>>> dat2[:, :, 0].shape
(2, 1)  # which corresponds to (2,) and will plot without issue

*

*See other resources:

*

*Slicing arrays in Numpy / Scipy

*Iterating over arrays
Some Plotting Options

*

*This is not an exhaustive list of options.

1. Plot 1 pair of numbers
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(wl2, dat2[:, :, 0], color='green', marker='o')

2. Plot 5 pairs of numbers (out of 991 pairs)
fig, ax = plt.subplots(figsize=(12,8))
for i, pair in enumerate(zip(*dat2[0, :, :5], *dat2[1, :, :5]), 1):
    ax.plot(wl2, pair, marker='o', label=f'Pair: {i}')
ax.legend()
plt.show()

3. Plot each group of 991

*

*This is not plotted against wl2.

fig, ax = plt.subplots(figsize=(12, 8))
for i, col in enumerate(dat2):
    ax.plot(col.flat, marker='.', label=f'Col: {i}')
ax.legend()
plt.show()

4. Reshape dat3 and plot
.reshape((991, 2))

*

*The plot of the reshaped array is equivalent to option 3.
# reshape the array
dat2l = dat2.reshape((991, 2))

>>> print(dat2l.shape)
(991, 2)

# plot
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(dat2l, marker='.')

.reshape((2, 991))

*

*The plot of the reshaped array is equivalent to option 2.

*

* ax.plot(wl2, dat2r[:, :5], color='green', marker='o', alpha=0.4) would plot the first 5 pairs.

# reshape the array
dat2r = dat2.reshape((2, 991))

>>> print(dat2r.shape)
(2, 991)

# plot
fig, ax = plt.subplots(figsize=(12, 40))
_ = ax.plot(wl2, dat2r, color='green', marker='o', alpha=0.4)


text:
Q: How to open a source file in a project? I am trying to open a file in an open project in Visual Studio using the extension API. I found this
http://msdn.microsoft.com/en-us/library/vstudio/bb164729(v=vs.110).aspx
and
http://msdn.microsoft.com/en-us/library/vstudio/microsoft.visualstudio.shell.interop.ivsuishellopendocument.openstandardeditor(v=vs.110).aspx
but I don't understand how to implement it. Is there any guide for it or am I looking in the wrong place?

A: Look here:

*

*DTE.OpenFile

*DTE.ItemOperations.OpenFile
Usage:
DTE.ExecuteCommand("File.OpenFile", @"C:\path\to\source_file.cs");

TIP:
To test the method open VS Command Window and simply type File.OpenFile

redpajama_set_name: RedPajamaStackExchange


text:
Q: Different DB Package Installation Calls I've read/seen various DB installation tutorials and one thing often perplexes me... sometimes I see people install both mysqldb & mysqldb-server, or only one or the other. My question is: are both calls needed? Or is it that installing one usually installs the other automatically?
If it matters at all, I am looking at this from the standpoint of installing Wordpress.
-- ps. I've seen the same for mariadb & mariabd-server, and I'm just as perplexed.

A: These databases operate on the client-server model. A given machine may require either a client, a server, or both. I don't see what is surprising about that. If the database software is properly packaged, it should be possible to install either packages for either the client or the server software, because it is not necessary to have a client installed for the proper functioning of a server, and vice versa.
Yes, a database client will need a database server, but the usage model may involve a database server running on another machine, typically a server machine. And similarly, a server machine may only have a database server running on it, but the usage model may not require the server machine to have a client running locally on it.
These facts are not particular to databases, they are generally true for any software using the client-server model, which is a common paradigm.


text:
Q: java: how to mock Calendar.getInstance()? In my code I have something like this:
private void doSomething() {
   Calendar today = Calendar.getInstance();
   ....
}

How can I "mock" it in my junit test to return a specific date?

A: Using Mockito and PowerMockito:
Calendar endOfMarch = Calendar.getInstance();
endOfMarch.set(2011, Calendar.MARCH, 27);
PowerMockito.mockStatic(Calendar.class);
Mockito.when(Calendar.getInstance()).thenReturn(endOfMarch);

Refer to the link for the complete code.

A: You can mock it using PowerMock in combination with Mockito:
On top of your class:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassThatCallsTheCalendar.class})

The key to success is that you have to put the class where you use Calendar in PrepareForTest instead of Calendar itself because it is a system class. (I personally had to search a lot before I found this)
Then the mocking itself:
mockStatic(Calendar.class);
when(Calendar.getInstance()).thenReturn(calendar);

A: Write a class called DateHelper with a method getCalendar that returns Calendar.getInstance().  Refactor the class that you're testing so that it has a member variable of type DateHelper, and a constructor that injects that member variable.  Use that constructor in your test, to inject a mock of DateHelper, in which getCalendar has been stubbed to return some known date.

A: As far as I see it you have three sensible options:

*

*Inject the Calendar instance in whatever method/class you set that day in.
private void method(final Calendar cal)
{
    Date today = cal.getTime();
}

*Use JodaTime instead of Calendar. This is less an option and more a case of a suggestion as JodaTime will make your life a lot easier. You will still need to inject this time in to the method.
DateTime dt = new DateTime();
Date jdkDate = dt.toDate();

*Wrap Calendar inside some interface that allows you to fetch the time. You then just mock that interface and get it to return a constant Date.
Date today = calendarInterfaceInstance.getCurrentDate()

A: Don't mock it - instead introduce a method you can mock that gets dates. Something like this:
interface Utility {

    Date getDate();
}

Utilities implements Utility {

    public Date getDate() {

        return Calendar.getInstance().getTime();
    }

}

Then you can inject this into your class or just use a helper class with a bunch of static methods with a load method for the interface:
public class AppUtil {

    private static Utility util = new Utilities();

    public static void load(Utility newUtil) {

         this.util = newUtil;
    }

    public static Date getDate() {

        return util.getDate();
    }

}

Then in your application code:
private void doSomething() {
   Date today = AppUtil.getDate();
   ....
}

You can then just load a mock interface in your test methods.
@Test
public void shouldDoSomethingUseful() {
     Utility mockUtility = // .. create mock here
     AppUtil.load(mockUtility);

     // .. set up your expectations

     // exercise the functionality
     classUnderTest.doSomethingViaAPI();

     // ... maybe assert something

}

See also Should you only mock types you own? and Test smell - everything is mocked

A: You can mockit using JMockit. Here you can see how you can do it: Mock Java Calendar - JMockit vs Mockito.

A: Avoid use Calendar.getInstance() and just use Mockito methods to return what you like.
For example:
@Test
fun italianLocale_returnsItalianFormatDate() {
    val calendar: Calendar = Mockito.mock(Calendar::class.java)
    Mockito.`when`(calendar.get(Calendar.DAY_OF_MONTH)).thenReturn(27)
    Mockito.`when`(calendar.get(Calendar.YEAR)).thenReturn(2023)
    Mockito.`when`(calendar.get(Calendar.MONTH)).thenReturn(1)
    val formatted = calendar.toReadableDate()
    assert(formatted == "27/01/2023")
}

import Mockito in your gradle file with:
testImplementation ("org.mockito.kotlin:mockito-kotlin:x.x.x")

or (if you are using groovy)
testImplementation "org.mockito.kotlin:mockito-kotlin:x.x.x"


text:
Q: Count the number of ways to divide array into 3 contiguous parts having equal sum I have an array and I have to count number of ways to divide it into into 3 contiguous parts such that their sum is equal. How to modify partition problem to do so?
For example-
let A be an array containing {1, 2, 3, 0, 3}
answer - 2
as it can be divided into {{1,2},{3},{0,3}} and {{1,2},{3,0},{3}} having equal sums.

A: If I understand you correctly, you are constraining the problem such that you cannot rearrange the order of the values in the array. Assuming the problem set is reasonable, you can easily loop through and test each possible variation. This would be recursive, but no dynamic programming necessary. I don't have an IDE in front of me, but I believe code would look something like this (adapt to language of choice):
public int countWays(Array array) {
    int count = 0;
    int sum = 0;
    for (int index = 0; index < array.length(); ++index) {
        // how much would each partition sum to if we partitioned here?
        sum += array.get(index);

        // how many ways could the rest of the array be split to match that sum?
        count += recursiveCount(sum, array.subArray(index + 1, array.length());
    }

    return count;
}

public int recursiveCount(int partitionSum, Array remaining) {
    // base case
    if (remaining.length() == 0) {
        return 1;
    }

    int count = 0;
    int sum = 0;
    for (int index = 0; index < remaining.length(); ++index) {
        // how much would this partion sum to if we partitioned here?
        sum += remaining.get(index);

        // did we hit the mark?
        if (sum == partitionSum) {
            // make a partion here and see if we can finish the rest of the array
            count += recursiveCount(paritionSum, remaining.subArray(index + 1, remaining.length());
        }
    }
    return count;
}

*note: this assumes a subArray function that creates a NEW array from the first index inclusively to the second index exclusively. I believe this is the most common behavior in most libraries.
The more you know about your input the more short cuts you could add to make this more efficient. For example; if you know that the array will only contain positive numbers then you can stop testing partitions when your sum is greater than the target value, because no matter what positive number you add it will never get the sum back down to the target value.

A: In the question asked we need to find three contiguous parts in an array whose sum is the same. I will mention the steps along with the code snippet that will solve the problem for you.

*

*Get the sum of the array by doing a linear scan O(n) and compute sum/3.

*Start scanning the given array from the end. At each index we need to store the number of ways we can get a sum equal to (sum/3) i.e. if end[i] is 3, then there are 3 subsets in the array starting from index i till n(array range) where sum is sum/3.

*Third and final step is to start scanning from the start and find the index where sum is sum/3. On finding the index add to the solution variable(initiated to zero), end[i+2].

The thing here we are doing is, start traversing the array from start till len(array)-3. On finding the sum, sum/3, on let say index i, we have the first half that we require.
Now, dont care about the second half and add to the solution variable(initiated to zero) a value equal to end[i+2]. end[i+2] tells us the total number of ways starting from i+2 till the end, to get a sum equal to sum/3 for the third part.
Here, what we have done is taken care of the first and the third part, doing which we have also taken care of the second part which will be by default equal to sum/3. Our solution variable will be the final answer to the problem.
Given below are the code snippets for better understanding of the above mentioned algorithm::-
Here we are doing the backward scanning to store the number of ways to get sum/3 from the end for each index.
long long int *end = (long long int *)calloc(numbers, sizeof(long long int);
long long int temp = array[numbers-1];
if(temp==sum/3){
    end[numbers-1] = 1;
}
for(i=numbers-2;i>=0;i--){
    end[i] = end[i+1];
    temp += array[i];
    if(temp==sum/3){
        end[i]++;
    }
}

Once we have the end array we do the forward loop and get our final solution
long long int solution = 0;
temp = 0;
for(i=0;i<numbers-2;i++){
    temp+= array[i];
    if(temp==sum/3){
        solution+=end[i+2];
    }
}

solution stores the final answer i.e. the number of ways to split the array into three contiguous parts having equal sum.

A: Here is a corrected working solution, with two examples based on @Mattew Pape answer. But this is a brute force approach trying all the possible partitions. This can be further optimized.The complexity of this method is O(N!).
public class partitonArray {

    static int total = 0;
    public static int countWays(int [] arr) {
        int sum = 0;

        for (int index = 0; index < arr.length; ++index) {
            sum += arr[index];
            List<List<Integer>> lst = new ArrayList();
            List<Integer> l1 = new ArrayList();
            for(int j=0;j<=index;j++)
                l1.add(arr[j]);
            lst.add(l1);
            recursiveCount(sum,  Arrays.copyOfRange(arr, index + 1, arr.length), lst);
        }

        return total;
    }

    public static void recursiveCount(int partitionSum, int [] remaining, List<List<Integer>> lst) {
        // base case
        if (remaining.length == 0 && lst.size() > 1) {
            System.out.println("Result here = "+lst.toString());
            total++;
        }

        int sum = 0;
        List<Integer> l1 = new ArrayList();
        for (int index = 0; index < remaining.length; ++index) {
            sum += remaining[index];
            l1.add(remaining[index]);

            // did we hit the mark?
            if (sum == partitionSum) {
                // make a partion here and see if we can finish the rest of the array
                lst.add(l1);
                recursiveCount(partitionSum, Arrays.copyOfRange(remaining, index + 1, remaining.length), lst);
                lst.remove(l1);
            }
        }
    }

    public static void main(String [] args) {
        //int [] arr ={ 2, 4, 6,7, 7, 6, 3, 3, 3, 4, 3, 4,5, 4, 4, 3, 3, 1,4};
        int [] arr = {1, 2, 3, 0, 3};
        System.out.println(countWays(arr));
    }

}

**Output**:

Result here = [[1, 2], [3], [0, 3]]
Result here = [[1, 2], [3, 0], [3]]
2

/*
  Result here `enter code here`= [[2, 4, 6, 7], [7, 6, 3, 3], [3, 4, 3, 4, 5], [4, 4, 3, 3, 1, 4]]
  Result here = [[2, 4, 6, 7, 7, 6, 3, 3], [3, 4, 3, 4, 5, 4, 4, 3, 3, 1, 4]]
  2
  */

A: The solution approach can be like below:

*

*At first, we should check if the sum of all the elements of the array is divisible by 3 or not. If it is not divisible by 3 then we will not be able to divide it into three parts. So, we will return 0.

*It is obvious that the sum of each part of each contiguous part will be equal to the sum of all elements divided by 3. So, we will call it as part_sum which is Array_Sum / 3.

*We will have to create an array suffix_part_count[], where suffix_part_count[i] equals 1, if the sum of elements from i-th to n-th equals Array_Sum/3 else 0. Now, we will calculate the cumulative sum of the suffix_part_count array from the last index. It is because when we find any prefix part, we will match with the correct suffix position where we will get the suffix part combinations count.

*Then, for each prefix of initial array 1…i with the sum that equals Array_Sum/3, we need to add to the answer suffix_part_count[i+2]. Now why suffix_part_count[i+2] ?
Because, when we get any prefix part which is equal to the part value and we know about if any suffix part present at i + 2 index or not with the suffix_part_count array. We are getting the count from suffix array at i + 2 index because we need to have another middle part which will be definitely equal to the part value.

For example: {1, 2, 3, 0, 3} . Let's do the steps of above.

*

*The sum of the array is 9 and it is divisible by 3. So, we can make three parts here.

*Each part value will be (9/3) = 3

*Now, starting from the last index of the array, we will check if the summation of ith index to last index is equal to 3 or not. If it is 3, then we found one suffix position where we can have one part of the three parts. We will add 1 into that position of the suffix count array. The suffix count array will be: {0, 0, 0, 1, 1}

*Now, we will do cumulative sum of the suffix count array to get the number of combination suffix part can be made at a particular position. The final suffix count array will be: {2, 2, 2, 2, 1}

*Now, we will start with the original array and find the prefix part which will be equal to 3. We will find that in the 2nd index. Now, from the second index, we will go to the 4th (prefix index + 2) index for number of suffix part. As we said before, we will have one middle part as well. Now, the answer will be increased by 2.

*The final answer will be 2 as there are no prefix part present after index 2 which will be equal to 3.

My solution:
https://github.com/setu1421/programming-revamp/blob/master/InterviewBit/Arrays/Partitions.cpp


text:
Q: iFrame Sandbox with Content Security Policy I assume that this is just a simple misunderstanding of the spec. However, I'm having an issue with including scripts in iFrames protected by sandboxing. Specifically, the code I am dealing with is below.
In top.html:
<iframe src="framed.html" sandbox="allow-scripts"></iframe>

In framed.html
...
<head>
  <meta http-equiv="Content-Security-Policy" content="script-src example.com">
  <script src="http://example.com/script.js"></script>
</head>
...

When running this file in Chrome, it gives me the error:

Refused to load the script 'http://example.com/script.js' because
  it violates the following Content Security Policy directive:
  "script-src localhost:9000".

Why is it blocking the script from loading? I know that without allow-same-origin, the iFrame gets a completely unique origin that is not equal to any other origin. Therefore, script-src 'self' wouldn't work. However, I am trying to load the script from an origin explicitly called for in the CSP. Thoughts?
Update: Created JSFiddle to showcase the issue.

A: When you use a sandboxed page with a unique origin, you can't put a host without scheme in the CSP, that's why the policy is violated. Use script-src https://example.com or script-src http://example.com or even script-src https://example.com http://example.com, and the CSP will correctly be relaxed (note that the CSP is whitelist-based, by default most things are disallowed).

As the grammar from the CSP specification shows, the scheme in a CSP directive is optional:
; Schemes: "https:" / "custom-scheme:" / "another.custom-scheme:"
scheme-source = scheme-part ":"

; Hosts: "example.com" / "*.example.com" / "https://*.example.com:12/path/to/file.js"
host-source = [ scheme-part "://" ] host-part [ port-part ] [ path-part ]
scheme-part = scheme
              ; scheme is defined in section 3.1 of RFC 3986.
host-part   = "*" / [ "*." ] 1*host-char *( "." 1*host-char )
host-char   = ALPHA / DIGIT / "-"
port-part   = ":" ( 1*DIGIT / "*" )
path-part   = path-abempty
              ; path-abempty is defined in section 3.3 of RFC 3986.

But a sandboxed frame without the allow-same-origin token will have a null origin, and the URL matching algorithm does not allow scheme-less directives to match (relevant parts of the algorithm shown below):

6.6.1.6. Does url match expression in origin with redirect count?
Given a URL (url), a source expression (expression), an origin (origin), and a number (redirect count), this algorithm returns "Matches" if url matches expression, and "Does Not Match" otherwise.
...

*If expression matches the host-source grammar:

*

*If url's host is null, return "Does Not Match".

*If expression does not have a scheme-part, then return "Does Not Match" unless one of the following conditions is met:

*

*origin's scheme is url's scheme

*origin's scheme is "http", and url's scheme one of "https", "ws", or "wss".

*origin's scheme is "https", and url's scheme is "wss".

In the given example:

*

*origin's scheme is null (because of the use of sandbox without allow-same-origin).

*url is http://example.com/script.js
The null origin's scheme does not match any of the last three cases, so the host name without scheme won't match any URL, and therefore the policy is violated.


text:
Q: Why mpiexec (MPICH2) launch very slow on windows server 2012 R2? Platform: Windows server 2012 R2 Datacenter
Version: mpich2-1.3
Problem: I have installed mpich2 on my windows server before and I could start mpiexec quickly. However, recently I added a domain for my windows server. After I shifted to my new domain and account, mpiexec seems to start too slow. I tried re-install MPICH2, but it still takes about 2 minutes to start the example cpi.exe. My intent is to use MPICH2 to run another program, which is much bigger than cpi.exe, and even if an hour passes, the calculation seems not start. I am quite confused. If you know any solution/guidance, please tell me.

A: I finally solved this question by migrating MPICH2 to MS-MPI. The codes are the same, but some configures of Visual Studio Project should be changed. A good article for how to compile MS-MPI program in Visual Studio: https://blogs.technet.microsoft.com/windowshpc/2015/02/02/how-to-compile-and-run-a-simple-ms-mpi-program/


text:
Q: How do I provide a connection string to a WCF Service from a WPF Browser Application? I am learning WPF and WCF. I created a WPF User Control Library and buit a control. Then I created a WPF Application which displays the control in a window. Then I created a WCF Service Library to provide data for the control. At first, I received this error:

The specified named connection is
  either not found in the configuration,
  not intended to be used with the
  EntityClient provider, or not valid.

Following the instructions here: [StackOverflow], I put the connection string into the WPF Application's app.config, and that fixed the problem.
Now, I've created a WPF Browser Application which displays the control in a browser. Once again, I get the same error. This time, however, I can't put the connection string into the WPF Browser Application's app.config file because, apparently, there is no app.config file for WPF Browser Applications. How, then, do I specify the connection string required by the WCF Service?
-TC

A: After some more research, I've discovered that WPF Browser Applications do use app.config files after all. I added an app.config file to my project and put the connection string into it, and now the application works as expected.


text:
Q: Frame class characterizing S4W5 Let W5 be the basic modal formula $\diamond \square \phi \rightarrow (\phi \rightarrow \square \phi)$ and let S4W5 be the smallest normal modal logic generated by the S4-axioms and W5. I want to find a frame class characterizing S4W5 but have failed so far.
I was able to show that the canonical frame $(W, R)$ of every normal logic containing W5 has the property $\forall x y (xRy \wedge yRx \rightarrow R(x) \subseteq R(y)  )$, where $R(w) : = \{u \in W: wRu \}$. However this property seems too strong when it comes to proving that W5 is valid in all frames with that property.
W5 is of course valid in the class of Euclidean frames, so I guess euclidicity must play some role here. This is also indicated by the fact that the contrapositive of W5 is $\phi \wedge \diamond \neg \phi \rightarrow \square\diamond \neg \phi$, which seems to mix the formulas which are canonical for symmetry and Euclidicity.
Any help would be appreciated.


text:
Q: Google cloud account number what's the equivalent of AWS account number in Google cloud ?
If the user adds 2 service accounts to a portal, how to validate if the service accounts belong to different accounts or a single account.

A: AFAIK in GCP there's no account ID.
By reading the AWS documentation looks like the concepts are slighty different in GCP and in AWS.
As I understand, you want to identify if a service account in GCP belongs to an account, the thing here is that service accounts in GCP do not belong to any account.
Quoting from the documentation:

One of the features of IAM service accounts is that you can treat it both as a resource and as an identity.

*

*When treating the service account as an identity, you can grant a
  role to a service account, enabling it to access a resource (such as
  a project).

*When treating a service account as a resource, you can grant permission to a user to access that service account. You can grant
  the Owner, Editor, Viewer, or Service Account User role to a user to
  access the service account.

Example of how service accounts work in GCP as an identity:

Let's say that I have 2 GCP projects where I am owner in both
  projects:

*

*projectA where I am owner with my email owner-of-project@gmail.com

*projectB where I am owner with my email owner-of-project@gmail.com

  I log into projectA with owner-of-project@gmail.com and from there I  create a service account:

*

*Service account name: service-account-project-A

*Role of the service account (permissions): "Compute Engine Admin" (meaning that this service account will have only access to Compute    Engine resources within projectA).

*Service account ID: service-account-project-a@projectA.iam.gservice

*I can choose to generate a private key for this service account

*I can also choose to enable G Suite Domain-wide Delegation
Then I can log into projectB with owner-of-project@gmail.com.
  Once there I can add the service account as a member of projectB so the Compute Engine resources within project A will be reachable from projectB.

What you can do is list all the service accounts that are added in a particular project in the Service Accounts section of GCP Console.


text:
Q: Subgroup of$\mathbb{Z}$ and finite subgroup of $\mathbb{Z}$ In class, we described a subgroup as follow :
A subset of $\mathbb{Z}$ is called a subgroup if it is nonempty, and the sum and difference of any two of its members is also a member.
I would like to find the "unique finite subgroup of $\mathbb{Z}$. I think it is $S=\{0\}$ but I am not sure $S$ is a subgroup of $\mathbb{Z}$ in this case.

A: If a such a subgroup is not $\{0\}$, it contains $n\neq 0$, for every $p$ integer, $pn$ is in the group and the cardinal of $\{pn, p\in\mathbb{N}\}$ is infinite.


text:
Q: How to handle temporary redirect 307 amazon S3 when using CORS I am using a file uploader (fine-uploader) to upload some files directly to S3. The uploading process works fine until amazon responds with temporary redirect (307). Then, the upload fails with the following error:

XMLHttpRequest cannot load http://testuploads.s3.amazonaws.com/.
  Redirect from 'http://testuploads.s3.amazonaws.com/' to
  'http://testuploads.s3-eu-west-1.amazonaws.com/' has been blocked by
  CORS policy: Request requires preflight, which is disallowed to follow
  cross-origin redirect.


text:
Q: Best way to store bookmarks MYSQL, PHP I was recently thinking which way is the best to store bookmarks and thought i will ask this question on here:
Method 1(this is the simple and most used way):
+-------------------+
| bookmarks_users   |
|-------------------|
| id (int, primary) |
| user_id (int)     |
| bookmark_id (int) |
+-------------------+

Method 2:
+-------------------+
| bookmarks_users   |
|-------------------|
| id (int, primary) |
| user_id (int)     |
| bookmarks_ids (int) |
+-------------------+

but instead of having it multiple we can have one row per user and each time they add a bookmark we can just put it in bookmarks_ids so it will look like this 1,21,35,223,677,345,653,566,244
and on the user side we can just use php to split them based on the , and then fetch all the posts via another function


text:
Q: express permutations with a fixed element and fixed number of elements I want to express permutations with a fixed element an fixed number of elements. Note that I don't want to actually count them, I need an elegant way to write it down. Here I go:
I have a set $S$ and a special element $e$. I want to express permutations of the form:
$<s_i, e, s_j>$
where $s_i,s_j \in S$ and $e$ is the special element.
That is, my permutations only have 3 elements and $e$ always appears in the middle.
How can I express this?

A: A permutation is formally defined to be a bijection from a set to itself.  In your case with the set $S = <s_i, e, s_j >$ we would say a permutation is a function $\pi : S \rightarrow S$ such that $S$ is one-to-one and onto, i.e.  $\pi(x) = \pi(y) \implies x = y$ and $\forall y \in S \hspace{2mm} \exists x \in S \text{ such that } \pi(x) = y$.  Thus we can describe the set of fixed points in the permutation $S' = \{x \in S : \pi(x) = x \}$.  In your case $e \in S'$. If you want to say that $S$ has a certain number of fixed elements, say $n$, then you could write $|S'| = n$ which means that the set $S'$ has $n$ elements.


text:
Q: Overlay png file over a picture Android I'm thinking to develop an app that should take a pic overlay over this pic a png image. For iOS I found some interesting on this link: overlay image over another.
Now I would do the same for an Android application, there's a way to do this stuff?
I need to develop quite the same app for iOS and for Android.
You suggest to use this way or you think it's better to implement something for augmented reality?


text:
Q: google action package how to define custom slot types? Hi this is a question about: google home, action sdk, gactions.exe
at https://developers.google.com/actions/reference/rest/Shared.Types/QueryPatterns
Are so called query pattern with custom types but when I try to add them to my action.json and than update via gaction it always says customTypes is an unknown Parameter.
Does someone have an working example with ApiVersion: 2 ?
Is there somewhere in general an larger example of this json. To better see how all works together? After 2 hours research I cant find anything.
Thanks and best regards
Update: EDIT that works BUT only as intent to start the Skill/APP not inside the APP
Its Still not change the Speech to text.
edit: that work:
 {
      "actions": [
        {
          "description": "Default Welcome Intent",
          "name": "MAIN",
          "fulfillment": {
            "conversationName": "cloud fleet manager"
          },
          "intent": {
            "name": "actions.intent.MAIN",
            "trigger": {
              "queryPatterns": [
                "talk to cloud fleet manager",
                "welcome at cloud fleet manager",
                "ask cloud fleet manager"
              ]
            }
          }
        },
        {
          "description": "first text Intent",
          "name": "hallo2",
          "fulfillment": {
            "conversationName": "cloud fleet manager"
          },
          "intent": {
            "name": "com.cfm.hallo2",
            "trigger": {
              "queryPatterns": [
                "(hello)? to cloud fleet manager",
                "hallo $Test:text cloud fleet manager"
              ]
            },
            "parameters": [
              {
                "name": "text",
                "type": "Test"
              }
            ]
          }
        }
      ],
      "types": [
        {
          "name": "$Test",
          "entities": [
            {
              "key": "bmw",
              "synonyms": [
                "B M W"
              ]
            },
            {
              "key": "benz",
              "synonyms": [
                "benz"
              ]
            }
          ],
          "isUserDefined": false
        }
      ],
      "conversations": {
        "cloud fleet manager": {
          "name": "cloud fleet manager",
          "url": "https://a69fa73a.ngrok.io/google",
          "fulfillmentApiVersion": 2
        }
      }
    }

https://drive.google.com/drive/folders/0B8G3pDr3aWiwZjU1akREdTZNQ1U

A: I got it after two days more trying and reading.
At first I forgot one dollar sign. Secondly user defined intents in action.json package are only working as start trigger.
And with a larger set of names it seems like this types dont change anything at the Speech to text model.
So dtrange names like "Moreton Bay" is still not correctly recognized when its in the type field. And need to be figured out with very difficult Text parsing later.

A: If you have custom slots like names of People or Ships.
To get Custom Words like names. Correctly matched I found that the adding of speech bias hints is working quite well.
You can find informations here:
https://developers.google.com/actions/reference/rest/Shared.Types/AppResponse#Suggestion


text:
Q: New PrintServer object fails, "printer name is invalid" I'm migrating a working ASP.NET web application from WS2008R2 to WS2016, but the same happens on WS2012R2. It fails when executing:
new System.Printing.PrintServer(@"\\printserver");

It throws:

System.Exception: An exception occurred while creating the PrintServer
object. Win32 error: The printer name is invalid.

printserver is not an alias but a hostname. It loads correctly on Windows Explorer. The same line works fine on a regular Console Application when compiling under the same .NET 4.5.2, and also in PowerShell when loading the System.Printing.dll. The GAC shows the right assemblies, and I've also added them manually just in case.
I've set the same application pool configuration settings from the working WS2008 (disabled 32-bit applications and Classic mode), but I've tried different combinations in any case. The application pool runs under the same domain service account on both old and new.
As some user also suggested, I've installed the Print and Document services role, even though the old server doesn't have it, but to no avail.
I'm out of ideas, any kind of help would be greatly appreciated. Thanks!

A: Not really a solution... But I "fixed" this by changing the path of the website in IIS manager back and forth a couple of times. Yes, after a year of trying all I could think of on several servers.
Anyway, not sure what exactly unblocked the situation, but it works for me.


text:
Q: How to write python __init__.py file for module If I have a module folder structure like this:
studio
    tools
        __init__.py
        camera
            __init__.py
            camera.py
        element
            __init__.py
            element.py

How do I write the __init__.py files to make it so I can write my import statements like the following? There is a class object in the camera module called CameraNode that I would like to call like shown in the sample below.
from studio import tools

tools.camera.fn()
tools.CameraNode('')
tools.element.fn()

A: If you have a studio/tools/__init__.py file like this:
from .camera import *
from .element import *

Then you can do a single import elsewhere like:
from studio import tools

and then reference everything as if it were directly in studio.tools.
Not sure if this is answering your question exactly, but hopefully it gets you going in the right direction.

A: An __init__py file allows you to treat any directory as a python package. It is not necessary to write anything in the file itself, just creating it in your directory is enough.
So camera, element and tools can behave as packages.
However, if you want to access python files in sub-directories as well, then you must import those in the __init__.py of the parent directory.
For example, if you want to do tools.camera then you must import camera in the __init__.py in the tools directory.
Otherwise, you will have to import camera separately to access all of the functions in it.
Hope this answers your question.


text:
Q: How to Build an Accumulating Either Builder I want to build an computational expression for either expressions.
That is simple enough
type Result<'TSuccess> =
| Success of 'TSuccess
| Failure of List<string>

type Foo = {
    a: int
    b: string
    c: bool
}

type EitherBuilder () =
    member this.Bind(x, f) =
        match x with
        | Success s -> f s
        | Failure f -> Failure f

        member this.Return x = Success x

let either = EitherBuilder ()

let Ok = either {
    let! a = Success 1
    let! b = Success "foo"
    let! c = Success true
    return
        {
             a = a
             b = b
             c = c
        }
}

let fail1 = either {
    let! a = Success 1
    let! b = Failure ["Oh nose!"]
    let! c = Success true
    return
        {
             a = a
             b = b
             c = c
        }
    } //returns fail1 = Failure ["Oh nose!"]

But in the case of Failures (multiple) I want to accumulate those and return an Failure as below.
let fail2 = either {
    let! a = Success 1
    let! b = Failure ["Oh nose!"]
    let! c = Failure ["God damn it, uncle Bob!"]
    return
        {
             a = a
             b = b
             c = c
        }
    } //should return fail2 = Failure ["Oh nose!"; "God damn it, uncle Bob!"]

I have an idea on how to do that by rewriting Bind and always returning Success (albeit with some additional structure that signifies the accumulated erors). However if I do this then I am missing the stop signal and I always get back the return value (actually not really as I will run into a runtime exception, but in principle)

A: I think that what you are trying to do cannot be expressed using monads. The problem is that Bind can only call the rest of the computation (which may produce more failures) if it can get a value for the function argument. In your example:
let! a = Success 1
let! b = Failure ["Oh nose!"]
let! c = Failure ["God damn it, uncle Bob!"]

The binding cannot call the continuation starting with b because Failure ["Oh nose!"] does not provide a value for b. You could use default values and keep errors on the side, but this is changing the structure you are using:
type Result<'T> = { Value : 'T; Errors : list<string> }

You could write this using applicative functor abstraction where you need to have:
Merge  : F<'T1> * F<'T2> -> F<'T1 * 'T2>
Map    : ('T1 -> 'T2) -> M<'T1> -> M<'T2>
Return : 'T -> M<'T>

You can implement all of these in a way that Merge accumulates errors (if both arguments represent a failure) and Map only applies the computation if there are no values.
There are various ways of encoding applicative functors in F#, but there is no nice syntax for that, so you'll most likely end up using ugly custom operators.

A: Eventually with the hints of @tomas above I could come with this solution which leaves the data types as they are but creates an stateful builder.
Now the only question that remains for me is this thread safe  - I would assume yes. Maybe someone could confirm?
type Result<'TSuccess> =
    | Success of 'TSuccess
    | Failure of List<string>

type Foo = {
    a: int
    b: string
    c: bool
}

type EitherBuilder (msg) =
    let mutable errors = [msg]
    member this.Bind(x, fn) =
        match x with
        | Success s -> fn s
        | Failure f ->
            errors <- List.concat [errors;f]
            fn (Unchecked.defaultof<_>)

    member this.Return x =
        if List.length errors = 1 then
            Success x
        else
            Failure errors

let either msg = EitherBuilder (msg)

let Ok = either("OK") {
    let! a = Success 1
    let! b = Success "foo"
    let! c = Success true
    return
        {
                a = a
                b = b
                c = c
        }
}

let fail1 = either("Fail1") {
    let! a = Success 1
    let! b = Failure ["Oh nose!"]
    let! c = Success true
    return
        {
                a = a
                b = b
                c = c
        }
} //returns fail1 = Failure ["Fail1"; "Oh nose!"]

let fail2 = either("Fail2") {
    let! a = Success 1
    let! b = Failure ["Oh nose!"]
    let! c = Failure ["God damn it, uncle Bob!"]
    return
        {
                a = a
                b = b
                c = c
        }
} //should return fail2 = Failure ["Fail2"; "Oh nose!"; "God damn it, uncle Bob!"]

A: As @tomasp is saying one approach is to always provide a value in addition to the failures in order to make bind work properly. This is the approach I have been using when dealing with this subject. I would then change the definition of Result to, for example, this:
type BadCause =
  | Exception of exn
  | Message   of string

type BadTree =
  | Empty
  | Leaf  of BadCause
  | Fork  of BadTree*BadTree

type [<Struct>] Result<'T> = Result of 'T*BadTree

This means that a Result always has a value whether it's good or bad. The value is good iff the BadTree is empty.
The reason I prefer trees over list is that Bind will aggregate two separate results that may have subfailures leading to list concatenations.
Some functions that let us create either good or bad value:
let rreturn     v       = Result (v, Empty)
let rbad        bv bt   = Result (bv, bt)
let rfailwith   bv msg  = rbad bv (Message msg |> Leaf)

Because even bad results need to carry a value in order to make Bind work we need to provide the value through bv parameter. For types that support Zero we can create a convinience method:
let inline rfailwithz  msg  = rfailwith LanguagePrimitives.GenericZero<_> msg

Bind is easy to implement:
let rbind (Result (tv, tbt)) uf =
  let (Result (uv, ubt)) = uf tv
  Result (uv, btjoin tbt ubt)

That is; we evaluate both results and join the bad trees if needed.
With a computation expression builder the following program:
  let r =
    result {
      let! a = rreturn    1
      let! b = rfailwithz "Oh nose!"
      let! c = rfailwithz "God damn it, uncle Bob!"
      return a + b + c
    }

  printfn "%A" r

Outputs:

Result (1,Fork (Leaf (Message "Oh nose!"),Leaf (Message "God damn it, uncle Bob!")))

That is; we get a bad value 1 and the reasons it's bad is because of the two joined error leafs.
I have used this approach when transforming and validating tree structures using composable combinators. It's in my case important to get all validation failure, not just the first. This means that both branches in Bind needs to be evaluated but in order to do we must always have a value in order to call uf in Bind t uf.
As in OP:s own answer I did experiment with Unchecked.defaultof<_> but I abandoned for example because the default value of a string is null and it usually leads to crashes when invoking uf. I did create a map Type -> empty value but in my final solution I require a bad value when constructing a bad result.
Hope this helps
Full example:
type BadCause =
  | Exception of exn
  | Message   of string

type BadTree =
  | Empty
  | Leaf  of BadCause
  | Fork  of BadTree*BadTree

type [<Struct>] Result<'T> = Result of 'T*BadTree

let (|Good|Bad|) (Result (v, bt)) =
  let ra = ResizeArray 16
  let rec loop bt =
    match bt with
    | Empty         -> ()
    | Leaf  bc      -> ra.Add bc |> ignore
    | Fork  (l, r)  -> loop l; loop r
  loop bt
  if ra.Count = 0 then
    Good v
  else
    Bad (ra.ToArray ())

module Result =
  let btjoin      l  r    =
    match l, r with
    | Empty , _     -> r
    | _     , Empty -> l
    | _     , _     -> Fork (l, r)

  let rreturn     v       = Result (v, Empty)
  let rbad        bv bt   = Result (bv, bt)
  let rfailwith   bv msg  = rbad bv (Message msg |> Leaf)

  let inline rfailwithz  msg  = rfailwith LanguagePrimitives.GenericZero<_> msg

  let rbind (Result (tv, tbt)) uf =
    let (Result (uv, ubt)) = uf tv
    Result (uv, btjoin tbt ubt)

  type ResultBuilder () =
    member x.Bind         (t, uf) = rbind t uf
    member x.Return       v       = rreturn v
    member x.ReturnFrom   r       = r : Result<_>

let result = Result.ResultBuilder ()

open Result

[<EntryPoint>]
let main argv =
  let r =
    result {
      let! a = rreturn    1
      let! b = rfailwithz "Oh nose!"
      let! c = rfailwithz "God damn it, uncle Bob!"
      return a + b + c
    }

  match r with
  | Good v  -> printfn "Good: %A" v
  | Bad  es -> printfn "Bad: %A" es

  0

A: We now have applicative computation expressions  with and! and MergeSources in the builder.
See this for a solution


text:
Q: Hide column on smaller screens only with Bootstrap 4 I am trying to create a grid to cover the full screen with 3 columns (left, middle, right)

*

*Left: This column should only show up on large views and should be 16.6% of the screen (2/12)

*Middle: This column should always show up. it should cover 75% (9/12) of the screen on <= mid-size view. And 66.6% (8/12) on large views

*Right: This column should always show up. It should cover 16.6% (2/12) of the width on large view and 25% 3/12 on <= mid-size view

Here is my html markup

LEFT

This column should only show up on large views and should be 16.6% of the screen (2/12)

MIDDLE

This column should always show up. it should cover 75% (9/12) of the screen on <= mid-size view. And 66.6% (8/12) on a large views

RIGHT

This column should always show up. It should cover 16.6% (2/12) of the width on large view and 25% 3/12 on <= mid-size view

Here is a codeply with my code https://www.codeply.com/go/LRlYKLav32
The class d-md-none does not appear to be working correctly. I am expecting the column to be hidden when the view is small but should be visible on larger views.
How can I correct this issue?

A: As explained in Missing visible-** and hidden-** in Bootstrap v4...
If you want the LEFT on lg and up, it would be: d-none d-lg-block.
If you want the LEFT on lg only it would be: d-none d-lg-block d-xl-none

LEFT

This column should only show up on large views and should be 16.6% of the screen (2/12)

MIDDLE

This column should always show up. it should cover 75% (9/12) of the screen on <= mid-size view. And 66.6% (8/12) on a large views

RIGHT

This column should always show up. It should cover 16.6% (2/12) of the width on large view and 25% 3/12 on <= mid-size view

https://www.codeply.com/go/PrAVeQSgb4


text:
Q: C# WinForms - SQL Server CE - SqlCeDataReader loses its data? I am trying to copy data from SQL Server database to SQL Server CE local database.
Here is my method :
private const string LOCAL_SDF_FILE = "LocalDB.sdf";
private const string LOCAL_CONN_STRING = "Data Source='|DataDirectory|LocalDB.sdf'; LCID=1033; Password=3C670F044A; Encrypt=TRUE;";
private const string SOURCE_CONN_STRING = "Data Source=SQL\\SERVER;Initial Catalog=DB;Integrated Security=True;Pooling=False";

public static void CreateDB()
{
        if (File.Exists(LOCAL_SDF_FILE))
        {
            File.Delete(LOCAL_SDF_FILE);
        }

        SqlCeEngine engine = new SqlCeEngine(LOCAL_CONN_STRING);
        engine.CreateDatabase();
        engine.Dispose();

        SqlCeConnection localCnx = null;

        try
        {
            localCnx = new SqlCeConnection(LOCAL_CONN_STRING);
            localCnx.Open();

            SqlCeCommand localCmd = localCnx.CreateCommand();

            #region CREATE TABLE t_TypeConfig
            localCmd.CommandText = @"CREATE TABLE t_TypeConfig(
                                        TypeConfig_ID int IDENTITY(1,1) NOT NULL,
                                        TypeConfig_Name nvarchar(50) NOT NULL,
                                        TypeConfig_IsVisible bit NOT NULL,
                                        CONSTRAINT pk_TypeConfigID PRIMARY KEY (TypeConfig_ID)
                                    )";

            localCmd.ExecuteNonQuery();
            #endregion

            using (SqlConnection sourceCnx = new SqlConnection(SOURCE_CONN_STRING))
            {
                try
                {
                    sourceCnx.Open();

                    SqlCommand SourceCmd = sourceCnx.CreateCommand();
                    SourceCmd.CommandText = "SELECT * FROM t_TypeConfig";
                    SqlDataReader reader = SourceCmd.ExecuteReader();

                    using (SqlCeBulkCopy bulkCopy = new SqlCeBulkCopy(LOCAL_CONN_STRING))
                    {
                        bulkCopy.DestinationTableName = "t_TypeConfig";

                        try
                        {
                            // Write from the source (DB server) to the destination (local wibe)
                            bulkCopy.WriteToServer(reader);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "An error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            reader.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "An error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    sourceCnx.Close();
                }
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString(), "An error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            localCnx.Close();
        }
    }

*

*Create SQL Server CE file and sample table (t_TypeConfig) -> ok.

*Get data into reader from SQL Server connection -> ok.

But when I want to fill, via SqlCeBulkCopy, my local database table with the reader I just filled previously, I see via Visual Studio watcher that reader does not contain the data anymore !
I don't know why. Still looking for a solution but I don't understand ? Maybe because the using ?
I also tried to convert the SqlDataReader into a SqlCeDataReader variable to give in SqlCeBulkCopy.WriteToServer() parameter but it cannot convert from one to other.
Any ideas?
Thanks a lot,
Hellcat.

A: Okay so the solution is, thanks to guys in comments, to give as parameter to SqlCeBulkCopy.WriteToServer() a DataTable instead of a SqlDataReader or IDataReader.
It works for me right now.
Added this :
SqlDataReader reader = SourceCmd.ExecuteReader();
DataTable SqlDatatable = new DataTable();
SqlDatatable.Load(reader);

Then :
bulkCopy.WriteToServer(SqlDatatable);

Thanks guys.


text:
Q: Syntax help for using bitwise to removing decimals in javascript trying to format variables as they get updated. I would like to do this by using the bitwise operators.  I cant seem to understadn the syntax.
Currently the numbers come in like 5.2342340990843  at max i would love them to be 2 decimals deep max.
example code
var app = angular.module('morningharwoodApp', []);
app.controller('MainCtrl', function ($scope, $window) {
    $scope.squares = [1,2,3,4,5,6,7,8];
    if ($window.DeviceMotionEvent != undefined) {
    $window.ondevicemotion = function(event) {
    //wan tto make this a 32bit integer by using pipe 0 however it's erroring out
      $scope.acceleration = {
        x: event.accelerationIncludingGravity.x*10 | 0,
        y: event.accelerationIncludingGravity.y*10 | 0,
        z: event.accelerationIncludingGravity.z*10 | 0
      };

      $scope.$digest();

    };
  }
});

Html:

X : {{acceleration.x}}

Y : {{acceleration.y}}

Z : {{acceleration.z}}

A: Why use bitwise operators, there is a method toFixed that does this. It allows you to specify the number of digits after the decimal
var d = 5.231579843214564;
var fixed = d.toFixed(2);
console.log(fixed);
//outputs: 5.23

Note this creates a string representation, if you want it back to a number instead of a string jst prepend a + operator to the front
var fixed = +d.toFixed(2);


text:
Q: How to Implement Search within WebGrid (Razor/C#) I'm reading over MSDN: http://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid.webgrid(v=VS.99).aspx about the WebGrid - but I can see that there seems to be no search functionality provided with it.
How can we add this functionality to the WebGrid?

A: Could you have a form that searches the server and just re-renders the WebGrid in a partial view with only the search results showing?


text:
Q: Maven compiler plugin isn't calling javac Running Maven from inside Eclipse or from command line, it does not run javac.  All test and main sources are in default paths src/main/java, src/test/java, src/main/resources, nothing is custom.
It used to compile as well as run my tests, then at some point it just stopped.  Eclipse still compiles the classes if I do project clean, but Maven by itself compiles nothing, and then tests nothing as it also doesn't compile the tests.  I have tried forcing includes of **/*.java (which should be redundant), but did nothing.
Running Maven with -X, it builds the classpath etc, then I see this (I assume here I would see it compile something):
[DEBUG] incrementalBuildHelper#beforeRebuildExecution
[INFO] Compiling 47 source files to E:\eclipse\osm-test-tool-java\Bell\target\classes
[DEBUG] incrementalBuildHelper#afterRebuildExecution

After some investigation, I discovered that it was this in my POM file that is causing the issue:
<dependency>
    <groupId>com.bell</groupId>
    <artifactId>BigDependencies</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

If I take the Maven classpath and compile with this, using javac directly with -X (verbose), it does not compile the classes.  If I remove the jar above, it compiles (fails because of missing artifacts, but at least it tries). What is this dependency? I have a big shaded jar of all of my external dependencies, the goal being to deploy it once, then be able to do application updates by deploying a much smaller jar. No idea why the shaded jar is making the compiler not function; I'm trying to find a way around it.

A: After some more research on shading jars, I made the executive decision to stop using a shaded dependency jar; instead made an assembly step that puts all dependent jars in a libs directory and just deploy the libs directory once (whenever it changes, which is rare) and deploy the small app jar alongside it.  Presto, everything works.
Moral of the story is avoid shaded jars, they are fraught with problems (stripping out conflicting manifest information, class loader issues, multiple version conflicts, shading other shaded jars....)


text:
Q: List all files, recursively, in Android Dropbox API How can I list all files, recursively in DropBox folder?
I tried code below but returns no result:
result = dbxClient.files().search("", "*");

And this returns files in path, not subfolders:
result = dbxClient.files().listFolder(path);

A: You can get a ListFolderBuilder from listFolderBuilder and use the withRecursive option to list out sub-items as well.
Be sure to check ListFolderResult.hasMore to see if you should call back to listFolderContinue to get more results though.

A: You can check this link, navigate to inner class 'FolderScanTask'. It contains working code for Android:
https://github.com/ControlX/Android-Dropbox-UploadImage-To-SpecificFolder-By-FolderSelection/blob/master/app/src/main/java/io/github/controlx/dbxdemo/MainActivity.java
This is work in progress, here I'm just making an ArrayList for parent folders, has more logic as suggested by Greg is already there you just need to fill in that.
Code Snippet for the same:
        String path = "";
        DbxClientV2 dbxClient = DropboxClient.getClient(ACCESS_TOKEN);
        TreeMap<String, Metadata> children = new TreeMap<String, Metadata>();

        try {
            try {
                result = dbxClient.files()
                        .listFolder(path);
            } catch (ListFolderErrorException ex) {
                ex.printStackTrace();
            }

            List<Metadata> list = result.getEntries();
            cs = new CharSequence[list.size()];
            arrayList = new ArrayList<>();
            arrayList.add("/");
            while (true) {
                int i = 0;
                for (Metadata md : result.getEntries()) {
                    if (md instanceof DeletedMetadata) {
                        children.remove(md.getPathLower());
                    } else {
                        String fileOrFolder = md.getPathLower();
                        children.put(fileOrFolder, md);
                        if(!fileOrFolder.contains("."))
                            arrayList.add(fileOrFolder);
                    }
                    i++;
                }

                if (!result.getHasMore()) break;

                try {
                    result = dbxClient.files()
                            .listFolderContinue(result.getCursor());
                } catch (ListFolderContinueErrorException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (DbxException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

Here ArrayList is just for my use wherein I'm just making a list of only folders.
So, modify accordingly.


text:
Q: how to handle ajax request on success or failer i just have a small problem with jquery
http://jsfiddle.net/XGM67/
when i click on vote i send data to server
server sends response 1 on success 0 on failure
how ever if i refresh the page and and click on vote -
the target.html('Voted').addClass('voted'); is applyed again
i want that to show up only one time if any voted link has been clicked - i mean the class dose not applied to the rest of voted links
i just don't know how to handle that - any help please - thank you in advanced
$(document).ready(function() {
 $("#container .bar a").click(function(e) {

   // e.preventDefault();

   var target = $(this);

   $('span a').removeAttr('href');

   $('span a').off('click');

   var id = $(this).attr('id');

   var ip = '<?php echo ipAddress(); ?>';

    $.ajax({

      url: 'listener.php',

      data:'id='+ id +'&ip=' + ip,

      success: function( response ){

       // here every thing is working
       $('#msg').show(400);

       $('span a').removeAttr('href');

        $('span a').off('click');

         target.html('Voted').addClass('voted');

      }
    });

        return false;
    });
});


text:
Q: Extract data from a two columned listbox to a sheet I have a two-columned listbox, which I've manually added entries to using
.AddItem (potato)
.List(.ListCount - 1, 1) = bananaTbx.Text

When the user closes the userform all of the data is lost, so I want to have a save & exit button which saves the data to a sheet.  However, it can't be saved to specific cells as the size of the list is dynamic and they will continually be adding to the master list in the sheet.
I tried to do something like this to extract the data:
Dim i As Integer

'loop through each row number in the list
For i = 0 To Userform1.Listbox1.ListCount - 1
    'create sequence 1,1,2,2,3,3,4,4 ... to reference the current list row
    j = Application.WorksheetFunction.RoundDown(i + 0.5, 0)
    'create sequence 0,1,0,1,0,1,0,1 ... to reference current column in list
    If Len(CStr(i / 2)) > 1 Then
        k = 0
    Else
        k = 1
        Sheets("Data").Range("A1" & ":" & "A" & i).Value = Userform1.ListBox1.List(j, k)
    End If

Error:
1004 Object defined error

How can I do this properly or in a more efficient manner?

A: I have created a simple userform to demonstrate how to Extract Values / Data from a multi-column Listbox on a Userform
Start by creating a simple userform with a few controls

add a new Module1 to your Project and stick the below code in it
Sub TestUserForm()
    UserForm1.Show
    Unload UserForm1
End Sub

in Project Explorer (VBE) Right-click on the UserForm1 and hit View Code
Copy and paste the below code
Private Sub CommandButton1_Click()

    With ListBox1
        .AddItem TextBox1.Value
        .List(.ListCount - 1, 1) = TextBox2.Value
    End With

End Sub

Private Sub CommandButton2_Click()

    Dim ws As Worksheet
    ' create a results sheets if you do not already have one
    Set ws = Sheets("Results")

    Dim nextAvailableRow As Long
    Dim i As Long
    For i = 0 To ListBox1.ListCount - 1
        nextAvailableRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
        ws.Range("A" & nextAvailableRow) = ListBox1.Column(0, i)
        ws.Range("B" & nextAvailableRow) = ListBox1.Column(1, i)
    Next i

    Me.Hide
End Sub

Create a new spreadsheet and name it Results
Run the TestUserForm macro
Add sample data to the list and click Save button


text:
Q: How to read ASP.NET Core Response.Body? I've been struggling to get the Response.Body property from an ASP.NET Core action and the only solution I've been able to identify seems sub-optimal.  The solution requires swapping out Response.Body with a MemoryStream while reading the stream into a string variable, then swapping it back before sending to the client.  In the examples below, I'm trying to get the Response.Body value in a custom middleware class.  Response.Body is a set only property in ASP.NET Core for some reason?  Am I just missing something here, or is this an oversight/bug/design issue?  Is there a better way to read Response.Body?
Current (sub-optimal) solution:
public class MyMiddleWare
{
    private readonly RequestDelegate _next;

    public MyMiddleWare(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        using (var swapStream = new MemoryStream())
        {
            var originalResponseBody = context.Response.Body;

            context.Response.Body = swapStream;

            await _next(context);

            swapStream.Seek(0, SeekOrigin.Begin);
            string responseBody = new StreamReader(swapStream).ReadToEnd();
            swapStream.Seek(0, SeekOrigin.Begin);

            await swapStream.CopyToAsync(originalResponseBody);
            context.Response.Body = originalResponseBody;
        }
    }
}

Attempted solution using EnableRewind():
This only works for Request.Body, not Response.Body.  This results in reading an empty string from Response.Body rather than the actual response body contents.
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifeTime)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.Use(async (context, next) => {
        context.Request.EnableRewind();
        await next();
    });

    app.UseMyMiddleWare();

    app.UseMvc();

    // Dispose of Autofac container on application stop
    appLifeTime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
}

MyMiddleWare.cs
public class MyMiddleWare
{
    private readonly RequestDelegate _next;

    public MyMiddleWare(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await _next(context);
        string responseBody = new StreamReader(context.Request.Body).ReadToEnd(); //responseBody is ""
        context.Request.Body.Position = 0;
    }
}

A: What you describe as a hack is actually the suggested approach of how to manage response streams in custom middleware.
Because of the pipeline nature of the middle ware design where each middle ware is unaware of the previous or next handler in the pipeline. There is no guarantee that the current middle ware would be the one writing the response unless it holds on to the response stream it was given before passing on a stream that it (the current middle ware) controls. This design was seen in OWIN and eventually baked into asp.net-core.
Once you start writing to the response stream it sends the body and headers (the response) to the client. If another handler down the pipeline does that before the current handler had a chance to then it wont be able to add anything to the response once it has been already sent.
Which again is not guaranteed to be the actual response stream if the previous middleware in the pipeline followed the same strategy of passing another stream down the line.
Referencing ASP.NET Core Middleware Fundamentals

Warning
Be careful modifying the HttpResponse after invoking next, because the
  response may have already been sent to the client. You can use
  HttpResponse.HasStarted to check whether the headers have been sent.
Warning
Do not call next.Invoke after calling a write method. A middleware
  component either produces a response or calls next.Invoke, but not
  both.

Example of built in basic middlewares from aspnet/BasicMiddleware Github repo
ResponseCompressionMiddleware.cs
/// <summary>
/// Invoke the middleware.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
    if (!_provider.CheckRequestAcceptsCompression(context))
    {
        await _next(context);
        return;
    }

    var bodyStream = context.Response.Body;
    var originalBufferFeature = context.Features.Get<IHttpBufferingFeature>();
    var originalSendFileFeature = context.Features.Get<IHttpSendFileFeature>();

    var bodyWrapperStream = new BodyWrapperStream(context, bodyStream, _provider,
        originalBufferFeature, originalSendFileFeature);
    context.Response.Body = bodyWrapperStream;
    context.Features.Set<IHttpBufferingFeature>(bodyWrapperStream);
    if (originalSendFileFeature != null)
    {
        context.Features.Set<IHttpSendFileFeature>(bodyWrapperStream);
    }

    try
    {
        await _next(context);
        // This is not disposed via a using statement because we don't want to flush the compression buffer for unhandled exceptions,
        // that may cause secondary exceptions.
        bodyWrapperStream.Dispose();
    }
    finally
    {
        context.Response.Body = bodyStream;
        context.Features.Set(originalBufferFeature);
        if (originalSendFileFeature != null)
        {
            context.Features.Set(originalSendFileFeature);
        }
    }
}

A: @RonC's answer works for the most part. But I wanted to add this. It seems that ASP.NET Core does not like to present the web contents directly from the memory stream (unless it's a simple string and not a whole HTML page). I spent hours trying to figure this one out, so I wanted to post it here so that other people wouldn't waste their time trying to figure this one out as I did.
Here is the little modification of @RonC's answer about the response part:
public class ResponseBufferMiddleware
{
    private readonly RequestDelegate _next;

    public ResponseBufferMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Store the original body stream for restoring the response body back to its original stream
        var originalBodyStream = context.Response.Body;

        // Create new memory stream for reading the response; Response body streams are write-only, therefore memory stream is needed here to read
        await using var memoryStream = new MemoryStream();
        context.Response.Body = memoryStream;

        // Call the next middleware
        await _next(context);

        // Set stream pointer position to 0 before reading
        memoryStream.Seek(0, SeekOrigin.Begin);

        // Read the body from the stream
        var responseBodyText = await new StreamReader(memoryStream).ReadToEndAsync();

        // Reset the position to 0 after reading
        memoryStream.Seek(0, SeekOrigin.Begin);

        // Do this last, that way you can ensure that the end results end up in the response.
        // (This resulting response may come either from the redirected route or other special routes if you have any redirection/re-execution involved in the middleware.)
        // This is very necessary. ASP.NET doesn't seem to like presenting the contents from the memory stream.
        // Therefore, the original stream provided by the ASP.NET Core engine needs to be swapped back.
        // Then write back from the previous memory stream to this original stream.
        // (The content is written in the memory stream at this point; it's just that the ASP.NET engine refuses to present the contents from the memory stream.)
        context.Response.Body = originalBodyStream;
        await context.Response.Body.WriteAsync(memoryStream.ToArray());

        // Per @Necip Sunmaz's recommendation this also works:
        // Just make sure that the memoryStrream's pointer position is set back to 0 again.
        // await memoryStream.CopyToAsync(originalBodyStream);
        // context.Response.Body = originalBodyStream;
    }
}

This way, you can present the web contents properly but also read the response body if you need to. This has been thoroughly been tested.
Also, note that this code is written using .NET Core 3.1 and the C# language version 8.0.
@DalmTo confirmed that this code works with .NET 5 and C# 9.

A: In ASP.NET Core 3, the story is even worse: Even if you ignore the fact that we are talking about a web framework that has turned something as fundamental as reading web requests into a struggle with unintuitive workarounds and an API that changes between every version, then there's an open issue which means that if you use EnableBuffering "too late" (including late in your middleware pipeline), it won't do anything.
In my case, I used the hacky solution of adding the body to HttpContext.Items as early in the pipeline as possible. I'm sure this is awfully inefficient, and it ignores the sort of issues that arise when the body is large, but if you're looking for something off-the-shelf (as I was when I came across this question), then maybe this is helpful.
Concretely, I use the following middleware:
    public class RequestBodyStoringMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestBodyStoringMiddleware(RequestDelegate next) =>
            _next = next;

        public async Task Invoke(HttpContext httpContext)
        {
            httpContext.Request.EnableBuffering();
            string body;
            using (var streamReader = new System.IO.StreamReader(
                httpContext.Request.Body, System.Text.Encoding.UTF8, leaveOpen: true))
                body = await streamReader.ReadToEndAsync();

            httpContext.Request.Body.Position = 0;

            httpContext.Items["body"] = body;
            await _next(httpContext);
        }
    }

To use this, do a app.UseMiddleware<RequestBodyStoringMiddleware>(); as early as possible in Startup.Configure; the issue is that depending on what else you're doing, the body stream might end up being consumed along the way, so the order matters. Then, when you need the body later (in the controller, or another piece of middleware), access it through (string)HttpContext.Items["body"];. Yes, your controllers now rely on implementation details of your configuration but what can you do.

A: You can use a middleware
in the request pipeline, in order to log request and responses.
However is increased the hazard of memory leak, due to the facth that:
1. Streams,
2. Setting Byte Buffers and
3. String conversions
can end up to Large Object Heap (in case the body of request or response is larger than 85,000 bytes). This increases the hazard of memory leak in your application.
 In order to avoid LOH, memory streams can be replaced by Recyclable Memory stream using the relevant library.
An implementation that uses Recyclable memory streams:
public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
    private const int ReadChunkBufferLength = 4096;

    public RequestResponseLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory
            .CreateLogger<RequestResponseLoggingMiddleware>();
        _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
    }

    public async Task Invoke(HttpContext context)
    {
        LogRequest(context.Request);
        await LogResponseAsync(context);
    }

    private void LogRequest(HttpRequest request)
    {
        request.EnableRewind();
        using (var requestStream = _recyclableMemoryStreamManager.GetStream())
        {
            request.Body.CopyTo(requestStream);
            _logger.LogInformation($"Http Request Information:{Environment.NewLine}" +
                                   $"Schema:{request.Scheme} " +
                                   $"Host: {request.Host} " +
                                   $"Path: {request.Path} " +
                                   $"QueryString: {request.QueryString} " +
                                   $"Request Body: {ReadStreamInChunks(requestStream)}");
        }
    }

    private async Task LogResponseAsync(HttpContext context)
    {
        var originalBody = context.Response.Body;
        using (var responseStream = _recyclableMemoryStreamManager.GetStream())
        {
            context.Response.Body = responseStream;
            await _next.Invoke(context);
            await responseStream.CopyToAsync(originalBody);
            _logger.LogInformation($"Http Response Information:{Environment.NewLine}" +
                                   $"Schema:{context.Request.Scheme} " +
                                   $"Host: {context.Request.Host} " +
                                   $"Path: {context.Request.Path} " +
                                   $"QueryString: {context.Request.QueryString} " +
                                   $"Response Body: {ReadStreamInChunks(responseStream)}");
        }

        context.Response.Body = originalBody;
    }

    private static string ReadStreamInChunks(Stream stream)
    {
        stream.Seek(0, SeekOrigin.Begin);
        string result;
        using (var textWriter = new StringWriter())
        using (var reader = new StreamReader(stream))
        {
            var readChunk = new char[ReadChunkBufferLength];
            int readChunkLength;
            //do while: is useful for the last iteration in case readChunkLength < chunkLength
            do
            {
                readChunkLength = reader.ReadBlock(readChunk, 0, ReadChunkBufferLength);
                textWriter.Write(readChunk, 0, readChunkLength);
            } while (readChunkLength > 0);

            result = textWriter.ToString();
        }

        return result;
    }
}

NB. The hazard of LOH is not fully eradicate due to textWriter.ToString() on the other hand you can use a logging client library that supports structured logging (ie. Serilog) and inject the instance of a Recyclable Memory Stream.

A: In my original response I had totally misread the question and thought the poster was asking how to read the Request.Body But he had asked how to read the Response.Body.   I'm leaving my original answer to preserve history but also updating it to show how I would answer the question once reading it correctly.
Original Answer
If you want a buffered stream that supports reading multiple times you need to set
   context.Request.EnableRewind()

Ideally do this early in the middleware before anything needs to read the body.
So for example you could place the following code in the beginning of the Configure method of the Startup.cs file:
        app.Use(async (context, next) => {
            context.Request.EnableRewind();
            await next();
        });

Prior to enabling Rewind the stream associated with the Request.Body is a forward only stream that doesn't support seeking or reading the stream a second time.  This was done to make the default configuration of request handling as lightweight and performant as possible.  But once you enable rewind the stream is upgrade to a stream that supports seeking and reading multiple times.  You can observe this "upgrade" by setting a breakpoint just before and just after the call to EnableRewind and observing the Request.Body properties.  So for example Request.Body.CanSeek will change from false to true.
update: Starting in ASP.NET Core 2.1 Request.EnableBuffering() is available which upgrades the Request.Body to a FileBufferingReadStream just like Request.EnableRewind() and since Request.EnableBuffering() is in a public namespace rather than an internal one it should be preferred over EnableRewind().  (Thanks to @ArjanEinbu for pointing out)
Then to read the body stream you could for example do this:
   string bodyContent = new StreamReader(Request.Body).ReadToEnd();

Don't wrap the StreamReader creation in a using statement though or it will close the underlying body stream at the conclusion of the using block and code later in the request lifecycle wont be able to read the body.
Also just to be safe, it might be a good idea to follow the above line of code that reads the body content with this line of code to reset the body's stream position back to 0.
request.Body.Position = 0;

That way any code later in the request lifecycle will find the request.Body in a state just like it hasn't been read yet.
Updated Answer
Sorry I originally misread your question. The concept of upgrading the associated stream to be a buffered stream still applies. However you do have to do it manually, I'm unaware of any built in .Net Core functionality that lets you read the response stream once written in the way that EnableRewind() lets a developer reread the request stream after it's been read.
Your "hacky" approach is likely totally appropriate. You are basically converting a stream that can't seek to one that can.  At the end of the day the Response.Body stream has to get swapped out with a stream that is buffered and supports seeking.  Here is another take on middleware to do that but you will notice it's quite similar to your approach.  I did however choose to use a finally block as added protection for putting the original stream back on the Response.Body and I used the Position property of the stream rather than the Seek method since the syntax is a bit simpler but the effect is no different than your approach.
public class ResponseRewindMiddleware
{
        private readonly RequestDelegate next;

        public ResponseRewindMiddleware(RequestDelegate next) {
            this.next = next;
        }

        public async Task Invoke(HttpContext context) {

            Stream originalBody = context.Response.Body;

            try {
                using (var memStream = new MemoryStream()) {
                    context.Response.Body = memStream;

                    await next(context);

                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }

            } finally {
                context.Response.Body = originalBody;
            }

        }
}

A: .NET 6.0+ Solution
In ASP.NET Core 6.0+ consider using a built-in extensions:
var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.AddHttpLogging(options => // <--- Setup logging
{
    // Specify all that you need here:
    options.LoggingFields = HttpLoggingFields.RequestHeaders |
                            HttpLoggingFields.RequestBody |
                            HttpLoggingFields.ResponseHeaders |
                            HttpLoggingFields.ResponseBody;
});
//...
var app = builder.Build();
//...
app.UseHttpLogging(); // <--- Add logging to pipeline
//...
app.Run();


text:
Q: Passing dict to constructor? I'd like to pass a dict to an object's constructor for use as kwargs.
Obviously:
foo = SomeClass(mydict)

Simply passes a single argument, rather than the dict's contents. Alas:
foo = SomeClass(kwargs=mydict)

Which seems more sensible doesn't work either. What am I missing?

A: Use :
foo = SomeClass(**mydict)

this will unpack the dict value and pass them to the function.
For example:
mydict = {'a': 1, 'b': 2}

SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)

A: To pass a dictionary to a constructor you have to do so by reference, which is by preceding it with **, like so:
foo = SomeClass(**mydict)

A: Try this:
SomeClass(**mydict)


text:
Q: Android Sqlite: Is there a way to control the number of duplicates cols you get within a single query? I have a table of books when each book contains tag and a name. Now I want to get 10 different books for each tag. I thought about using distinct or group by, but this removes all the duplicates. Does anyone know of a method to control the number of duplicates?
ID   NAME   TAG
-----------------------
1    GREEN  adventures
2    RED    adventures
3    YELLOW love
4    BLACK  adventures
5    WHITE  love
6    PURPLE Fantasy

Results for 2 copies of the same tag:
ID   NAME   TAG
-----------------------
1    GREEN  adventures
3    YELLOW love
4    BLACK  adventures
5    WHITE  love
6    PURPLE Fantasy

A: With ROW_NUMBER() window function:
select b.id, b.name, b.tag
from (
  select *, row_number() over (partition by tag order by random()) rn
  from books
) b
where b.rn <= 10

This will return 10 random books for each tag.
If you want the 10 first books by id then change:
order by random()

to:
order by id

See the demo.
Or for older versions of SQLite which do not support window functions:
select b.id, b.name, b.tag
from (
  select b.*, (select count(*) from books where tag = b.tag and id <= b.id) rn
  from books b
) b
where b.rn <= 10

See the demo.


text:
Q: OnLocationStateChange cordova application crashes The application i am working is basically fetches users location using cordova geolocation plugin, and then show the location on the google maps.
The problem i'm facing is that when i kill the app and turn off/on the location services from settings the application crashes.

java.lang.RuntimeException: Unable to start receiver cordova.plugins.Diagnostic$LocationProviderChangedReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void cordova.plugins.Diagnostic.notifyLocationStateChange()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void cordova.plugins.Diagnostic.notifyLocationStateChange()' on a null object reference

this is the screen shot of error that i got after running the app directly from Android studio
I'm using diagnostic plugin as well because i'm testing app on API 23 i-e Marshmallow, that needs run time permissions. if i remove diagnostic plugin the app crashes as soon as it starts on Marshmallow.
The app runs on API's below 23 and also it does not crashes when i turn location services On/Off.
Advices/Suggestions are welcomed.

A: This is noted as issue #85 in the plugin repo and is resolved by patch release cordova.plugins.diagnostic@3.0.4:
$ cordova plugin rm cordova.plugins.diagnostic &&
  cordova plugin add cordova.plugins.diagnostic@latest


text:
Q: flask-appbuilder select record to filter another view I use Flask-appbuilder 4.1.1. I'd like to define an action in MyViewA (I followed this doc ) to filter another view MyViewB. To create the filter i used this other
models.py example
class TableA(Model):
   id = db.Column(db.Integer, primary_key=True)
   name = db.Column(db.String(100))

class TableB(Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(100))
  id_a = db.Column(db.ForeignKey('tablea.id'), index=True)

  tablea = relationship('TableA', primaryjoin='TableB.id_a == TableA.id')

I need to create a view of TableA with an action on record selection that redirect on the view of TableB with a filter like
base_filters = [['id_a',FilterEqual, THE_ID_OF_THE_RECORD_SELECTED],]

Thanks in advance
Thanks in advance


text:
Q: Line color between cells in selected row (TableView) I set the color of the selected row using css (JavaFX):
.table-row-cell:selected {
    -fx-background-color: lightgray ;
}

I also set the color of some other rows using css pseudo classes:
.table-row-cell:redRow {
    -fx-background-color: orangered ;
}
.table-row-cell:aquaRow {
    -fx-background-color: aqua ;
}

The result is shown in the picture:

For unselected rows, the vertical lines between cells are white.
The problem is that the selected row has vertical lines that still blue.
How to change the color of these vertical lines to white ? (so that the filled rows differ only in the background color)
P.S. Selected row in the picture is gray

Here is a simpler working example of an application with a similar result:
Main class:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TableTest extends Application{

    @Override
    public void start(Stage primaryStage) {
        try {

            ObservableList<PrimitiveModel> variableList = FXCollections.<PrimitiveModel>observableArrayList();
            for (int i = 0; i < 5; i++) {
                variableList.add(new PrimitiveModel(i, i*2.5, Integer.toString(i*3)));
            }

            TableView<PrimitiveModel> myTable = new TableView<PrimitiveModel>(variableList);
            myTable.getColumns().addAll(getIntegerColumn(), getDoubleColumn(), getStringColumn());
            myTable.setPrefSize(400.0, 300.0);

            PseudoClass redRowPseudoClass = PseudoClass.getPseudoClass("redRow");
            PseudoClass aquaRowPseudoClass = PseudoClass.getPseudoClass("aquaRow");

            myTable.setRowFactory( table ->{
                TableRow<PrimitiveModel> row = new TableRow<>();

                row.itemProperty().addListener(new ChangeListener<PrimitiveModel>() {
                    @Override
                    public void changed(ObservableValue<? extends PrimitiveModel> observable, PrimitiveModel oldValue,
                            PrimitiveModel newValue) {
                        if(oldValue!=null) {
                            if(oldValue.getInteger()%2==0) {
                                row.pseudoClassStateChanged(redRowPseudoClass, false);
                            }else {
                                row.pseudoClassStateChanged(aquaRowPseudoClass, false);
                            }
                        }

                        if(newValue!=null) {
                            if(newValue.getInteger()%2==0) {
                                row.pseudoClassStateChanged(redRowPseudoClass, true);
                            }else {
                                row.pseudoClassStateChanged(aquaRowPseudoClass, true);
                            }
                        }
                    }
                });

                row.selectedProperty().addListener(new ChangeListener<Boolean>() {
                    @Override
                    public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                        if(row.getItem()!=null) {
                            if (newValue) {
                                if(row.getItem().getInteger()%2==0) {
                                    row.pseudoClassStateChanged(redRowPseudoClass, false);
                                }else {
                                    row.pseudoClassStateChanged(aquaRowPseudoClass, false);
                                }
                            } else {
                                if(row.getItem().getInteger()%2==0) {
                                    row.pseudoClassStateChanged(redRowPseudoClass, true);
                                }else {
                                    row.pseudoClassStateChanged(aquaRowPseudoClass, true);
                                }
                            }
                        }

                    }
                });
                return row;
            });

            VBox root = new VBox(myTable);
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("TableStyle.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

    public static TableColumn<PrimitiveModel, Integer> getIntegerColumn() {
        TableColumn<PrimitiveModel, Integer> integerCol = new TableColumn<PrimitiveModel, Integer>("Integer");
        integerCol.setCellValueFactory(new PropertyValueFactory<PrimitiveModel, Integer>("integer"));
        return integerCol;
    }

    public static TableColumn<PrimitiveModel, Double> getDoubleColumn() {
        TableColumn<PrimitiveModel, Double> doubleCol = new TableColumn<>("Double");
        doubleCol.setCellValueFactory(new PropertyValueFactory<PrimitiveModel, Double>("double"));
        return doubleCol;
    }

    public static TableColumn<PrimitiveModel, String> getStringColumn() {
        TableColumn<PrimitiveModel, String> stringCol = new TableColumn<PrimitiveModel, String>("String");
        stringCol.setCellValueFactory(new PropertyValueFactory<PrimitiveModel, String>("string"));
        return stringCol;
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Model class:
public class PrimitiveModel {

    public PrimitiveModel(int i, double d, String s) {
        this.i = i;
        this.d = d;
        this.s = s;
    }
    public int getInteger() {
        return i;
    }
    public double getDouble() {
        return d;
    }
    public String getString() {
        return s;
    }

    private int i;
    private double d;
    private String s;
}

TableStyle.css file:
.table-row-cell:selected{
    -fx-background-color: lightgray ;
}

.table-row-cell:redRow {
    -fx-background-color: red;
}

.table-row-cell:aquaRow {
    -fx-background-color: aqua ;
}

A: You can use border-right, border-left for the td tag. so it will only apply for vertical lines.
check the below snippet
  td {
    border-right: solid 1px lightgray;
    border-left: solid 1px lightgray;
  }

A: Perhaps not the best solution (add this style to .css file):
.table-cell{
    -fx-border-color: #ececec;  /* similar to the default color */
    -fx-border-width: 0.5;   /* similar to the default width */
}

Border-color determines the color of lines between cells.
This css style applies to all TableView, not only selected row. But it works: blue lines no longer appear.
One of the disadvantage is that you need to specify the border-width of the line, otherwise the arrangement of some cells is shifted.


text:
Q: About swift Parsing JSON I have a question.I'm trying to parse JSON.However,I got a error. It's called "Cannot call value of non-function type '[Movie]' "  in  this line "completionHandler(modelList)" Can you help me please?
This my class;
class Movie {
    var type : String?
    var title: String?
    var thumbnail: String?
    var id: String?

    init(Dictionary : [String:AnyObject]){
        self.title = Dictionary["Title"] as? String
        self.id = Dictionary["Id"] as? String
        self.type = Dictionary["Type"] as? String
    }
    static func fetchData(completionHandler: ([Movie])) -> () {
        let urlString = "http://tcm-api.azurewebsites.net/api/movie/search?term='Batman'&page=1"
        NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!) { (data, response, error) -> Void in
            if error != nil {
                print(error)
                return
            }

            do {
                var modelList = [Movie]()

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
                for resultDictionary in json["Data"]!!["Results"] as! [[String : AnyObject]]  {
                    let model  = Movie(Dictionary: resultDictionary)
                    modelList.append(model)
                }
                dispatch_async(dispatch_get_main_queue()) {
                    completionHandler(modelList)
                }
            } catch {
                print(error)
            }

        }.resume()
    }
}

A: If you look closely at your function declaration:
func fetchData(completionHandler:([Movie]))->() {

which is equal to:
func fetchData(completionHandler: [Movie]) {

What you want is this:
func fetchData(completionHandler: [Movie] -> Void) {


text:
Q: Apache memory leak with Subversion server Does anyone know of a way to fix the Apache memory leak in relation to Subversion Server? We have a windows server 2003 machine running Apache to host Subversion. From day one, we have had memory leak issues and have not found a solution yet. All we do is monitor our server when when the memory use reaches near the max it can handle we have to restart Apache.

A: We had a similar issue with SVN 1.6.6, Win 2K3 32-bit, CollabNet install.
We tried using this info from the SVN mailing list related to MaxMemFree and it seems to have worked for us so far.

Try adding the MaxMemFree Apache directive to your httpd.conf file. This
  seems to force apache to "clean up" memory more often. I use:
MaxMemFree 512

That, along with not using mod_deflate, and changing some SSL
  parameters (SSLSessionCache and SSLMutex) seems to have stabilized
  our apache memory usage on Windows.

A: There's a bug raised against it here: http://subversion.tigris.org/issues/show_bug.cgi?id=3084
Unfortuantly, there's no fix yet. But it may be worth trying some of the workarounds listed on there until there is a proper fix. It's also worth following some of the links in the comments that go to a number of threads that discuss the issue as various workarounds are listed within those threads as well as those amongst the bug comments.

A: We have same issue after upgrading Apache 2.2.9 and SVN 1.5.5 to Apache 2.2.14 and SVN 1.6.6. It look like that it is SVN 1.6.x related issue, because we didnt have this problem anything before until upgrade..
I hope that somebody have resolution for it...


text:
Q: PHP MySQL Pivot Table Issue Hello everyone i want to create a timesheet aplication in php and
I have the following table structure
noi15 table
id (Primary)    int(11) No
cod     text    No
nume    text    No
intrare     text    No
totalsectie     text    No

which is like this

*

*id cod name      intrare     totalsectie

*1  ABC John Doe  11/12/2015   8

*2 ABC John Doe 11/13/2015     9

*3 AED Andrew Peters 11/12/2015  8

*4 AED Andrew Peters 11/13/2015  8

And the Persons Table
id (Primary)    int(11) No
cod     varchar(255)    No
name    varchar(200)    No
sectie  varchar(80) No
marca   varchar(6)  No
masina

I have tryed something like this
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when intrare = ''',
      intrare,
      ''' then totalsectie end),'''') AS ',
      intrare
    )
  ) INTO @sql
FROM
  noi15;
SET @sql = CONCAT('SELECT noi15.id, noi15.cod, noi15.intrare, persoane.name, persoane.masina, noi15.iesire, noi15.total, noi15.totalsectie, noi15.schimb, persoane.sectie,
    persoane.marca , noi15.reale ', @sql, '
                  FROM `persoane`  LEFT JOIN noi15 ON persoane.name=noi15.name AND
                   GROUP BY name');

But it shows me an empty query.
Thank you in advance!
PS I'm an SO novice.

A: I have solved the problem it was an database issue.