text:
Q: How to do in SQL: next and privious value with same value of master_id from two rows? MS SQL Server 2019 Hello every Body
I have a table like this in SQL:

I need to write SQL query to get the result as the following:

Thanks for any help in advance

A: Do a self join on master_id and exclude rows where the values match:
with cte as (
select 1 [details_id], 1 [master_id], 'a' [value]
union all select 2, 1, 'b'
union all select 3, 2, 'c'
union all select 4, 2, 'd'
)

select a.*, b.value
from cte a
inner join cte b on a.master_id = b.master_id
where a.value <> b.value

A: Thanks @Simeon
SQL get value from next row  guide me
The answer will be:
select details_id,master_id,value,CASE WHEN LEAD( value) OVER ( PARTITION BY master_id ORDER BY details_id ) IS NOT NULL THEN LEAD( value) OVER ( PARTITION BY master_id ORDER BY details_id )
     else lag( value) OVER ( PARTITION BY master_id ORDER BY details_id )
      END AS second_value
            from table1


text:
Q: Comparing an i7 (3.2Ghz) against an i5 (2.5Ghz) using linpack shows the i7 being worse I am trying to compare the number crunching performance of an i5-3210M @ 2.5GHz with 6GB ram and an i7 970 @3.2GHz with 24GB ram. The results are so unexpected I presume I am either doing something very wrong or there is something very wrong with the i7.
As background, the information at the following site shows that the i7 is better is every way (other than being an older cpu model by about 2 years).
http://www.cpubenchmark.net/compare.php?cmp[]=840&cmp[]=815
The operating systems on both computers are identical(Arch Linux x86_64). Both computers are equally stable and never crash.
I am using xlinpack_xeon64, which I obtained here
https://aur.archlinux.org/packages/linpack/
This test "...makes use of SMP parallelism and by default generates as many
threads of execution as the number of the processors of the SMP system." I can verify it is doing so by watching top/htop. Also, when I explicitly set the environment variable OMP_NUM_THREADS to variable numbers of threads, I can observe by top/htop that the specified numbers are being used.
Using this, I have found the i5 to be faster than the i7 by sometimes a factor of 1.2. I have pasted the results for both in full below.
I was initially expecting that in these very parallelizable tests, i7 would outperform the i5 by maybe a factor of three (the i7 has 6 physical cores, and i5 has 2).
I used the systester benchmarker to see if there was something peculiar about linpack here, and this provided almost identical results (i5 faster by around a factor of 1.2).
Finally, I checked the recorded gflops for the two cpu's reported at this site
http://www.intel.com/support/processors/sb/CS-017346.htm
Here, the specified gflops for the i5 is 40. So more of less exactly what the linpack results show. On the other hand, the specified gflops for the i7 is around 79. And I am getting about half of that.
I am baffled but I presume the i7 (whether the cpu itself or the ram or the mb) is malfunctioning. Indeed the variability of the results for the i7 and also complete lack of variability for the i5 is also indicative of something awry with the i7.
Any insight would be very helpful.
-m
======= Results =================
============================================================================
========== i7 linpack test =================================================
============================================================================

 Input data or print help ? Type [data]/help :

Number of equations to solve (problem size): 20000
Leading dimension of array: 20000
Number of trials to run: 4
Data alignment value (in Kbytes): 4
Current date/time: Wed May 21 23:51:14 2014

CPU frequency:    3.206 GHz
Number of CPUs: 1
Number of cores: 6
Number of threads: 12

Parameters are set to:

Number of tests: 1
Number of equations to solve (problem size) : 20000
Leading dimension of array                  : 20000
Number of trials to run                     : 4
Data alignment value (in Kbytes)            : 4

Maximum memory requested that can be used=3200404096, at the size=20000

=================== Timing linear equation system solver ===================

Size   LDA    Align. Time(s)    GFlops   Residual     Residual(norm) Check
20000  20000  4      149.874    35.5909  3.288586e-10 2.911119e-02   pass
20000  20000  4      135.832    39.2701  3.288586e-10 2.911119e-02   pass
20000  20000  4      142.117    37.5334  3.288586e-10 2.911119e-02   pass
20000  20000  4      121.434    43.9262  3.288586e-10 2.911119e-02   pass

Performance Summary (GFlops)

Size   LDA    Align.  Average  Maximal
20000  20000  4       39.0801  43.9262

Residual checks PASSED

End of tests

============================================================================
========== i5 linpack test =================================================
============================================================================

Input data or print help ? Type [data]/help :

Number of equations to solve (problem size): 20000
Leading dimension of array: 20000
Number of trials to run: 4
Data alignment value (in Kbytes): 4
Current date/time: Wed May 21 23:54:15 2014

CPU frequency:    3.092 GHz
Number of CPUs: 1
Number of cores: 2
Number of threads: 4

Parameters are set to:

Number of tests: 1
Number of equations to solve (problem size) : 20000
Leading dimension of array                  : 20000
Number of trials to run                     : 4
Data alignment value (in Kbytes)            : 4

Maximum memory requested that can be used=3200404096, at the size=20000

=================== Timing linear equation system solver ===================

Size   LDA    Align. Time(s)    GFlops   Residual     Residual(norm) Check
20000  20000  4      125.668    42.4461  4.097986e-10 3.627616e-02   pass
20000  20000  4      125.602    42.4686  4.097986e-10 3.627616e-02   pass
20000  20000  4      125.551    42.4856  4.097986e-10 3.627616e-02   pass
20000  20000  4      125.550    42.4861  4.097986e-10 3.627616e-02   pass

Performance Summary (GFlops)

Size   LDA    Align.  Average  Maximal
20000  20000  4       42.4716  42.4861

Residual checks PASSED

End of tests

A: My answer is coming quite a bit late, but since I just did HPL (high performance linpack) benchmark, I may as well write down my answer.
To understand the result of your experiment, you need to know what Linpack is calculating and aiming at benchmarking. Linpack uses dense-matrix linear algebra calculations in order to measure the performance of high-density floating-point calculations. The results are somewhat reflective of the peak of the CPU theoretical FLOPS capacity because of the dominating matrix-multiply operations. (Of course some other factors exist--memory, extra memory operations, etc--which do not permit the achievement of full CPU theoretical FLOPS; but traditionally 70-80% of full FLOPS are quite achievable, if you look at the TOP500 lists.)
I bet that your Linpack executable is leveraging Intel MKL (Math Kernel Library). On older architecture (before Sandy Bridge, which your i7 belongs to), the only "fast" floating-point processing unit available is the SSE unit, which processes 2 floating point numbers at a time. Your newer i5 processor is of Ivy Bridge architecture that has AVX unit, that can process 4 floating point numbers at a time. (Actually, if you look more closely at the hardware capability, the number of floating point ops doubles, because they can simultaneously perform addition and multiplication, thus 4 FLOP/cycle and 8 FLOP/cycle for each SSE and AVX units, respectively).
So the theoretical ratio of single-core CPU performance of your i7 (3.2 GHz) to i5 (2.5 GHz) CPUs would be:
(2.5) * 2 / (3.2) = 1.56

(Factor 2 accounting SSE-AVX difference.) But if you utilize all the cores without hyperthreading, you should get:
(2.5) * 2 * 2 / (3.2 * 6) = 0.52

Now, I can't fully account your observation, then! Unless, if the 6-core calculation really starves the CPU of data to compute? The fact that the i5 is faster could indicate other improvements that are not coming from CPU speed & compute capabilities alone.
Wirawan
PS: Intel's use of terms "i7" and "i5" are always confusing to me; while "i7" is of course better than "i5", it is not that clear what performance advantage the former gives, and how much.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex vertical bar I'd like to find all matches for these in 1 go:
http://somewebsite/usr/blah_blah

http://somewebsite/ch/blah_blah_blah

I've tried using vertical bar but no go
matches = re.findall('http://somewebsite/(usr|ch)/(.*?)', line, re.DOTALL)

Instead of doing 2 separate regex, I'd like to have blah_blah and blah_blah_blah with just one above regex using vertical bar (OR)
Any suggestion? Please help. Thanks.

A: If you want to match the whole line starting from http link, then you have to do two things.

*

*Remove the space which exists before http in your regex.

*Turn all the capturing groups into non-capturing groups.

*Turn non-greedy regex to greey.
So your regex must be,
matches = re.findall(r'\bhttp://somewebsite/(?:usr|ch)/.*', line, re.DOTALL)

If you want to fetch only the part which exists after usr or ch then apply the capturing group only to the following .*
matches = re.findall(r'\bhttp://somewebsite/(?:usr|ch)/(.*)', line, re.DOTALL)

A: There are a couple of things that need to be done. As was mentioned, remove the white space it is treated as if there was a white space. Next, you failed to escape the / character. Finally the question mark character tells the expression to stop looking at some spot. Try the following.
 matches = re.findall('http:\/\/somewebsite\/(usr|ch)\/.*', line, re.DOTALL)

Finally the parenthesis can be used to captcha data. Leave it out if you want the full address. In python group 0 will have the full match. The same is true in java and most other languages.This appears to be python so [x[0] for x in matches] will give a list of the entire link.
More info is available at the following site.

A: In order to give you a more general example; the actually most adequate solution might depend on some information, that is not given yet:
    test1 = "xxx http://somewebsite/usr/blah_blah/baff_blaff"
    test2 = "yyy http://somewebsite/log/blah_blah_blah"
    test3 = "zzzzhttp://somewebsite/ch/blah_blah_blah_blah/ ZZZ"

    matches = re.findall(r'http://somewebsite/(?:usr|ch)/(\w*)', test1 + '\n' + test2 + '\n' + test3)

    print(matches)

>>> ['blah_blah', 'blah_blah_blah_blah']


text:
Q: How to install two versions of Cocoapods on Mac OSX How to install two versions of Cocopads. Because I have a project that needs a specific Cocoapods version so the build targets would work fine. If I use a newer version of Cocoapods to install the frameworks, the project just won't build. So what's the solution for this kind of problem?

A: Gemfiles tend to be the solution to this, though it works per-project not per target. I don't think you're going to find an answer for different pod versions per target.


text:
Q: How to read a log file within a msbuild task and check each line I want to read a log file created during the build process and check if it contains some error messages. And I want to print out the lines with the error message.
So far I can read the file in and print the whole file out again, but I cannot check several lines for the exception text and print only these lines out. Has someone a hint for me?
<Target Name="CheckLog">
    <PropertyGroup>
        <ErrorText>ERR</ErrorText>
    </PropertyGroup>

    <ReadLinesFromFile File="execution.log" >
        <Output TaskParameter="Lines" ItemName="FileContents" />
    </ReadLinesFromFile>

    <!-- lines are printed out correctly -->
    <Message Text="%(FileContents.Identity)" />

    <CreateProperty Value="true" Condition="@(FileContents.Contains('$(ErrorText)'))">
        <Output TaskParameter="Value" PropertyName="VerifyError" />
    </CreateProperty>

    <Message Text="@(VerifyError)" />
    <Error Condition="@(VerifyError) != ''" Text="Execution returned with an error." />
</Target>

A: I found a solution by myself.
First I added a condition to the Message Task. So the lines are filtered. Only lines that indicate an error are printed out.
Second I replaced the CreateProperty Task. I use a PropertyGroup now to create a property that contains all lines (not exactly what I wanted initially, but it works for me together with the next point).
And third I modified the error condition. I check if in the whole text an error occurred.
<Target Name="CheckLog">
    <PropertyGroup>
        <ErrorText>ERR</ErrorText>
    </PropertyGroup>

    <ReadLinesFromFile File="execution.log" >
        <Output TaskParameter="Lines" ItemName="FileContents" />
    </ReadLinesFromFile>

    <Message Text="%(FileContents.Identity)" Condition="$([System.String]::Copy('%(FileContents.Identity)').StartsWith($(ErrorText)))" />

    <PropertyGroup>
        <AllLines>@(FileContents)</AllLines>
    </PropertyGroup>
    <Error Condition="$(AllLines.Contains($(ErrorText)))" Text="Execution returned with an error." />
</Target>

A: Maybe even more elegant: Using an Error Task, only:
<Target Name="CheckLog">
    <PropertyGroup>
        <ErrorText>ERR</ErrorText>
    </PropertyGroup>
    <ReadLinesFromFile File="execution.log" >
        <Output TaskParameter="Lines" ItemName="FileContents" />
    </ReadLinesFromFile>

    <Error Text="%(FileContents.Identity)" Condition="$([System.String]::Copy('%(FileContents.Identity)').StartsWith($(ErrorText)))" />
</Target>


text:
Q: Is a self-adjoint operator continuous on its domain? Let $H$ be a Hilbert space, and $A : D(A) \subset H \rightarrow H$ be an unbounded linear operator, with a domain $D(A)$ being dense in H.
We assume that $A$ is self-adjoint, that is $A^*=A$.
Since $A$ is unbounded, we can find a sequence $x_n$ in the domain such that $x_n \rightarrow x$ with $x \notin D(A)$, meaning that $Ax_n$ does not converge.
My question is the following: Is it true that $A$ is continuous relatively to its domain? More precisely: given a converging sequence $x_n \rightarrow x$ for which both the sequence $x_n$ and the limit point $x$ lie in $D(A)$, can we conclude that $Ax_n \rightarrow Ax$? Or is there any counter-example?
I know that self-adjoint operators are closed, in the sense that their graph $D(A)\times A(D(A))$ is closed in $H \times H$, but continuity on the domain is something else.

A: If $A$ is unbounded, that means that for any $n$ there exists a $v\in D(A)$ such that $\|Av\|> n\|v\|$.  Dividing such a $v$ by $\|v\|$, we may assume $\|v\|=1$, so we can find a sequence $(v_n)$ of unit vectors in $D(A)$ such that $\|Av_n\|>n$ for each $n$.  The sequence $(v_n/n)$ then converges to $0$ but $Av_n/n$ does not converge to $A(0)=0$ since $\|Av_n/n\|>1$ for all $n$.
(More generally, the same argument shows that if $X$ and $Y$ are normed vector spaces, then a linear map $A:X\to Y$ is continuous iff it is bounded.)

A: Let $H$ be a Hilbert space, and let $D$ be a dense subset in $H$ under the metric topology induced by $H$'s norm. Let $A: D\rightarrow D$ be an unbounded self adjoint operator such that
$$
\langle Ah,g\rangle=\langle h,Ag\rangle, \forall h,g\in D
$$
Thus there exists a sequence of elements such that $$d_{i}\in D, |d_{i}|=1, |A(d_{i})|\ge i^2, \forall i $$
Now if $h_{i}\rightarrow h \in H$, we can construct a new sequence $s_{i}=h_{i}+\frac{d_{i}}{i}$. So we have for sufficiently large $i$:
$$
s_{i}\rightarrow s, |A(s_{i})|\ge |A(h_{i})-A(\frac{d_{i}}{i})|\ge i-2|A(h)|
$$
which cannot happen. Thus $A$ is unbounded on $H$ as well.


text:
Q: $K/F$ Galois Extension, $H \leq G$, where $G$ the Galois group, then there is $\alpha \in K$ s.t. $H=\{\sigma \in G : \sigma \alpha = \alpha\}$. Let $K/F$ be a finite Galois extension of fields with Galois group $G$. Let $H$ be a subgroup of $G$. Then there is $\alpha \in K$ such that $H=\{\sigma \in G : \sigma \alpha = \alpha\}$.
My proof is this:
Consider the fixed field $E$ of $H$. Let $\alpha \in E$ be such that if $\alpha \in E' \subseteq K$ then $E\subseteq E'$. Then $H = \{\sigma \in G : \sigma \alpha = \alpha \}$ since if $\sigma \in H$, then sigma fixes $\alpha$. Conversely, if $\sigma \in G$ fixes alpha, then by choice of $\alpha$, $\sigma$ is contained in some subgroup $H'$ with fixed field $E'$ containing $\alpha$ and $E' \supseteq E$. In particular, since $E \subseteq E' \iff H' \subseteq H$, we have $\sigma \in H$. The result follows.
Does this work? I feel like I might be missing something since I (apparently) did not use the finiteness assumption on the field extension.

People have posted (better) solutions but I'm still interested in knowing whether what I came up with is correct.

A: $E=K^H$, being a subextension of the Galois extension $K/F$ is a finite separable extension of $K$, hence by the Primitive element theorem, there exists $\alpha\in E$  such that $E=K(\alpha)$. Now, it isresults from the Galois correspondence that:
 $$H=\{\sigma\in G\mid \sigma(\alpha)=\alpha\}.$$

A: You used the assumption of finiteness of the extension when you assumed that exist $ \alpha $ as you choose. The existence of such $ \alpha $ is ensured by the Primitive element theorem and not necessary true for infinite extensions. From then on, your solution is absolutely correct.


text:
Q: NativeScript AdMob plugin - crash the app on emulator or on playground: Cannot read property 'getRewardedVideoAdInstance' of undefined I've created a nativescript with angular (drawer template) app and everything works fine.
Using the command tns run android --bundle the app was successfully installed and runned on the Pixel 2 emulator.
The problem was after I installed the admob plugin, using the command tns plugin add nativescript-admob. Immediately app crashed on the emulator.
Bellow the package.json to proff the installation of the admob plugin on my app.
...
"nativescript-admob": "^4.0.1",
...

Nevertheless, I've continued following instructions from here: https://market.nativescript.org/plugins/nativescript-admob
so my AndroidManifest.xml it looks like that:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="__PACKAGE__"
android:versionCode="10000"
android:versionName="1.0">

<supports-screens
    android:smallScreens="true"
    android:normalScreens="true"
    android:largeScreens="true"
    android:xlargeScreens="true"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:name="com.tns.NativeScriptApplication"
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    **<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-3940256099942544/5224354917" />**

    <activity
        android:name="com.tns.NativeScriptActivity"
        android:label="@string/title_activity_kimera"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|locale|uiMode"
        android:theme="@style/LaunchScreenTheme">

        <meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.tns.ErrorReportActivity"/>
</application>

and the browse.component.ts it looks like that:
On the emulator, the app continues to crash,
However, using the nativescript playground (tns preview) the app does not crash but it gives the error: LOG from device Galaxy S9: Error in admob.preloadRewardedVideoAd: TypeError: Cannot read property 'getRewardedVideoAdInstance' of undefin
LOG from device Galaxy S9: admob preloadRewardedVideoAd error: TypeError: Cannot read property 'getRewardedVideoAdInstance' of undefined
import { Component, OnInit } from "@angular/core";
import { RadSideDrawer } from "nativescript-ui-sidedrawer";
import * as app from "tns-core-modules/application";
import * as admob from "nativescript-admob";

@Component({
    selector: "Browse",
    templateUrl: "./browse.component.html"
})
export class BrowseComponent implements OnInit {

    constructor() {
        // Use the component constructor to inject providers.
    }

    ngOnInit(): void {

        // Init your component properties here.
        admob.preloadRewardedVideoAd({
            testing: true,
            iosAdPlacementId: "ca-app-pub-XXXXXX/YYYYY2", // add your own
            androidAdPlacementId: "ca-app-pub-3940256099942544/5224354917", // add your own
            keywords: ["keyword1", "keyword2"], // add keywords for ad targeting
        }).then(
             () => {
                console.log("RewardedVideoAd preloaded");
            },
            (error) => {
                console.log("native-admob preloadRewardedVideoAd error: " + error);
            }
        )
    }

    onDrawerButtonTap(): void {
        const sideDrawer = <RadSideDrawer>app.getRootView();
        sideDrawer.showDrawer();
    }
}


text:
Q: SQL: how does parallelism of a join operation exactly work in a "shared nothing" architecture? I'm currently reading a book about parallelism in a DBMS and I find it difficult to understand how parallelism works exactly in the join operation.
Suppose we have 10 systems, each system has each own disk space and main memory. There is a network with which the systems can communicate with each other in order for example to share data.
Now suppose we have the following operation: A(X,Y) JOIN B(Y,Z)
the tables A and B are too big so we want to use parallelism in order to gain better overall computing speed.
What we do is we apply a hash function on the 'Y' attribute for each record of A and B tables, and we send these records to a different system. Each system can then use a local algorithm in order to join the records that they got.
What I don't understand is, where exactly is the initial hash function being applied and where exactly are the initial tables A and B being stored?
While I was reading I thought that we had another "main" system, which had also its own disk space, and in this space we had all the initial information, which is table A and B with all their records. This system used its own main memory in order to apply the initial hash function, which determined for each record the system out of the total 10 where it will eventually go and be processed.
however upon reading I got stuck in the following example(I translate from Greek)
Let's say we have two tables R(X,Y) JOIN S(Y,Z) where R has 1000 pages and S 500 pages. Suppose that we have 10 systems that can be used in parallel. So we start by using a hash function to determine where we should send each record. The total amount of I/Os needed to read the tables R and S is 1500, which is 150 for each system. Each system will have 15 pages of data which are necessary for each of the remaining systems, so it sends 135 pages to the other nine systems. Hence the total communication is 1350 pages.
I don't really understand the bold part. Why would a system have to send any data to the other systems? Doesn't the "main" system I was talking about previously do this job?
I imagine something like this:
               main_system
                  ||
                  \/
            apply_hash(record)
                  ||
                  \/
              send record to the appropriate system
              / /  /  /  /  /  /  /  /  /
            s1 s2 s3 s4 s5 s6 s7 s8 s9 s10

now all systems have their own records, they apply the local algorithm and give the result to the output. No communication between the systems, what am I missing here?? does the book use a different approach and if so what kind of approach because I have read the same unit 3 times and I still don't get it(maybe a bad translation not sure though).
thanks in advance

A: id take a wild guess that your connection is your local client. since it has a connection to all machines.

A: In a shared-nothing system, the data is typically partitioned across the processors when the data is created.  Although databases can be shared-nothing, probably the best documentation is for Hadoop and HDFS, the Hadoop distributed file system.
A function assigns rows to a partition.  Some examples are:  round-robin, where new rows are assigned to the processors one after the other; range-based, where rows are assigned to a processor based on the value of a column; hash-based, where rows are assigned to a processor based on a hash of the value.  The process of partitioning the data is very similar to "partitioning" in databases such as SQL Server and Oracle which are not in a shared-nothing environment.
If your join uses the partition key for both tables, and the partitioning method is the same, then the data is already local.  Otherwise, one or both tables need to be redistributed to continue the processing.
In the section that you quote, you are probably confused by the arithmetic.  Remember that if you have 1500 pages across 10 processors, each will have on average 150 pages.  These pages need to be redistributed.  Say you are processor 3.  About 15 pages will go to processor 1; another 15 to processor 2.  And another to processor 3.  Wait!  You don't have to send these; they are already in the right spot.  You only have to send 9*15 = 135 pages to other processors.
The key idea is that the same processors are storing the data as doing the processing, in a shared-notthing environment.


text:
Q: Carbon setTestNow function is not working I am working on dates in Laravel. I have to set dates for patient future injections.
To keep it simple, let's suppose today is 13-03-2019 (Wednesday).
I created first date as:
$firstDate = Carbon::create(2019,03 ,18, 12); // The day is Monday
// set date
Carbon::setTestNow($firstDate);

Now I want the next two appointments should be on Wednesday and Friday. So I again set the dates as follow:
  // set second date
   $secondDate = new Carbon('Wednesday');
   Carbon::setTestNow($secondDate);
   // set thirdDate
   $thirdDate = new Carbon('Friday');
   Carbon::setTestNow($thirdDate);

According to above example the output should be:

*

*2019-03-18

*2019-03-20

*2019-03-22

But the problem is that it outputs the first set date correct but print the 2nd and 3rd date wrong as it considers 'Wednesday' of next week as today's date.
So the Output print as:

*

*2019-03-18

*2019-03-13

*2019-03-14

I have spent a lot of time on it, I would appreciate if anyone of you people could help me in this.
I would appreciate if anyone guides me where I am going wrong.
Thanks.

A: As the setTestNow() function was not working for 2nd and third date/days, so I first get all three required days then convert them to 'dayOfWeek' which returns day number (Sunday 0, Monday 1 and so on...). I subtracted the first day from second and third day and then finally add these days to the date that i get from the datepicker.
      // set the start date
      if( $visitstart_date != null && $visitstart_date != '') {
           Carbon::setTestNow($visitstart_date);
      } else {
       Carbon::setTestNow();
     }

     if($perweek_visit1_day != '')
     {
        //Get first selected day number
        $firstDay = Carbon::parse($perweek_visit1_day)->dayOfWeek;
        $perweek_visit1_dayDate = Carbon::now();
     }
     if($perweek_visit2_day != '')
     {
        //Get second day numer
        $secondDay = Carbon::parse($perweek_visit2_day)->dayOfWeek - $firstDay;
        $perweek_visit2_dayDate = Carbon::now()->addDays($secondDay);
      }
     if($perweek_visit3_day != '')
     {
        //Get third day number
        $thirdDay = Carbon::parse($perweek_visit3_day)->dayOfWeek - $firstDay;
        $perweek_visit3_dayDate = Carbon::now()->addDays($thirdDay);
     }


text:
Q: Kivy: Scatter inside scatter Question: How do I put one Scatter inside another Scatter?
I have some troubles with kivy's coordinates. In principal I would like to have a Scatter in a Scatter. They should be drageable (moving first scatter moves everything, moving 2nd scatter moves the 2nd scatter inside the first scatter).
Concrete setup

*

*I would like to have a base map (scatter 1) that is scaleable and moveable. When we transform this map, everything drawn "on top" of this map should be transformed as well (s.t. it keeps its position on the map).

*Then I would like to draw a grid on top of the map which is moveable by its own (scatter 2).

*Then I add some point onto scatter 2.

*The relative positions must be preserved on rescaling the window.
Expected behavior
When I grab scatter 2, it can be moved around and the points (3.) stay relative to scatter 2. When I grab scatter 1, it should move everything s.t. scatter 2 and the points stay where they are on the map (scatter 1).
Basic example code
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

kv = """
<MyRoot>:
    orientation: 'vertical'
    ActionBar:
        ActionView:
            ActionPrevious:
                title: ''
                with_previous: True
            ActionOverflow:
                ActionButton:
                    text: 'Preferences'
                    on_press: app.open_settings()
    Scatter:
        canvas:
            Color:
                rgb: .2, .2, .3
            Rectangle:
                pos: self.pos
                size: self.size
        Scatter:

            canvas:
                Color:
                    rgb: .8, .2, .3
                Rectangle:
                    pos: self.pos
                    size: self.size
            Widget:
                pos: 200, 200
                canvas:
                    Color:
                        rgb: .1, .7, .3
                    Ellipse:
                        pos: 30,50
                        size: 10, 10
"""
Builder.load_string(kv)

class MyApp(App):
    def build(self):
        return MyRoot()

class MyRoot(BoxLayout):
    pass

if __name__ == '__main__':
    MyApp().run()

Also here is an image of what's happening. I would like to have the green point fixed on the red scatter and the red scatter sitting inside the violet one:

Approach
I guess I have to transform the coordinates in each step and overwrite the functions on_touch_..., maybe using self.parent.to_parent(*touch.pos) but unfortunately I don't manage to patch everything together.
Thank you for any help!

A: Rectangle:
    size: self.size

This is a relative layout, therefore we need: pos: 0,0 and not pos: self.pos.


text:
Q: Using authblk package automated count on affil command My current coding is affiliation link number insert manually.
    \title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}
\author[1]{Junli Liu}
\author[2]{James Rowe}
\author[3]{Keith Lindsey}
\affil[1]{address one}
\affil[2]{address two}
\affil[3]{address three}

But i want affiliation link number to be entered automatically like counter concept.suggest solution
For Example:
\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}
    \author[1]{Junli Liu}
    \author[2]{James Rowe}
    \author[3]{Keith Lindsey}
    \affil{address one}
    \affil{address two}
    \affil{address three}

A: If you want one entry to not have a number, you could use \affil[ ]{<stuff>}:

\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}
\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}
\author[1]{Junli Liu}
\author[2]{James Rowe}
\author[2]{Keith Lindsey}
\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences, The Bio physical Sciences Institute, Durham University, Durham, UK}
\affil[$\relax$]{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences, The Bio physical Sciences Institute, Durham University, Durham, UK}

\maketitle

\end{document}

If you want all \affil to be void of numbers you can add the following to your preamble:
\usepackage[noblocks]{authblk}
\let\oldaffil\affil% Store a copy of \affil in \oldaffil
\renewcommand{\affil}{\oldaffil[ ]}% Update \affil to *always* use \affil[ ]

The above modification makes \affil default to \affil[ ] so you don't have to pass an optional argument anymore.

\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}
\let\oldaffil\affil
\renewcommand{\affil}{\oldaffil[ ]}
\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}
\author[1]{Junli Liu}
\author[2]{James Rowe}
\author[2]{Keith Lindsey}
\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences, The Bio physical Sciences Institute, Durham University, Durham, UK}
\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences, The Bio physical Sciences Institute, Durham University, Durham, UK}

\maketitle

\end{document}

A: I'm not sure what logic you're expecting in \affil.
There are two forms for using authblk facilities.
First form
\author{Name1}
\affil{Affiliation1}

\author{Name2a}
\author{Name2b}
\affil{Affiliation 2}

(any number of authors can precede an \affil command, that will refer to that group of authors). It's your case:
\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}

\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}

\author{Junli Liu}
\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences,
  The Bio physical Sciences Institute, Durham University, Durham, UK}

\author{James Rowe}
\author{Keith Lindsey}
\affil{Some other laboratory, Elsewhere}

\maketitle

\end{document}

produces

Second form
If affiliations don't follow the order of authors, one has to go with the second form, where the optional argument becomes necessary:
\author[1]{Name1a}
\author[2]{Name2}
\author[1]{Name1b}

\affil[1]{Affiliation1}
\affil[2]{Affiliation2}

So, if in your case Lindsey has the same affiliation as Liu, you should input
\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}

\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}

\author[1]{Junli Liu}
\author[2]{James Rowe}
\author[1]{Keith Lindsey}

\affil[1]{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences,
  The Bio physical Sciences Institute, Durham University, Durham, UK}
\affil[2]{Some other laboratory, Elsewhere}

\maketitle

and you'd get

Alternative way
If you have an affiliation for each author and want automatic numbering, you can do it by changing how the commands work.
\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}

\usepackage{letltxmacro,xpatch}
\newcounter{affiliations}
\LetLtxMacro{\authblkauthor}{\author}
\LetLtxMacro{\authblkaffil}{\affil}

\renewcommand{\author}[1]{%
  \authblkauthor[\theauthors]{#1}%
}
\renewcommand{\affil}[1]{%
  \stepcounter{affiliations}%
  \authblkaffil[\theaffiliations]{#1}%
}

\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}

\author{Junli Liu}
\author{James Rowe}
\author{Keith Lindsey}

\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences,
  The Bio physical Sciences Institute, Durham University, Durham, UK}
\affil{Some other laboratory, Elsewhere}
\affil{Another laboratory, Somewhere Else}

\maketitle
\end{document}

However, you'd get exactly the same result by using the first form, which in my opinion is clearer input.
\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}

\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}

\author{Junli Liu}
\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences,
  The Bio physical Sciences Institute, Durham University, Durham, UK}

\author{James Rowe}
\affil{Some other laboratory, Elsewhere}

\author{Keith Lindsey}
\affil{Another laboratory, Somewhere Else}

\maketitle
\end{document}

Another possibility (here you need the optional argument next to \author):
\documentclass[twocolumn]{article}
\usepackage[noblocks]{authblk}

\usepackage{letltxmacro,xpatch}
\newcounter{affiliations}
\LetLtxMacro{\authblkaffil}{\affil}

\renewcommand{\affil}[1]{%
  \stepcounter{affiliations}%
  \authblkaffil[\theaffiliations]{#1}%
}

\begin{document}

\title{Hormonal crosstalk for root development: a combined experimental and modeling perspective}

\author[1]{Junli Liu}
\author[2]{James Rowe}
\author[3]{Keith Lindsey}

\affil{Integrative Cell Biology Laboratory, School of Biological and Biomedical Sciences,
  The Bio physical Sciences Institute, Durham University, Durham, UK}
\affil{Some other laboratory, Elsewhere}
\affil{Another laboratory, Somewhere Else}

\maketitle
\end{document}


text:
Q: Do debug messages being displayed on production server? Let's say I have console handler that prints DEBUG messages to console.
On production server where DEBUG=False, do debug messages displayed on console? Or they're only valid on development machine.

A: Django prints to apache's error.log when DEBUG=False.

A: When DEBUG=False Error messages wont appear on site.You will get email to mails listed in 'ADMINS' settings in the "settings.py" file.


text:
Q: PowerShell Send Mail To Address In Array I'm building a script that checks for user accounts with soon-expiring passwords and sends emails to these people reminding them to change their passwords. Yes, our domain settings already generate those prompts counting down from 14 days. Yes, people ignore these. Yes, I'm trying to save work due to people failing to change their passwords in time while working remotely.
In the script I go through an array of the OUs I am responsible for and get the user accounts with expiring passwords and store these in an array containing their DisplayName, Mail, and calculated values containing DaysLeft and ExpiryDate:
$diff = New-TimeSpan -Start ([datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")) -End (Get-Date)

$OusToSearch = @(
    'OU=ORG1,DC=corp,DC=com'
    'OU=ORG2,DC=corp,DC=com'
    'OU=ORG3,DC=corp,DC=com'
)
ForEach ($OU in $OusToSearch) {
    $PwdExpUsersInOU = Get-ADUser -SearchBase $OU -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and Mail -like '*'} -Properties "DisplayName", "mail", "msDS-UserPasswordExpiryTimeComputed" | Where-Object {
        $diff = New-TimeSpan -End ([datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")) -Start (Get-Date)
        $diff.Days -le 14 -and $diff.Days -ge 0
        } | Select-Object "DisplayName","Mail",@{Name="DaysLeft";Expression={$diff.Days}},@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
    $PwdExpUsers += $PwdExpUsersInOU
}

Thanks to other askers and answerers here for lots of that code.
This part works. At this point I have an array $PwdExpUsers containing the relevant information.
Next I break this array apart into several smaller arrays in order to send tailored email addressed to each person that query returns with messages appropriate to how soon their passwords are expiring:
Note 1: This is currently testing code and filters for and only creates emails for those with passwords expiring tomorrow, as should be obvious from the code below. Once I get the addressing issue figured out I'll expand this to handle the rest of the array.
Note 2: The message content is HTML I've already stored in variables ($MsgTomorrow) earlier in the script. It works fine.
$Outlook = New-Object -ComObject Outlook.Application

$ExpTomorrow = $PwdExpUsers | Where-Object -FilterScript {$PSItem.DaysLeft -eq '0'}

foreach ($Account in $ExpTomorrow) {
    $Mail = $Outlook.CreateItem(0)
    $Mail.Importance = 2
    $Mail.To = $PSItem.Mail
    $Mail.Subject = "IMPORTANT: Your computer login password expires tomorrow"
    $Mail.HTMLBody = $MsgTomorrow
    $Mail.Save()
}

At the end of this I have emails in my Drafts folder with the correct subject and body, but no email address in the To field.
I assume I am failing to grasp how the $PSItem.Mail value is being passed along, and what $Mail.To expects to receive.
A valid solution would also remove the ForEach bit entirely and allow me to create a single email addresses to all members of the array $ExpTomorrow.

A: $PSItem -aka $_ ... This is the variable for the value that is running through the pipe line.
Try $Mail.To = $Account.Mail
If this doesn't do it please post example content of $ExpTomorrow
───────
You can also try it this way without outlook.

#

$smtp = "mail.server.com"
$from = "123abc@xyz.com"
$subject = "Email Subject Example - Password expiring!"

foreach($Account in $ExpTomorrow){
    # All HTML will go into the body.
    $body = "You are bad at maintaining your passwords, please do it now."
    $to = $Account.Mail

    # Now send the email using Send-MailMessage
    send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high
}


text:
Q: Grab section of text where a string resides I have a text file that looks like this:
# Query 1:
.
.
.
# Hosts ip-127-0-0-1
.
.
.

# Query 2:
.
.

In my file there might be multiple queries; I only want to extract the information when my ip is NOT a certain value.
For example here I want to capture starting with '# Query 1' up until the space right before where it says '# Query 2' -- however I need to do this ONLY if Hosts ip does NOT match ip-127-0-0-1. This isn't an exact match as ip-127-0-0-1 can have other text appended to the end like ip-127-0-0-1.notusefultext
I'm open to using awk, sed or python to assist with this problem.

A: This might work for you (GNU sed):
sed -n '/^# Query [0-9]*:/{:a;N;/^\s*$/M!ba;/Hosts.*127-0-0-1/I!p}' file

Use sed's -n option to only print explicitly. Focus on any line that begins # Query n*: where n* means zero or more digits (use [^:]* if this match is too specific). Gather up the current and following lines until (and including) an empty line. Test the collection of lines for the string 127-0-0-1 and if not present, print the collection. All other lines will not be printed.
N.B. The collection includes both the query line and the empty line, this may not be the case if the last query does not have an empty line as the last line of the file. This can be catered for by an ameliorated version:
sed -n '/^# Query [0-9]*:/{:a;$!{N;/^\s*$/M!ba};/Hosts.*127-0-0-1/I!p}' file

A: I assume your query file would be like below. Please try this Perl solution
$ cat query_ip.txt
# Query 1:
select a b c from
tab
# Hosts ip-127-8-8-1
where a = '1'

# Query 2:
select a b c from
tab2
# Hosts ip-127-0-0-1
where a = '1'

# Query 3:
select a b c from
tab3
# Hosts ip-127-9-9-1
where a = '1'

$  perl -0777 -ne ' $_.="# Query "; while( /(# Query.+?)(# Query.+)/smg ) { $x=$1 ; $_="$2"; print $x if not $x=~/ip-127-0-0-1/ } ' query_ip.txt
# Query 1:
select a b c from
tab
# Hosts ip-127-8-8-1
where a = '1'

# Query 3:
select a b c from
tab3
# Hosts ip-127-9-9-1
where a = '1'

$

or try this.
$ perl -0777 -ne ' while( /(# Query.+?)(# Query.+|\Z)/smg ) { $x=$1 ; $_="$2"; print "$x\n" if not $x=~/ip-127-0-0-1/ } ' query_ip.txt
# Query 1:
select a b c from
tab
# Hosts ip-127-8-8-1
where a = '1'

# Query 3:
select a b c from
tab3
# Hosts ip-127-9-9-1
where a = '1'
$

A: Given those anchors are exact, and there's nothing before # Query 1:,
try this please:
awk -v RS="# Query 2" 'FNR<2 && !/# Hosts ip-127-0-0-1/'

Judge from your own trying, if you want only lines starts with a letter in the block you described:
awk -v RS="# Query 2" -F"\n" 'FNR<2 && !/# Hosts ip-127-0-0-1/{for (i=1;i<=NF;i++) if($i~ "^[A-Za-z]") print $i}'

If the conditions are somewhat different, please leave comment.

A: Final working solution:
# Pull in isolated code block for each individual query and write to unique file.
TEMP='temp_file'
while read -r line; do
    if [[ $line =~ ^#[[:space:]]Query[[:space:]][0-9].* ]]; then
        new_query='1'
        ((counter++))
        echo "$line" > ${TEMP}_${counter}
    else
        new_query='0'
        echo "$line" >> ${TEMP}_${counter}
    fi
done < "${LONG_RUNNING_QUERIES}"

# Remove first file, as it only contains query statistics for all long running queries.
rm ${TEMP}_0

# For all files that don't contain the IP, group them together in one file.
QUERIES_TO_GRAB='master_file'
> $QUERIES_TO_GRAB
for i in $(ls -v1 temp_file_*); do
    match=$(grep "${IP_ADDY}" "$i")
    if [ -z "$match" ]; then
        cat $i >> $QUERIES_TO_GRAB
    fi
done


text:
Q: Is a limit of measure of a sequence of sets equal to measure of limit of the sequence of sets? I'm sitting at the same question desk as this: Limit of the measure of the converging sequence of sets.
Actually, I can't prove it neither. PA6OTA gave a hint to show there is subsequence $A_{n_k}$ such that $μ(A_{n_k}) > μ(lim\ sup_n A_n) + ϵ$ for large enough k, leading to a contradiction. I don't know why should I assume a subsequence?

A: For any sequence of sets $(A_n)$ the $\limsup$ is defined by $$\limsup A_n
=\bigcap_{n=1}^\infty\left(\bigcup_{j=n}^\infty A_j\right)=\bigcap_{n=1}^\infty B_n.$$ Since the $B_n$ are decreasing, if we assume the measure is finite we have $$\mu(\limsup A_n)=\lim_{n\to\infty}\mu(B_n)
=\limsup_{n\to\infty}\mu(B_n).$$But $A_n\subset B_n$, so $\mu(A_n)\le\mu(B_n)$, so the above implies
$$\mu(\limsup A_n)\ge\limsup_{n\to\infty}\mu(A_n).$$
Similarly (without assuming $\mu$ is finite) for any sets $A_n$ we have
$$\mu(\liminf_{n\to\infty} A_n)\le\liminf_{n\to\infty}\mu(A_n).$$
Now suppose $A=\lim_{n\to\infty}A_n$ exists. By definition this means $$A=\limsup A_n=\liminf A_n.$$ So the two previous inequalities say $$\liminf\mu(A_n)\ge\mu(A)\ge\limsup\mu(A_n).$$Hence $\lim\mu(A_n)$ exists and equals $\mu(A)$.

A: I think I've figured out a proof.
It is not appropriate to write the symbol "$\lim\sup_n A_n$" because $\sup_n A_n$ is not defined. So replace $\lim\sup_n A_n$ by $\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m$ and $\lim\inf_n A_n$ by $\bigcup_{k=1}^{+\infty} \bigcap_{m=k}^{+\infty}A_m$
Suppose $\lim\sup_n \mu( A_n) > \mu (\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m)$.
Then $\exists$ some rational $r$ with $\lim\sup_n \mu( A_n) > r > \mu (\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m)$(two real numbers $a, b$ satisfy $a > b$ if and only if there is some rational r with $a > r > b$).
So $\exists N ∈ \mathbb N^+$ such that $sup_n \mu (A_n)$ = $sup_n${$μ(A_n), μ(A_{n+1}), ..., μ(A_{\infty})$} $> r > \mu(\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m)$ for all $n \geqslant N$.
Since $sup_n${$μ(A_n), μ(A_{n+1}), ..., μ(A_{\infty})$} $\geqslant$ $sup_{n+1}${$μ(A_{n+1}), μ(A_{n+2}), ..., μ(A_{\infty})$}, then $sup_n \mu (A_n) \geqslant sup_{n+1}  \mu (A_{n+1}) \geqslant .. \geqslant sup_{\infty}  \mu (A_{\infty}) > r > \mu (\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m)$ while actually $sup_{\infty} \mu (A_{\infty}) = \mu (A_{\infty})$.
Here contradiction $\mu (A_{\infty}) = \mu (A)> r > \mu(\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m)$ where $\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m = A$.
So $\lim\sup_n \mu( A_n) \leqslant \mu (\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m)$.
Similar proof for $\mu (\bigcup_{k=1}^{+\infty} \bigcap_{m=k}^{+\infty}A_m) \le \lim\inf_n \mu( A_n)$.
Finally, $$\mu (A) = \mu (\bigcup_{k=1}^{+\infty} \bigcap_{m=k}^{+\infty}A_m) \le \lim\inf_n \mu( A_n) \le  \lim\sup_n \mu( A_n) \le  \mu (\bigcap_{k=1}^{+\infty} \bigcup_{m=k}^{+\infty}A_m) = \mu (A)$$


text:
Q: Increment ($inc) update not working with upsert (MongoDB, NodeJS) I am currently working on a MongoDB Post-Hashtag system, I am using NodeJS and the library "Mongoose". Following the creation of a new "post", I wish to increment the quantity of the "posts" field of the given hashtag's document, else if it does not exist: create a new document for the hashtag. I attempted to do this by utilizing the upsert option and performing a single update (updateOne) for each hashtag. The upserting & new document creation process for a new hashtag appears to work fine, however, pre-existing hashtags do not have their "posts" field incremented.
My code:
await Hashtag.updateOne({hashtag: hashtag}, {
  $set: {$inc: {posts: 1}},
  $setOnInsert: {
   uniqueID: hashtagID,
   hashtag: hashtag,
   timeOfCreation: now,
   posts: 1
 }
}, {upsert: true});

I have attempted both with & without the '$set' operator, as well as '$update' and '$inc' to no avail. Omitting it results in the following error:
{
    "errorType": "MongoServerError",
    "errorMessage": "Updating the path 'posts' would create a conflict at 'posts'",
    "code": 40,
    "index": 0,
    "stack": [
        "MongoServerError: Updating the path 'posts' would create a conflict at 'posts'",
    ...
}

My schema as defined in Mongoose:
const hashtagSchema = new mongoose.Schema({
    uniqueID: {
        type: String,
        required: true
    },
    hashtag: {
        type: String,
        required: true
    },
    timeOfCreation: {
        type: Number,
        required: true
    },
    posts: {
        type: Number,
        required: true
    },
});

A: Remove the $set which is used before $inc.
await Hashtag.updateOne({hashtag: hashtag}, {
      $inc: {posts: 1},
      $setOnInsert: {
       uniqueID: hashtagID,
       hashtag: hashtag,
       timeOfCreation: now,
       posts: 1enter code here
     }
    }, {upsert: true});


text:
Q: Windows Container, with Legacy WCF / TCP Issue I've started migrating a Legacy multi-service application to a Windows Container, so we can easily move it to a new server in the near future.
This application is .Net 4.5.1, and utilizes WCF for majority of its connections. The WCF is net.tcp, with Security Mode Transport, and a Windows TCP Client Credential Type.
I have a DockerFile which uses microsoft/wcf as a base, and builds the requirements of the application on top of that, eventually adding and starting the services.
The services start correctly, I have confirmed with a netstat from within the container, as well as they have a logging mechanism which logs start and stop to a SQL Server, and that works correctly as well.
The issue is I am unable to make an inbound connection to the WCF services. I keep getting this error:
"The server has rejected the client credentials"
I wrote a small application to run in the container, and it just triggers a command against the same service I was testing, except from within the container it works correctly.
Any help would be appreciated.


text:
Q: Does iOS provide a function to get a device-specific suffix string? On iOS there is this nice feature that an app developer can specify device-specific resources or keys in Info.plist by tacking on a device-specific suffix to the base name of the resource or key. Currently we have ~ipad and ~iphone.
I would like to use the same system for some of my app's registration domain user defaults that should have different values on the various devices. Do you know of a function or method in iOS that I can call to get the current device suffix? Although it is simple to code this myself, I prefer to use the system API whenever that is possible.
I don't really care whether the system gives me ~ipad and ~iphone, the strings just need to be unique for each device. I also prefer something that is human readable, which is why I am not enthusiastic about using UIDevice.userInterfaceIdiom (that's just a number). I also looked at UIDevice.model but I am unsure if this would be suitable.

A: Just in case there is no positive answer, this is how my implementation of the desired function looks:
// NSStringAdditions.h
@interface NSString(NSStringAdditions)
- (NSString*) stringByAppendingDeviceSuffix;
@end

// NSStringAdditions.m
- (NSString*) stringByAppendingDeviceSuffix
{
  static NSString* deviceSuffix = nil;
  if (! deviceSuffix)
  {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
      deviceSuffix = @"~iphone";
    else
      deviceSuffix = @"~ipad";
  }
  return [self stringByAppendingString:deviceSuffix];
}


text:
Q: Google Maps Android API v2 supports devices with OpenGL ES 2.0 and above I have an issue regarding OpenGL ES 2.0.  I am developing an android application with Google maps api v2. My logcat is returning an error "Google Maps Android API v2  supports devices with OpenGL ES 2.0 and above". My Phone's android version is 2.2.2. Is there anything i need to install at my device? please give me some advice regarding this issue. thanks.
 at the manifest file
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>


text:
Q: Format number different depending on mobile or business phone Currently in my php application I have the following code that formats the unformatted 10 digit australian phone number to XX XXXX XXXX. What I would like to do is if the phone number in the database starts with 04 then it will format it as 4,3,3 like XXXX XXX XXX otherwise will maintain the 2,4,4 formatting. All phone numbers are stored in the database as XXXXXXXXXX.
Here is my code so hopefully someone can shed some light. I know there needs to be an if statement, but unsure how to check the first 2 digits of the number for the 04.
<?php

    $num = $record['busphone'];
    $phoneformated = substr($num,0,2)." ".substr($num,4,4)." ".substr($num,6);

    echo "Ph: " . $phoneformated;

?>

A: You're on the right track. Here's an if statement
$prefix = substr($num,0,2);
if($prefix == '04') {
    $phoneformated = $prefix . " ".substr($num,2,4)." ".substr($num,-6);
} else {
    $phoneformated = substr($num,0,4)." ".substr($num,2,3)." ".substr($num,-3);
}

A: Compare the substring in an if statement:
if (substr($num, 0, 2) == '04') {
    $phoneformatted = substr($num, 0, 4) . " " . substr($num, 4, 3) . " " . substr($num, 7);
} else {
    $phoneformatted = substr($num, 0, 2) . " " . substr($num, 2, 4) . " " . substr($num, 6);
}

Notice that you had a typo in formatting the residential numbers, substr($num, 4, 4) should be substr($num, 2, 4).

A: Match First 04 with regex
$num = $record['busphone'];
// check first 04
if( preg_match('/^04/', $num) ) {
   // Your format
   // xxxx xxx xxx
}
else {
    // xxxxxxxxxx
}


text:
Q: Why is my loop not following its condition? so im working on this code for school and i dont know much about python. Can someone tell me why my loop keeps outputting invalid score when the input is part of the valid scores. So if i enter 1, it will say invalid score but it should be valid because i set the variable valid_scores= [0,1,2,3,4,5,6,7,8,9,10].
This code has to allow the user to enter 5 inputs for six different groups and then add to a list which will find the sum of the list and the avarage of the list.
Code:
valid_scores =[0,1,2,3,4,5,6,7,8,9,10]

for group in groups:
    scores_for_group = []
    valid_scores_loops=0
    print("What do you score for group {group_name} as a player?"\
         .format(group_name=group))
    while valid_scores_loops < 5:
        valid_scores=True
        player_input =input("* ")
        if player_input==valid_scores:
            player1.append(player_input)
            scores_for_player.append(int(player_input))
        else:
            if player_input!=valid_scores:
                valid_scores= False
                print("Invalid score!")

A: You're setting valid_scores=True, which overwrites your list of valid scores with a boolean value of True. Then, when you check player_input!=valid_scores, it will always return False.
What you want to do is get rid of the valid_scores=True line, cast the player_input to an integer using int(player_input), then check int(player_input) in valid_scores. This will return True if the player inputs a string that can be cast to one of the integers in valid_scores.

A: In your code there you are comparing a list (the valid values) with a string (the input.) This means you would have to give in a list for the statement to be correct. The right way is input in valid_inputs, which will check if any of the elements in the valid_inputs list equals the variable input. You're also assigning True to valid_inputs, which essentially deletes the list. Another error is that the player1 and scores_for_player variables aren't defined in your code. To fix your code, you'll have to cast the input to an integer, the variable storing if the input is valid must be renamed, the variables player1 and scores_for_player must be declared, and you probably should adjust your code with the fixes below.
You can also improve your code by replacing while valid_score_loops < 5 with for valid_score_loops in range(5) because you don't change valid_score_loops in loop. Another way for you to express [0,1,2,3,4,5,6,7,8,9,10] is to convert it to a tuple: (0,1,2,3,4,5,6,7,8,9,10) or express it as a range: range(0, 11).
Ranges are objects like lists and tuples that contain a sequence of numbers. The signatures of the range method are:

*

*range(end) with start equivalent to 0 and step to 1

*range(start, end) with step equivalent to 1

*range(start, end, step)
It will start at start and increase by step each time, ending before end.
Example:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(3, 5))
[3, 4]
>>> list(range(1, 6, 2))
[1, 3, 5]

There is another optimization to make to your code. If the input isn't valid, it is invalid, so you don't have to check that in your code. To fix that, you can just remove the check if the argument isn't in the valid_scores list inside the else clause.


text:
Q: java sqlite - Error: function not yet implemented for SQLite I created the following class in java to make using SQLite easier when I code.
import java.sql.*;

public class Dbm {
//We want to use the connection througout the whole class so it is
//provided as a class level private variable
private Connection c = null;
//This constructor openes or creates the database provided by the arguement
//NameOfDatabase
public Dbm(String NameOfDatabase){

try {
  //Database is checked for in project folder, if doesnt exist then creates database
  c = DriverManager.getConnection("jdbc:sqlite:" + NameOfDatabase);
} catch ( Exception e ) {
  System.err.println( e.getClass().getName() + ": " + e.getMessage() );
  System.exit(0);
}
System.out.println("Opened database successfully");
}
public void CloseDB(){
try{
c.close();
System.out.println("Closed Database Successfull");
}
catch (Exception e){
System.out.println("Failed to close Database due to error: " + e.getMessage());
}
}
 public void ExecuteNoReturnQuery(String SqlCommand){
//creates a statment to execute the query
try{
    Statement stmt = null;
stmt = c.createStatement();
stmt.executeUpdate(SqlCommand);
stmt.close();
System.out.println("Sql query executed successfull");
} catch (Exception e){
   System.out.println("Failed to execute query due to error: " +     e.getMessage());
}
}
// this method returns a ResultSet for a query which can be iterated throughd
public ResultSet ExecuteSqlQueryWithReturn(String SqlCommand){
try{

Statement stmt = null;

stmt = c.createStatement();
 ResultSet rs = stmt.executeQuery(SqlCommand);
 return rs;
}catch (Exception e){
System.out.println("An Error has ocured while executing this query" + e.getMessage());
}
return null;
}
}

Here is the main code in the program
import java.sql.*;

public class InstaText {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
 Dbm db = new Dbm("people.db");
 ResultSet rs = db.ExecuteSqlQueryWithReturn("select * from people;");
try{
   String name = "";
   int age = 0;
   String address = "";
 while (rs.isLast() == false){
 name = rs.getString("name");
 age = rs.getInt("age");
 address = rs.getString("address");
         System.out.println("Name is " + name +" age is " + age + " Address is " + address);
         rs.next();
 }
}catch (Exception e ){
System.out.println("Error: " + e.getMessage());
}
      db.CloseDB();
   }
 }

But when I execute it I get the following output:
 Opened database successfully
 Error: function not yet implemented for SQLite
 Closed Database Successfull

So how do I solve the Error "Error: function not yet implemented for SQLite"?
I am running the NetBeans Ide with the latest JDBC on mac os sierra.
Edit: Here is the output after adding e.printstacktrace(); in the catch block:
Opened database successfully
Error: function not yet implemented for SQLite
java.sql.SQLException: function not yet implemented for SQLite
Closed Database Successfull
at org.sqlite.jdbc3.JDBC3ResultSet.isLast(JDBC3ResultSet.java:155)
at instatext.InstaText.main(InstaText.java:24)

A: The problem is not your select query but the isLast() method you are using on the ResultSet instance to retrieve the result. Try the next() method, it should work :
while (rs.next()){
 name = rs.getString("name");
 age = rs.getInt("age");
 address = rs.getString("address");
         System.out.println("Name is " + name +" age is " + age + " Address is " + address);
         rs.next();
 }

You can read here :
https://github.com/bonitasoft/bonita-connector-database/issues/1
that with SQLLite, you may have some limitations with the isLast() method :

According to JDBC documentation
  (http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html)
  calls to isLast() and first() methods are forbidden if the result set
  type is TYPE_FORWARD_ONLY (e.g SQLite).


text:
Q: the website doesn't work on IIS server my website gives an error when i want to access Search.aspx page. it works on visual stdio 2010 and there is no error ,but when i added  it to iis server it doesn't.
please anyone can help i'm stack.
here is the error:

Compiler Error Message: CS0246: The type or namespace name
  'Searcharoo' could not be found (are you missing a using directive or
  an assembly reference?)

Source Error:

Line 1:  <%@ Control Language="c#" AutoEventWireup="true"%>
Line 2:  <%@ Import Namespace="Searcharoo.Common" %>


text:
Q: Find repeating dates within a specific range It's my first post on stackoverflow, so please tell me if my question doesn't fit the rules here properly.
I'm trying to implement a search in PHP/Mysql which will find all entries within a specific time range, where the entries specify on which weekdays they are valid.
This is the database model:
CREATE TABLE offer (
    offer_id int unsigned not null auto_increment,
    start int unsigned not null,
    primary key(offer_id),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE offer_weekdays (
    offer_id int unsigned not null,
    weekday tinyint unsigned not null,
    index (offer_id),
    foreign key (offer_id) references offer(offer_id)
          ON delete restrict ON update cascade,
    unique key (offer_id, weekday)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The table offer describes an entry and from when (column start (timestamp)) it is available. The table *offer_weekdays* specifies on which weekdays the entry is repeated. Each entry may be repeated on several different weekdays.
I want to implement a function which fetches all entries that are available in a specific timestamp range. My ideas to solve this problem are either slow or lacking accuracy.
I appreciate any hint. Thanks in advance!
Example:
The following entries are stored in the database:

*

*Start: 2011-01-11 10:00 (Tue), repeated: Tue

*Start: 2011-01-11 08:00 (Tue), repeated: Tue

*Start: 2011-01-12 12:00 (Wed), repeated: Wed, Thu, Fri

The searched time range is from 2012-01-10 09:00 (Tue) to 2012-01-11 11:00 (Wed).
Result:

*

*found

*not found. It fits the weekday range but is only valid at 08:00 but
the search is from 09:00.

*not found. It is valid at 12:00, but the search is until 11:00.

If the searched time range overlaps one whole week all entries should be found.

A: It sounds like you want to select when
The offer starts within the search interval, OR
(the offer starts *before* search interval and
 start time of the offer >= start time of the search range
 as long as repeating weekdays match)

I'm really, really not sure I got that right. So I'm going to take a different look at the problem. I'm also going to use SQL timestamps instead of Unix epochs, so everyone can see what's going on.
Also, I'm assuming offers end at midnight, more or less. There seems to be no other assumption that makes sense to me right now.
create table offerings (
  offer_id integer not null,
  offer_start timestamp not null,
  offer_end timestamp not null check (offer_end > offer_start),
  primary key (offer_id, offer_start)
);

-- Offer 1 starts 2012-01-10 10:00, ends 2012-01-10 23:59, repeats every Tue.
insert into offerings values (1, '2012-01-10 10:00', '2012-01-10 23:59');
insert into offerings values (1, '2012-01-17 10:00', '2012-01-17 23:59');
insert into offerings values (1, '2012-01-24 10:00', '2012-01-24 23:59');
insert into offerings values (1, '2012-01-31 10:00', '2012-01-31 23:59');

-- Offer 2 starts 2012-01-10 08:00, ends 2012-01-10 23:59, repeats every Tue.
insert into offerings values (2, '2012-01-10 08:00', '2012-01-10 23:59');
insert into offerings values (2, '2012-01-17 08:00', '2012-01-17 23:59');
insert into offerings values (2, '2012-01-24 08:00', '2012-01-24 23:59');
insert into offerings values (2, '2012-01-31 08:00', '2012-01-31 23:59');

-- Offer 3 starts 2012-01-11 12:00, ends 2012-01-11 23:59, repeats every Wed, Thu, Fri.
insert into offerings values (3, '2012-01-11 12:00', '2012-01-11 23:59');
insert into offerings values (3, '2012-01-12 12:00', '2012-01-12 23:59');
insert into offerings values (3, '2012-01-13 12:00', '2012-01-13 23:59');

insert into offerings values (3, '2012-01-18 12:00', '2012-01-18 23:59');
insert into offerings values (3, '2012-01-19 12:00', '2012-01-19 23:59');
insert into offerings values (3, '2012-01-20 12:00', '2012-01-20 23:59');

insert into offerings values (3, '2012-01-25 12:00', '2012-01-25 23:59');
insert into offerings values (3, '2012-01-26 12:00', '2012-01-26 23:59');
insert into offerings values (3, '2012-01-27 12:00', '2012-01-27 23:59');

Now the selection is dead simple.
select *
from offerings
where offer_start >= '2012-01-10 09:00'
  and offer_end   <= '2012-01-11 11:00';

offer_id   offer_start           offer_end
--
1          2012-01-10 10:00:00   2012-01-10 23:59:00

So if you can build a view that returns the same results as this offerings table, you can just query the view.
There are three lessons here.

*

*Don't let what you have confuse you. Look for what you need.

*Remember the Easter problem. (Just because you can calculate something doesn't mean you should.)

*After simplifying it to the offerings table, I'm still not sure I understand the criteria.

Later, after comments and corrections . . .
-- PostgreSQL
create table offerings (
  offer_id integer not null,
  offer_at timestamp not null,
  primary key (offer_id, offer_at)
);

-- A little data for offer 1. Inserts for 2 and 3 are similar.
insert into offerings
select 1 offering_id, '2011-01-11 10:00'::timestamp + (n || ' days')::interval offer_at
from generate_series(0, 1000, 7) n
where '2011-01-11 10:00'::timestamp + (n || ' days')::interval  < '2012-03-01';

The query, again, is dead simple. (And, with a little luck, actually correct this time.) Both these queries will return only offer number 1.
select *
from offerings
where offer_at between '2012-01-10 09:00' and '2012-01-10 11:00'

select *
from offerings
where offer_at between '2012-01-10 09:00' and '2012-01-11 11:00'

The best thing about them is that, assuming the underlying data is correct, it's obvious that the queries are doing the right thing.  And it's a lot easier to troubleshoot data than to troubleshoot code.


text:
Q: Custom SyncAdapter without using ContentProvider I want to create my own SyncAdapter, that syncs information from my app with some server.
The thing is - I want the sync itself to run from my own application's context, using my own connection to the DB, w/o the need to access my DB using a ContentProvider.
Is that possible?
Thank you,
Udi

A: Short answer:  No, it's not possible.
Long answer:  The Android platform's model for sync is to link a user Account to a ContentProvider through a SyncAdapter.  You can't set up the XML tags in AndroidManifest to be read by the Android platform without having set up all three.
Biased answer:  You should never write an app with a local DB.  ContentProvider is by far the way to go, for the reasons listed here.


text:
Q: parse datetime string to datetime object without setting a format I have a datetime string in the following format: 2021-02-25T04:39:55Z.
Can I parse it to datetime object without explicitly telling Python how?
strptime() requires you to set the format.

A: You can use the parse method from dateutil.parser module which converts a str object to a datetime object:
from dateutil.parser import parse
dtstr = '2021-02-25T04:39:55Z'
dt = parse(dtstr)
print(dt)

Output:
2021-02-25 04:39:55+00:00

A: You can use dateutil, since your date and time format looks pretty standard.
from dateutil import parser as dtparse

dtparse.parse('2021-02-25T04:39:55Z')

Which returns :
datetime.datetime(2021, 2, 25, 4, 39, 55, tzinfo=tzutc())

A: You can create a new function and call it strptime that calls datetime.strptime:
from datetime import datetime

def strptime(time_, time_fmt=None):
    time_fmt = time_fmt or r"Your Own Default Format Here"
    return datetime.strptime(time_, time_fmt)

Other than that I prefer if you utilize dateutil as recommended above.

A: pandas can also be used
import pandas as pd

datetime_str = "2021-02-25T04:39:55Z"
my_datetime = pd.to_datetime(datetime_str).to_pydatetime()
print(my_datetime)
print(type(my_datetime))
# output
# 2021-02-25 04:39:55+00:00
# <class 'datetime.datetime'>


text:
Q: Mongoid: retrieving documents whose _id exists in another collection I am trying to fetch the documents from a collection based on the existence of a reference to these documents in another collection.
Let's say I have two collections Users and Courses and the models look like this:

*

*User: {_id, name}

*Course: {_id, name, user_id}
Note: this just a hypothetical example and not actual use case. So let's assume that duplicates are fine in the name field of Course. Let's thin Course as CourseRegistrations.
Here, I am maintaining a reference to User in the Course with the user_id holding the _Id of User. And note that its stored as a string.
Now I want to retrieve all users who are registered to a particular set of courses.
I know that it can be done with two queries. That is first run a query and get the users_id field from the Course collection for the set of courses. Then query the User collection by using $in and the user ids retrieved in the previous query. But this may not be good if the number of documents are in tens of thousands or more.
Is there a better way to do this in just one query?

A: What you are saying is a typical sql join. But thats not possible in mongodb. As you suggested already you can do that in 2 different queries.
There is one more way to handle it. Its not exactly a solution, but the valid workaround in NonSql databases. That is to store most frequently accessed fields inside the same collection.
You can store the some of the user collection fields, inside the course collection as embedded  field.
Course : {
   _id : 'xx',
   name: 'yy'
   user:{
       fname : 'r',
       lname :'v',
       pic: 's'
   }
}

This is a good approach if the subset of fields you intend to retrieve from user collection is less. You might be wondering the redundant user data stored in course collection, but that's exactly what makes mongodb powerful. Its a one time insert but your queries will be lot faster.


text:
Q: How do I set the keras backend in python dynamically when loaded using supervisor How do I set the keras backend in python dynamically when loaded using supervisor?. When I load the python file using supervisor, the environmental variables seem to override the backend setup in the below code.
from keras import backend as K
import os
os.environ['KERAS_BACKEND'] = 'theano'
reload(K)

In the environmental variables, Keras backend is defined as 'tensorflow' and so the scripts starts with 'tensorflow' backend. The above set of lines doesn't work.


text:
Q: Normalize equation in NDSolve? I have numerically solved and plotted the solution to the Mathieu equation using NDSolve successfully, as below:
ClearAll["Global`*"]
a = 0.5;
b = 0.1;
w0 = 2.0;
T = 2 Pi/w0;

f[t_] := f[t] = y''[t] + (a + b  Cos[t]) y[t] == 0

s = NDSolve[{f[t], y[0] == 1, y'[0] == 0}, y, {t, 0, 1}]

Plot[Evaluate[y[t] /. s], {t, 0, 1}, PlotRange -> All]

But now I wish the normalize the period so I can plot from t=0 -> t=1 and get 1 full period. I can do this by hand, but how do I do this inside of the NDSolve function?

A: Is this what you are after? Using WhenEvent to find the extrema..
 s = Reap[
      NDSolve[{y''[t] + (a + b Cos[t]) y[t] == 0, y[0] == 1, y'[0] == 0,
         WhenEvent[ y'[t] == 0 && y[t] > 0 , Sow[{ t, y[t]}]]},
        y, {t, 0, 50}] ]
 Show[
   Plot[Evaluate[y[t] /. s[[1]]], {t, 0, 50 }, PlotRange -> All],
      ListPlot[s[[2, 1]], PlotStyle -> {Red, PointSize[.02]}]
       ]

The solution isn't exactly periodic, or it has a long period..so its not exactly clear what you mean to normalize to the period.
If I put
WhenEvent[ y'[t] == 0 && Abs[y[t] - 1] < .001 , Sow[{ t, y[t]}]]

we find "period" of ~ 170 where the solution returns to a good approximaiton to y=1,y'=0


text:
Q: Shortening code by exploiting symmetry among multiple type class instances

Context
I'm writing a Haskell module that represents SI prefixes:
module Unit.SI.Prefix where

Each SI prefix has a corresponding data type:
data Kilo = Kilo deriving Show
data Mega = Mega deriving Show
data Giga = Giga deriving Show
data Tera = Tera deriving Show

-- remaining prefixes omitted for brevity

Problem
I would like to write a function that, when applied with two SI prefixes, determines statically which of the two prefixes is smaller. For example:
-- should compile:
test1 = let Kilo = smaller Kilo Giga in ()
test2 = let Kilo = smaller Giga Kilo in ()

-- should fail to compile:
test3 = let Giga = smaller Kilo Giga in ()
test4 = let Giga = smaller Giga Kilo in ()

Initial Solution
Here's a solution that uses a type class together with a functional dependency:
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}

class Smaller a b c | a b -> c where smaller :: a -> b -> c

instance Smaller Kilo Kilo Kilo where smaller Kilo Kilo = Kilo
instance Smaller Kilo Mega Kilo where smaller Kilo Mega = Kilo
instance Smaller Kilo Giga Kilo where smaller Kilo Giga = Kilo
instance Smaller Kilo Tera Kilo where smaller Kilo Tera = Kilo

instance Smaller Mega Kilo Kilo where smaller Mega Kilo = Kilo
instance Smaller Mega Mega Mega where smaller Mega Mega = Mega
instance Smaller Mega Giga Mega where smaller Mega Giga = Mega
instance Smaller Mega Tera Mega where smaller Mega Tera = Mega

instance Smaller Giga Kilo Kilo where smaller Giga Kilo = Kilo
instance Smaller Giga Mega Mega where smaller Giga Mega = Mega
instance Smaller Giga Giga Giga where smaller Giga Giga = Giga
instance Smaller Giga Tera Giga where smaller Giga Tera = Giga

instance Smaller Tera Kilo Kilo where smaller Tera Kilo = Kilo
instance Smaller Tera Mega Mega where smaller Tera Mega = Mega
instance Smaller Tera Giga Giga where smaller Tera Giga = Giga
instance Smaller Tera Tera Tera where smaller Tera Tera = Tera

The above solution appears to solve the problem correctly, however it has a downside: the number of type class instances is quadratic w.r.t. the number of types.
Question
Is there any way to reduce the number of type class instances to be linear w.r.t. the number of types, perhaps by exploiting symmetry?
It may be that it's more appropriate to use Template Haskell here, in which case, feel free to suggest that as a solution.
Thanks!

A: It could probably be argued that TH is more appropriate in cases like this. That said, I'll do it with types anyhow.
The problem here is that everything is too discrete. You can't iterate through the prefixes to find the right one, and you're not expressing the transitivity of the ordering you want. We can solve it by either route.
For a recursive solution, we first create natural numbers and boolean values at the type level:
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}

data No = No deriving (Show)
data Yes = Yes deriving (Show)

newtype S nat = Succ nat deriving (Show)
data Z = Zero deriving (Show)

type Zero  = Z
type One   = S Zero
type Two   = S One
type Three = S Two

A bit of simple arithmetic:
type family Plus x y :: *
type instance Plus x Z = x
type instance Plus Z y = y
type instance Plus (S x) (S y) = S (S (Plus x y))

type family Times x y :: *
type instance Times x Z = Z
type instance Times x (S y) = Plus x (Times y x)

A "less than or equal to" predicate, and a simple conditional function:
type family IsLTE n m :: *
type instance IsLTE Z Z = Yes
type instance IsLTE (S m) Z = No
type instance IsLTE Z (S n) = Yes
type instance IsLTE (S m) (S n) = IsLTE m n

type family IfThenElse b t e :: *
type instance IfThenElse Yes t e = t
type instance IfThenElse No t e = e

And conversions from the SI prefixes to the magnitude they represent:
type family Magnitude si :: *
type instance Magnitude Kilo = Three
type instance Magnitude Mega = Three `Times` Two
type instance Magnitude Giga = Three `Times` Three

...etc.
Now, to find the smaller prefix, you can do this:
type family Smaller x y :: *
type instance Smaller x y = IfThenElse (Magnitude x `IsLTE` Magnitude y) x y

Given that everything here has a one-to-one correspondence between the type and the single nullary constructor inhabiting it, this can be translated to the term level using a generic class like this:
class TermProxy t where term :: t
instance TermProxy No where term = No
instance TermProxy Yes where term = Yes
{- More instances here... -}

smaller :: (TermProxy a, TermProxy b) => a -> b -> Smaller a b
smaller _ _ = term

Filling in the details as needed.

The other approach involves using functional dependencies and overlapping instances to write a generic instance to fill in gaps--so you could write specific instances for Kilo < Mega, Mega < Giga, etc. and let it deduce that this implies Kilo < Giga as well.
This gets deeper into treating functional dependencies as what they are--a primitive logic programming language. If you've ever used Prolog, you should have the rough idea. In some ways this is nice, because you can let the compiler figure things out based on a more declarative approach. On the other hand it's also kind of terrible because...

*

*Instances are chosen without looking at constraints, only the instance head.

*There's no backtracking to search for a solution.

*To express this sort of thing you have to turn on UndecidableInstances because of GHC's very conservative rules about what it knows will terminate; but you then have to take care not to send the type checker into an infinite loop. For instance, it would be very easy to do that by accident given instances like Smaller Kilo Kilo Kilo and something like (Smaller a s c, Smaller t b s) => Smaller a b c--think about why.

Fundeps and overlapping instances are strictly more powerful than type families, but they're clumsier to use overall, and feel somewhat out of place compared to the more functional, recursive style the latter uses.

Oh, and for completeness' sake, here's a third approach: This time, we're abusing the extra power that overlapping instances gives us to implement a recursive solution directly, rather than by converting to natural numbers and using structural recursion.
First, reify the desired ordering as a type-level list:
data MIN = MIN deriving (Show)
data MAX = MAX deriving (Show)

infixr 0 :<
data a :< b = a :< b deriving (Show)

siPrefixOrd :: MIN :< Kilo :< Mega :< Giga :< Tera :< MAX
siPrefixOrd = MIN :< Kilo :< Mega :< Giga :< Tera :< MAX

Implement an equality predicate on types, using some overlapping shenanigans:
class (TypeEq' () x y b) => TypeEq x y b where typeEq :: x -> y -> b
instance (TypeEq' () x y b) => TypeEq x y b where typeEq _ _ = term

class (TermProxy b) => TypeEq' q x y b | q x y -> b
instance (b ~ Yes) => TypeEq' () x x b
instance (b ~ No) => TypeEq' q x y b

The alternate "is less than" class, with the two easy cases:
class IsLTE a b o r | a b o -> r where
    isLTE :: a -> b -> o -> r

instance (IsLTE a b o r) => IsLTE a b (MIN :< o) r where
    isLTE a b (_ :< o) = isLTE a b o

instance (No ~ r) => IsLTE a b MAX r where
    isLTE _ _ MAX = No

And then the recursive case, with an auxiliary class used to defer the recursive step based on case analysis of the type-level boolean:
instance ( TypeEq a x isA, TypeEq b x isB
         , IsLTE' a b isA isB o r
         ) => IsLTE a b (x :< o) r where
    isLTE a b (x :< o) = isLTE' a b (typeEq a x) (typeEq b x) o

class IsLTE' a b isA isB xs r | a b isA isB xs -> r where
    isLTE' :: a -> b -> isA -> isB -> xs -> r

instance (Yes ~ r) => IsLTE' a b Yes Yes xs r where isLTE' a b _ _ _ = Yes
instance (Yes ~ r) => IsLTE' a b Yes No xs r where isLTE' a b _ _ _ = Yes
instance (No ~ r) => IsLTE' a b No Yes xs r where isLTE' a b _ _ _ = No
instance (IsLTE a b xs r) => IsLTE' a b No No xs r where
    isLTE' a b _ _ xs = isLTE a b xs

In essence, this takes a type-level list and two arbitrary types, then walks down the list and returns Yes if it finds the first type, or No if it finds the second type or hits the end of the list.
This is actually kind of buggy (you can see why if you think about what happens if one or both types aren't in the list), as well as prone to failing--direct recursion like this uses a context reduction stack in GHC that is very shallow, so it's easy to exhaust it and get a type-level stack overflow (ha ha, yes, the joke writes itself) instead of the answer you wanted.

A: You can map your types to type level natural numbers and then do the comparisons using those. That should make it linear as you only have to specify one instance for each type mapping it to the corresponding number.
The type arithmetic page on the Haskell Wiki has some nice examples of working with type level natural numbers. It would be a good place to start.
Also note that there is already the popular package dimensional on Hackage for working with SI units in a similar way. It might be worthwhile to have a look at how this is implemented in their code.


text:
Q: Adding a Detail line total field to a screen I'm trying to simply add a new total field to the Purchase Receipts screen header (the Total Amt that was removed in a more recent release of Acumatica for some reason).  It seems like this should have been pretty straightforward, but I haven't been able to get any method I've tried to work; and before I try to manually total all of the detail lines myself in custom code when any change is made in the detail lines, I wanted to find out how to do this the proper way.  I've tried the following methods so far that just don't seem to work and my total field remains at zero:
1.)  PXFormula on the new custom field on a POReceipt DAC extension (I also tried using PXUnboundFormula since this is an unbound field):
    [PXFormula(typeof(Mult<POReceiptLine.unitCost, POReceiptLine.receiptQty>), typeof(SumCalc<POReceiptExt.usrTotalAmt>))]

2.)  PXFormula on a new custom field on a POReceiptLine DAC extension (I also tried using PXUnboundFormula since this is an unbound field):
    [PXFormula(typeof(Mult<POReceiptLine.unitCost, POReceiptLine.receiptQty>), typeof(SumCalc<POReceiptExt.usrTotalAmt>))]

3.) PXDBCalced on a new custom field on a POReceiptLine DAC extension to perform the calc on each line:
    [PXDBCalced(typeof(Mult<POReceiptLine.unitCost, POReceiptLine.receiptQty>), typeof(decimal))]

then try to total that with a new view
    public PXSelectGroupBy<POReceiptLine, Where<POReceiptLine.receiptNbr, Equal<Required<POReceipt.receiptNbr>>>,Aggregate<GroupBy<POReceiptLine.receiptNbr, Sum<POReceiptLineExtension.usrLineAmt>>>> Totals;

4.) Defining a dataview method to build the view contents and total manually.
What is the proper method?  Or, even if you could point me to the code from the previous release that calculated this total, I can possibly use that.

A: The following post finally led me to a solution that worked for me --> https://stackoverflow.com/a/36870660/7376238 by summing the total manually in the RowSelected event handler.


text:
Q: What's the difference between two ways of adding property to an existing js object? Let's say we need to add a property to an existing js object
var billingData = {}

In my case, I want to store input value in the js object
Here's the basic input
<input type="text" class="form-control" id="billingFullName">

We, basically, have two ways to add the property to the js object:
The first one:
billingData["billingFullName"] = document.getElementById('billingFullName').value

And the second one:
billingData.billingFullName = document.getElementById('billingFullName').value

What's the difference between them?
I'm asking, because when I was submitting the js object using AJAX to MVC Controller, where properties where added using the [] notation, the model in the Controller appeared to be null. Whereas, the dot notation appeared to solve the issue and I'm wondering why..

A: Typically you use bracket notation when you need to define a property dynamically such as with a variable or if the key is not in proper format for dot notation:
const obj = {}
const someKey = 'key'
obj[someKey] = 'somevalue'

console.log(obj.key) // 'somevalue'
console.log(obj.someKey) // undefined

Dot notation is when you already know the key:
const obj = {}
object.key = 'someValue'


text:
Q: Modelling of a flow network with a positional constraint While I do realise pasting an exercise question in here is not exactly perfect form, I am desperate and I wil try anyway. So here it goes:
Consider a set of n mobile computing clients in a town with k mobile base stations. Every client needs to be connected to one exactly one base station. Each of the n clients as well as each of the k base stations is specified by its (x,y) coordinates in the plane. Each client needs to be connected to exactly one base station. For a given parameter r, a client can only be connected to a base station that is within distance r from the client. At the same time, no base station can handle more than L clients being assigned to it. Design a polynomial-time algorithm for the following problem: Given the positions of the n clients and k base stations, as well as the range and load parameters r and L, respectively, decide whether all clients can be connected to the base stations, subject to the range and load conditions as described above. Argue that your algorithm is correct.
I understand that I have to use Max-Flow theory somehow, and I am guessing the flow network would be a bipartite graph with a constraint on the degrees of one of the two partitions to be <= L. But how do I model a positional variable like r into it? Any help would be greatly appreciated.

A:
While I do realise pasting an exercise question in here is not exactly perfect form, I am desperate and I wil try anyway.

I am a official tutor in algorithmic graph theory. I'll save you. :-) We construct a usual flow model $\mathcal F$ for your problem as follows. Let $s$ and $t$ be a sourse and a target, respectively, of a flow network, $c_1,\dots, c_n$ be the clients, and $b_1,\dots, b_k$ be the base stations. Introduce edges $(s, c_1),\dots, (s, c_n)$ of capacity $1$ each and $(b_1,t),\dots, (b_k,t)$ of capacity $L$ each. Also introduce edges $(c_i,b_j)$ iff the distance between $c_i$ and $b_j$ is at most $r$. It is easy to check that all clients can be connected to the base stations, subject to the range and load conditions iff maxflow in $\mathcal F$ is $n$ (one way it is obvious, but the other way we use Integrality Theorem stating that if all capacities are integral, then there is an integral maximum flow). There are the following polynomial-time algorithms to find a maxflow in $\mathcal F$.


text:
Q: Https on JSF 2, for protected resources and login I have a managed bean with 2 attribute: userName & password (with its respective getters and setters methods), and a login() method that access the database to verify login credentials.
My question is, when the user clicks the "login" button, the action must go through https protocol. How can I achieve this with JSF 2?
Also, if I want to have some Faces to be protected (under https protocol), how do I achieve this? Is there a filter that enables me to do this?
Thanks in advance.

A: You can define a security constraint in the web.xml of your application:
<security-constraint>
   <web-resource-collection>
      <web-resource-name>SecureConnection</web-resource-name>
        <url-pattern>*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
      </web-resource-collection>
      <auth-constraint/>
      <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
</security-constraint>

Adapt the url-pattern to contain your login page and all other secured pages. The use of https is defined by the user-data-constraint.
From the Java EE tutorial:

If you specify CONFIDENTIAL or
  INTEGRAL as a security constraint, it
  generally means that the use of SSL is
  required and applies to all requests
  that match the URL patterns in the web
  resource collection, not just to the
  login dialog box.

If you wrote your own login() method and are using Glassfish, you could take a look at container-based authentication with a JDBCRealm as alternative login approach.


text:
Q: Changes user's email on crowd doesn't apply in confluence It's my configuration:
Atlassian Crowd Version: 2.0.2 (Build:#409 - 06-10-2009)
Atlassian Confluence 3.0.2
I can't change users' emails in Confluence because I use Crowd as external user management. So I have to change users' emails in Crowd but changes doesn't apply in Confluence. Even users has access to crowd user console and can login to Crowd and view their profile and edit their email password but changed emails doesn't apply in Confluence.
What should I do? Is it a bug?
Also I should mention that emails contains dot character(.).
I posted my question to Atlassian forum 3 days ago but there's no answer yet!
http://forums.atlassian.com/message.jspa?messageID=257342171


text:
Q: Enterprise apps for WP7? How are people handling the distribution for Enterprise apps on WP7?
I have an app that is real basic and only has some static info, but I don't want to put it in the Public Market with the Hidden option enabled because that doesn't seem secure enough.  It seems like if there was a way to verify that the user has a company email account setup on the phone on startup that would unlock the app, but I dont think thats possible.

A: There's currently no features in assisting for enterprise apps. You'll have to verify the authenticity of the user in your application, by requesting credentials, or requiring the application to be on a company network (or visa versa).
As for distribution, hidden publication is the only real option you have, as beta-distribution is limited to a few accounts.


text:
Q: How to ignore blank lines when printing lines of a file in python? We got an exercise in class in which we need to print out the first x letters of the first y lines of a text file. That itself I managed to do with the code below, but the issue is that the exercise says "Your function should not print empty lines, e.g.  lines that only contain the newline character "\n"." - Basically meaning our code should only print the first y lines which are not blank and ignore the blank lines in the counting process.
How could I change/extend my code to achieve that?
My code so far:
def print_file(name,int1,int2=None):
    file_1 = open(name, "r")

    if int2 is None:
        for line in file_1.readlines():
            print(line[:int1-1])

    else:
        lines = file_1.readlines()
        lines = lines[0:int2+1]

        for line2 in lines:
            print(line2[0:int1-1])

print(print_file("Adventures of Sherlock Holmes.txt", 10, 6))


text:
Q: How to use value of variable as variable? I want to use value of the variable as a new variable. But i don't know how to use it.
DECLARE
    example1 varchar2(10) = 'AAA';
    AAA varchar2(10) = 'BBB';
BEGIN
    dbms_output.put_line(?example1); -- Output must be 'BBB'.
END;

Which character must be come instead of "?" to achieve 'BBB' output? Do you have any idea about that?
Thanks.

A: Perhaps you can achieve what you want with an associative array.
declare
    type string_aa is table of varchar2(100) index by varchar2(100);
    my_list string_aa;

    example1 varchar2(10) := 'AAA';

begin
    my_list('AAA') := 'BBB';

    dbms_output.put_line(my_list(example1));
end;

A: One method to solve this problem may be to use dynamic SQL to access the variables.
DECLARE
example1 varchar2(10) := 'AAA';
AAA varchar2(10) := 'BBB';
x varchar2(1000);
BEGIN
  x := 'declare '||example1||' varchar2(10) := '''||AAA||'''; begin dbms_output.put_line('||example1||'); end;';
  execute immediate x;
END;


text:
Q: Excel of updating dates within a cell with various formulas I have a current summary tab that is using this current formula
Currently, I have a report that is dated back to 2 weeks
=COUNTIFS(Industrial!A:A,">9/6/2021",Industrial!A:A,"<9/12/2021",Industrial!F:F,"Sold")
I am trying to have the dates update now to reflect the new dates below
=COUNTIFS(East!A:A,">9/13/2021",East!A:A,"<9/19/2021",East!F:F,"Sold")
The hardest part is all the cells have a slightly different region within the formula and we are trying to update the dates automatically within the report. We want the dates to update for 2 2weeks prior, last week and the current week. The hardest part is the formula is pulling from multiple master sheets and each cell has its on region tagged in.

A: It is difficult to follow your question likely because of language barriers. However assuming you are asking how to manage updating dates in the formulas to reflect a new period I would suggest removing the dates from the formulas and instead referencing cells that contain dates You could take for example 9/6/2021 and put it in a cell $B$1 (better yet name it 'startdate' and put 9/12/2021 in cell $B$2 (name it 'enddate'). Then you will need to do a find/replace to update your formulas to reference the two cells (or the names) but you won't need to do that again). The next time you want to update the dates simply update those two cells instead of all the formulas.