text:
Q: Progress bar never displays I simply want a nondeterministic progressbar that becomes visible and shows some "activity" to indicate a query is running, and then, when the query is through, goes back to being invisible. Seems simple enough; but with this code:
try
{
    Cursor.Current = Cursors.WaitCursor;
    progressBarChanges.Value = 50;
    progressBarChanges.Step = 20;
    progressBarChanges.Visible = true;
    ... // the meat of the code, where the query is being done, elided
} finally
{
    progressBarChanges.Visible = false;
    Cursor.Current = Cursors.Default;
}

...the progress bar never displays, even though the query takes awhile to run. The progress bar is on a DGV. I realize my progress code is a bit lame, but first things first - I just want the darned thing to show something for starters.
UPDATE
I am setting the progressBar to visible way before I'm calling the BackgroundWorker proc that runs the query:
progressBarChanges.Value = 50;
progressBarChanges.Step = 20;
progressBarChanges.Visible = true;
. . .
if (args.KeyCode == Keys.Enter)
{
    if (ValidEntryForCRID(textBoxID.Text))
    {
        RetrieveAndBindPlatypusData();
        var tb = (TextBox)Controls.Find("textBoxDuckbill", true).First();
        if (tb != null)
        {
            tb.Focus();
        }
        if ((!string.IsNullOrWhiteSpace(textBoxID.Text)) &&
            (backgroundWorkerShowChanges.IsBusy != true))
        {
            backgroundWorkerShowChanges.RunWorkerAsync();
        }
    . . .

...yet the progressBar is never becoming visible (unless I never set it back to visible = false after the DGV's DataSource is assigned the OracleDateTable value of the returned query/result set). If I comment that out, it then (belatedly) finally shows up, apparently thinking (erroneously) "better late than never."
Is there a way to force Windows to "pay attention" to the "progressBarChanges.Visible = true;" line right away? Something like a .ProcessMessages() or this.Refresh or...???

A: This is happening because you are not giving the UI thread time to update. You are updating to visible and immediately running your code. The code should run on a background thread and send update messages.
To elaborate:
When you set the Visible property, the UI thread does not actually update until the end of that current logic. So, what is happening is this:

*

*Visible

*Run process

*Not Visible

*Code is complete, so UI is unfrozen and updated...with the last state being Not Visible

What you want is:

*

*Visible

*Kick off new thread to run meat

*UI Code is complete, so UI is unfrozen and updates the bar to Visible

Then this:

*

*==>New thread runs meat sending updates to the UI thread so that the progress bar can update

Then this:

*

*New thread ends and in its final method sets Not Visible

*UI Code is complete, so UI is unfrozen and updates the bar to Not Visible

A Task or Backgroundworker should be pretty easy to implement this with.
UPDATE FOR CODE TO SHOW CONSTANT SCROLL
I believe you are only missing that the progressbar's style should be ProgressBarStyle.Marquee. If you already are offloading the work to a backgroundworker, then the rest should just work
    public Form1()
    {
        InitializeComponent();
        this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
        this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
        progressBar1.Enabled = progressBar1.Visible = false;
        progressBar1.Style = ProgressBarStyle.Marquee;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        progressBar1.Visible = true;
        progressBar1.Enabled = true;
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        System.Threading.Thread.Sleep(10000);
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.Visible = progressBar1.Enabled = false;
    }

A: This is how I got it to work:
I enable the ProgressBar just before the BackgroundWorker call:
progressBarChanges.Visible = true;
backgroundWorkerShowChanges.RunWorkerAsync();

The BackgroundWorker code gets the OracleDataTable from the DB:
private void backgroundWorkerShowChanges_DoWork(object sender, System.ComponentModel.DoWorkEventArgs args)
{
    holdChanges = GetChangesMade(textBoxID.Text);
}

The BackgroundWorker's "completed" event updates the UI:
private void backgroundWorkerShowChanges_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs args)
{
    PopulateChangesGrid();
}

In PopulateChangesGrid(), after assigning the OracleDataTable object to the DGV, I set the Progress bar invisible:
private void PopulateChangesGrid()
{
    dgvPlatypi.DataSource = holdChanges;
    progressBarChanges.Visible = false;
}

It works like a charm (<-- not necessarily a reference to Windows 8 "Metro" charms).


text:
Q: Google Big query : run parallel stored procedure with in stored procedure I have a Google stored procedure, and in that procedure, I need to do this:

*

*In the stored procedure, call two other stored procedures in parallel (each stored procedure takes around 30 minutes to run)

*Once these two stored procedures have completed, remaining logic will continue

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you clear the Response buffer in ColdFusion? I'm looking for something like Response.Clear().

A: You can reset the output buffer using the cfcontent tag with the reset argument:
<cfcontent reset="true">

A: This will clear the response body and prevent the output of buffered content -
<cfset GetPageContext().getCFOutput().clear()>

A: The two existing answers (<cfset GetPageContext().getCFOutput().clear()> and <cfcontent reset="true">) will reset the main content buffer, but those commands will not reset the header buffers (i.e. content that ColdFusion automatically inserts into the <head> element such as <script> tags when using <cfchart>).
To reset everything, you can use either of the following approaches:
<cfcontent reset="true" resethead="true">

or
<cfset getPageContext().getCFOutput().clearAll()>
<cfset getPageContext().getCFOutput().clearHeaderBuffers()>

These approaches are not documented (so possible to change in future version -- though unlikely) and these approaches are unlikely to be portable to other CFML engines, but I have not found any documented approach for clearing the header buffers.
Related answer: Is there a way to prevent cfchart from forcing js into response content?


text:
Q: Strange behavior with contours in Cartopy polar stereographic plot I'm trying to create a contour plot on a North Polar Stereographic map projection using Cartopy. I used add_cyclic_point() to try and get around the problem of having a gap between longitude 0 and longitude 35X and followed an example from the documentation (always_circular_stereographic) to set up the map axes.
When I call plt.contour, I get the following plot. It looks like the contour plotter is getting confused at the transition from 355 to 0 longitude, and sends contour lines around the globe.

Here is my code:
import numpy as np
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
import matplotlib.pyplot as plt

def define_map():
    from matplotlib.path import Path

    fig = plt.figure(figsize=(10,10))
    ax = plt.axes(projection=ccrs.NorthPolarStereo())
    ax.coastlines()

    # From example: http://scitools.org.uk/cartopy/docs/latest/examples/always_circular_stereo.html
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)
    return(fig, ax)
lats = np.arange(65,91,5)
lons = add_cyclic_point(np.arange(0,359,5))
data = add_cyclic_point(np.random.random((len(lats),len(lons)-1)))

fig, ax = define_map()
plt.contour(lons,lats,data,5,transform=ccrs.PlateCarree(), cmap=plt.cm.Blues)
plt.colorbar(fraction=0.05, shrink=0.9)
plt.show()

How do I do a Cartopy contour plot properly?
Also, why do the contours only show up with transform=ccrs.PlateCarree() and not with transform=ccrs.NorthPolarStereo()?

A: Apparently the add_cyclic_point function is just for the data; the contour routine treats 0 different than 360. So the simple fix is to set
lons = np.arange(0,360,5)


text:
Q: Adding click event handlers recursively I have an element #standardBox
#standardBox.click --> replaces itself with #newBox
#newBox.click --> replaces itself with #standardBox
But this latest #standardBox has no click event listener. I want it to have an on click event listener and its subsequently created elements too. This is getting into a recursive loop, which I don't know how to address.
I'm using this for header with standard contents, which gets replaced by something intermediate/new contents, which again is to get back to standard contents ...
Thanks.
HTML

CSS
html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}
#container {
    position: relative;
    height: 5em;
    width: 5em;
    background: #C5CAE9;
}
#standardBox {
    position: absolute;
    top: 20%;
    right: 20%;
    bottom: 20%;
    left: 20%;
    background: #ffffff;
    cursor: pointer;
}
#newBox {
    height: 3em;
    width: 3em;
    background: #000000;
    cursor: pointer;
}

JAVASCRIPT


text:
Q: How to properly configure the application in electron for compatibility with windows 7, through the command prompt? I am creating an application in electron, but I can only send notifications if the application is in compatibility mode with windowns 7
I found a way to perform compatibility mode configuration through the command prompt (REG.EXE ADD "HKLM \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ AppCompatFlags \ Layers" / v "C: \ Program Files (x86) \ Application \ Application.EXE "/ t REG_SZ / d" WIN7RTM "/ f),
however this setting is not working the same way when manually configuring compatibility mode.
When I perform compatibility mode configuration through properties / compatibility / compatibility mode and change to windows 7, the notifications work perfectly, however with the command REG.EXE ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" /v "C:\Program Files (x86)\Aplication\Aplication.exe" /t REG_SZ /d "WIN7RTM" /f The application does not behave in the same way, although it is observed in the properties, the mode is apparently configured the same way.
I need to know if there is a need to put any more information on my command, or if I happen to be doing it totally wrong. Would you help me?


text:
Q: Call variable from within a string I'm trying to use Powershell to open AD U&C in another domain (/domain switch) using a variable.
No domain switch used, works (just not the domain I want):
Start-Process powershell -Credential $domvar'\'$id -ArgumentList '-command &{Start-Process mmc -verb Runas -ArgumentList "C:\Windows\System32\dsa.msc"}'

Defining a specific domain in an array works:
Start-Process powershell -Credential $domvar'\'$id -ArgumentList '-command &{Start-Process mmc -verb Runas -ArgumentList @("C:\Windows\System32\dsa.msc" /domain=domain.com)}'

BUT
Adding /domain=$domain does not (double quoting everything in the ArgumentList did not help):
Start-Process powershell -Credential $domvar'\'$id -ArgumentList '-command &{Start-Process mmc -verb Runas -ArgumentList "C:\Windows\System32\dsa.msc" /domain=$domain}'

NOR
Changing domain.com to my variable $domain:
Start-Process powershell -Credential $domvar'\'$id -ArgumentList '-command &{Start-Process mmc -verb Runas -ArgumentList @("C:\Windows\System32\dsa.msc" /domain=$domain)}'

Also, a new window pops up and I see the red error font but I'm not sure how to grab that information. Tried using debugging and stepping into but didn't work.

A: In powershell single quotes do NOT perform variable substitution.  In your case you can probably just change the single quotes around your command to double quotes.  For the double quotes inside the quoted string you can include the $ as a literal by preceding it with a backtick.
"-command &{Start-Process mmc -verb Runas -ArgumentList `"C:\Windows\System32\dsa.msc`" /domain=$($domain)}"


text:
Q: Generate TSQL random dates between a range Generate 650 dates between 3rd Jan to 16th Jan 2023 and exclude weekends
and time between working hours i.e 9 AM to 5 PM
randomised to the day and right to milliseconds .

A: WITH CTE AS (
  SELECT TOP 1000
    DATEADD(MILLISECOND, ABS(CHECKSUM(NEWID())) % 1000, DATEADD(MINUTE, ABS(CHECKSUM(NEWID())) % 480 + 540,
    DATEADD(DAY, ABS(CHECKSUM(NEWID())) % 14, '2023-01-03 00:00:00'))) AS RandomDate
  FROM
    sys.all_objects
)
SELECT
 TOP 650 RandomDate
FROM
  CTE
WHERE
  DATEPART(WEEKDAY, RandomDate) NOT IN (1, 7) -- exclude weekends
  AND RandomDate BETWEEN '2023-01-03 09:00:00' AND '2023-01-16 17:00:00'
ORDER BY
  RandomDate;

In this query, the DATEADD function is used three times to generate a random date and time between 3rd Jan 2023 and 16th Jan 2023 with a random milliseconds value. The first DATEADD call adds a random number of days (ABS(CHECKSUM(NEWID())) % 14) to 3rd Jan 2023, generating a random date between 3rd Jan 2023 and 16th Jan 2023. The second DATEADD call generates a random time between 9:00 AM and 5:00 PM by adding a random number of minutes (ABS(CHECKSUM(NEWID())) % 480 + 540) to the random date generated in the first DATEADD call. The third DATEADD call adds a random milliseconds value. The WHERE clause is then used to exclude weekends and to further restrict the random dates and times to only those between 9:00 AM and 5:00 PM on each date.


text:
Q: What is method interception with regards to mocking? I have read a lot about mocking, particularly using Rhino Mocks and have learned that Rhino Mocks can only mock interface methods which are virtual or virtual methods in concrete classes.  I have read that the reason for this is because Rhino mocks can't intercept non-virtual methods and this is where I am stuck.  What does it mean by intercepting methods?  How does intercepting methods actually work with regards to mocking (Rhino Mocks in particular)

A: Basically the idea is that it creates a 'behind the scenes' class that overrides any virtual or interface methods and plugs in 'mock' code into them.
Highly simplified example/overview
if you have (based on your comment question)
public EmailHelper
{
    public virtual int SendEmail( MailMessage message)
    {
        var server = ConnectToServer();
        int statusCode = server.SubmitEmail( message );
        return statusCode;
    }
}

and then in a test (I forget Rhino's syntax for this, but this is close enough)
var mock = Mocks.CreateMockFor<EmailHelper>();
Expect.Call(mock.SendEmail).Return(5);

behind the scenes it will use reflection to load up the SomeClass Type object, search it for interface implementations and virtual methods and generate a class something like
public MockEmailHelper
{
    public override int SendEmail( MailMessage message )
    {
        return 5;
    }
}

So as you can see, when you call the mock version of SendEmail, it wont connect to server etc, it will just do what you told it to, so you can test your code that depends on the 'email module' without actually sending email.


text:
Q: Swift: Map AsyncStream into another AsyncStream Update
The accepted answer did not directly answer the original question, but helped resolve the underlying issue I tried to solve: I wanted to map an AsyncStream (which is an AsyncSequence) into another AsyncSequence with element type T2. I added some details in this comment.
Original question
I would like to map an AsyncStream into another AsyncStream. I wonder if there is a .map that can be used just like for arrays.
Quoting from Apple documentation:

Creates an asynchronous sequence that maps the given closure over the asynchronous sequence's elements.

To code below has an error:
Cannot convert value of type 'AsyncMapSequence<AsyncStream<Int>, Int>' to specified type 'AsyncStream<Int>'

As I understand, it is because the return type of .map in this case is AsyncMapSequence<...> instead of AsyncStream<Int>.
Is there a way to just map an AsyncStream<T1> into an AsyncStream<T2> with a transform function T1 → T2, as it works for mapping Array<T1> into Array<T2>?
Thank you in advance!
import SwiftUI

@main
struct MacosPlaygroundApp: App {
    var body: some Scene {
        WindowGroup("Playground") {
            Text("Hello World")
                .padding(100)
                .onAppear {
                    Task {
                        let numStream: AsyncStream<Int> = AsyncStream { continuation in
                            Task {
                                try await Task.sleep(nanoseconds: 1_000_000_000)
                                continuation.yield(0)
                                try await Task.sleep(nanoseconds: 1_000_000_000)
                                continuation.yield(1)
                                try await Task.sleep(nanoseconds: 1_000_000_000)
                                continuation.yield(2)
                                continuation.finish()
                            }
                        }

                        let doubleNumStream: AsyncStream<Int> = numStream.map { num in
                            return 2 * num
                        }

                        for await doubleNum in doubleNumStream {
                            print("Next num is \(doubleNum)")
                        }

                    }
                }
        }
    }
}

A: How about extending AsyncStream?
extension AsyncStream {
    public func map<Transformed>(_ transform: @escaping (Self.Element) -> Transformed) -> AsyncStream<Transformed> {
        return AsyncStream<Transformed> { continuation in
            Task {
                for await element in self {
                    continuation.yield(transform(element))
                }
                continuation.finish()
            }
        }
    }

    public func map<Transformed>(_ transform: @escaping (Self.Element) async -> Transformed) -> AsyncStream<Transformed> {
        return AsyncStream<Transformed> { continuation in
            Task {
                for await element in self {
                    continuation.yield(await transform(element))
                }
                continuation.finish()
            }
        }
    }
}

A: You said:

Let's say I have a function, input is some async sequence of data of a certain type T, and for each such T item, it does something with it... For this function, it doesn't matter how that async sequence was calculated, e.g. whether it was mapped from another sequence or not. Ideally I would type it as AsyncSequence<T> (T being a specific type in my actual code), but AsyncSequence doesn't take type parameters.

I would suggest that you define this function to use AsyncSequence, e.g., here is a method that prints the values of the sequence:
func printSequence<S: AsyncSequence>(_ sequence: S) async throws where S.Element == Int {
    for try await value in sequence {
        print("Next num is \(value)")
    }
    print("done")
}

This will work with any AsyncSequence of Int, either the original numStream or the mapped doubleNumStream.
Then, as Sweeper said, you can just use the existing map of AsyncSequence:
Task {
    let numStream = AsyncStream<Int> { continuation in
        Task {
            try await Task.sleep(nanoseconds: 1_000_000_000)
            continuation.yield(0)
            try await Task.sleep(nanoseconds: 1_000_000_000)
            continuation.yield(1)
            try await Task.sleep(nanoseconds: 1_000_000_000)
            continuation.yield(2)
            continuation.finish()
        }
    }

    let doubleNumStream = numStream.map { num in             // let it just infer the type for you
        return 2 * num
    }

    try await printSequence(doubleNumStream)
}

A: You can add:
extension AsyncStream {
    init<Sequence: AsyncSequence>(_ sequence: Sequence) where Sequence.Element == Element {
        self.init {
            var iterator: Sequence.AsyncIterator?
            if iterator == nil {
                iterator = sequence.makeAsyncIterator()
            }
            return try? await iterator?.next()
        }
    }

    func eraseToStream() -> AsyncStream<Element> {
        AsyncStream(self)
    }
}

And then do
let doubleNumStream: AsyncStream<Int> = numStream
    .map { num in
        return 2 * num
    }
    .eraseToStream()


text:
Q: Laravel 5.4, AJAX Not Erroring When it Should I've been trying to follow quite a few different articles on how to deal with AJAX requests in Laravel. They're all different..
I have one that is finally not throwing me a 500 error, but it actually does not throw validation errors in the way you'd think.
My code will always default to the AJAX success part, not the error part, and display a "Success" in the console but also display the error JSON thrown back by my controller.
I have no idea what's going on my dudes. If you could help me out, it would be much appreciated!
Controller
public function store(Request $request)
    {
        if ($request->ajax())
        {
            $rules = array(
                "name"      => "required|string|unique:brands|max:255",
                "contact"   => "string|max:255",
                "email"     => "string|max:255",
                "phone"     => "max:12"
            );

            $validator = Validator::make(Input::all(), $rules);

            if ($validator->fails())
            {
                return \Response::json(array(
                    "errors" => $validator->getMessageBag()->toArray()
                ));
            }
            else
            {
                // Submit to the database
                $brand = new Brand();

                $brand->name        = $request->name;
                $brand->contact     = $request->contact;
                $brand->email       = $request->email;
                $brand->phone       = $request->phone;
                $brand->created_by  = auth()->user()->id;
                $brand->updated_by  = auth()->user()->id;

                $brand->save();

                return \Response::json($brand);
            }
        }
        else
        {
            return \Response::json(array("error" => "response was not JSON"));
        }
    }

Route
// Brands
Route::get('/brands', 'BrandsController@index')->name('brands');
Route::post('/brands/store', 'BrandsController@store');

AJAX (Embedded via {{ Html::script() }})
$(document).ready(function() {

    /**
    * Save a new brand to the database via AJAX
    */
    var url = "/brands/store";

    $("#save").click(function (e) {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
            }
        });

        e.preventDefault();

        var formData = {
            name:       $('#name').val(),
            contact:    $('#contact').val(),
            email:      $('#email').val(),
            phone:      $('#email').val(),
        }

        var type = "POST";

        console.log(formData);

        $.ajax({

            type: type,
            url: url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log("Error: ", data);
                console.log("Errors->", data.errors);
            }

        });

    });

});

HTML (Snippet, as it is a modal)

            Create a Brand

        <form id="create_brand" name="create_brand" class="form" novalidate="">

                {{ Form::label("name", "Name", ["class" => "field-label is-normal"]) }}

                            {{ Form::text('name', null, ["class" => "input", "id" => "name", "required" => "required", "autofocus" => "autofocus"]) }}

                {{ Form::label("contact", "Contact", ["class" => "field-label is-normal"]) }}

                            {{ Form::text('contact', null, ["class" => "input", "id" => "contact"]) }}

                {{ Form::label("email", "Email", ["class" => "field-label is-normal"]) }}

                            {{ Form::email('email', null, ["class" => "input", "id" => "email"]) }}

                {{ Form::label("phone", "Phone", ["class" => "field-label is-normal"]) }}

                            {{ Form::text('phone', null, ["class" => "input", "id" => "phone"]) }}

                    {{ Form::button("Save", ["type" => "submit", "class" => "button is-stenton", "id" => "save"]) }}
                    Cancel

        </form>

    <button class="modal-close" onclick="modal('#modal-create', 'close');"></button>

<meta name="_token" content="{{ csrf_token() }}" />
{{ Html::script('js/brands/create_ajax.js') }}

A: The response is always a success because you always send a successful response, even when it has errors included.
You have three choices in what to do:
1) Send the error code manually
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())  {
    //422 is the standard error code laravel uses for validation errors so we're going to keep it
    return \Response::json(array("errors" => $validator->getMessageBag()->toArray()),422);
}

2) Let laravel handle it (recommended)
$this->validate($request,$rules); //Laravel will generate the appropriate error exception response

*$this->validate comes from the trait ValidatesRequests
3) Not recommended: keep the controller code as is and change your AJAX code to:
 $.ajax({

        type: type,
        url: url,
        data: formData,
        dataType: 'json',
        success: function (data) {
            if (data.errors) { /* errors happened */ }
            else { /* no errors happened */ }
        }
 });

Not recommended because handling errors in a success handler is just wrong.


text:
Q: How to sort 2D Points in a 2D-Raster I have a lot of unsorted 2D points which represent the positions of randomized picked pixels of an image.
In the next step I try sort/rasterize them in a 2D array, by point with smallest  x, y value at
array[0][0]

and Point with highest x,y value at
array[n][k]

with condition 1:
all the other 2D should be between this boundaries and almost sorted.
condition 2:
all rows of the array should be filled nearly with same number of values, same for the columns.
Any ideas how to solve this problem?
I computed delaunay-triangulation and thought about a voronoi diagram for going step by step threw each cell, but I don´t know if I am on the right path.
My random positions are created in that way:
std::vector<Point_d> sample_rand_points(){
  std::cout<<"sampling random points\n";
  std::vector<Point_d> output_pattern;

  //PREPARE:
  std::vector<std::pair<int, int> > not_sampled_yet;
  for(int x=0; x<_X; x++)
  {
    for(int y=0; y<_Y; y++)
    {
      not_sampled_yet.push_back(std::pair<int,int>(x,y));
    }
  }
  //SAMPLING
  Point_d pix;
  for (int i=0; i<_Amount; i++)
  {
    //std::cout<<i<<"\n";
    int n= rand()% not_sampled_yet.size();
    pix.x= (double)not_sampled_yet[n].first;
    pix.y= (double)not_sampled_yet[n].second;
    not_sampled_yet[n]=not_sampled_yet.back();
    not_sampled_yet.pop_back();
    output_pattern.push_back(pix);
  }
  return output_pattern;

}

Output is one vector with Points  {{x1,y1},{x2,y2},......}

A: With the following code you can generate an "2d-array" with random pixel.
In my opinion there is no need to use a generator function like sample_rand_points.
#include <iostream>
#include <vector>
#include <cstdlib>

int main()
{
    int NumX =10, NumY =20;
    std::vector<std::vector<bool>> data(NumX, std::vector<bool>(NumY));

    for(int i=0; i<NumX ; ++i)
    {
        for(int m=0; m<NumY ; ++m)
        {
            //Generation
            bool val = false;
            if(rand() % 2 == 0)
                val = true;

            //The Data
            data[i][m] = val;

            //Output
            if(val)
                std::cout << "*";
            else
                std::cout << "_";

        }
        std::cout << std::endl;
    }
}

You can run the above code online to see the following output:
_*____**__*_*__*****
_*__***____***___*_*
____*_**_*_*_**_***_
__*_*_*___*_*_*_**_*
_*****__*_****_****_
_***___*_***_**___*_
*__________*__*_*__*
*_*___***_*_*_*_*___
_***_*_*****_*_____*
*__*__*_*_____**__*_

Note that the line if(rand() % 2 == 0) controls the density of the "selected" pixel.


text:
Q: Need help adding values to list I have a table called confiog.datalist that looks like this:
DBNAME | SCHEMANAME | TABLENAME | order
DatabaseA | staging | customers | 1
DatabaseB | conversion | * | 2
DatabaseC | fact | *truck | 3

Both databases reside on the same server.
DatabaseB has 3 tables in schema conversion: teacher, classroom, student
DatabaseC has 100 tables in schema fact of which two with truck in the name: privatetruck, companytruck
What I want is to create a dataset (Powershell) that contains the following
SELECT * FROM DatabaseA.staging.customer
SELECT * FROM DatabaseB.staging.teacher
SELECT * FROM DatabaseB.staging.classroom
SELECT * FROM DatabaseB.staging.student
SELECT * FROM DatabaseC.fact.privatetruck
SELECT * FROM DatabaseC.fact.companytruck

I will be looping through this dataset to execute these queries.
I do know how to get SELECT * FROM DatabaseA.staging.customer and put that in a dataset.
I do know how to get all the other SELECT statements but I do not know how  to add all these statements to the same dataset ($FinalList)...
Below the code I have so far. The only issue here is that I do not know how to create #FinalList and add records to it... The part about executing the queries once they are in $FinalList is already done.
# Get variables
$dataSource = $args[0]
$database = $args[1]
$destinationfolder = $args[2]

#Create Connection
$auth = "Integrated Security=SSPI;"
$connectionString = "Provider=sqloledb; " + "Data Source=$dataSource; " + "Initial Catalog=$database; " +"$auth; "
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionString

#Read [config].[datalist] and insert in $tblDataList, fill $rowsInDatalist
$sql = "SELECT
        row_number() OVER(ORDER BY [ORDER]) as [Order]
        ,replace(replace([tablename],'[',''),']','') AS TableName_Org
        ,replace(replace([dbname],'[',''),']','') AS DBName
        ,replace(replace([schemaname],'[',''),']','') AS SchemaName
        ,replace(replace([tablename],'[',''),']','') AS TableName
        ,replace(replace(replace([tablename],'[',''),']',''),'*','ALL_'+upper(replace(replace([schemaname],'[',''),']',''))) as [FileName]
        , 'SELECT  * FROM ' + quotename(replace(replace([dbname],'[',''),']',''))+'.'+
        quotename(replace(replace([schemaname],'[',''),']',''))+'.'+
        quotename(replace(replace([tablename],'[',''),']','')) AS SelectQuery
        from [config].[datalist]
        order by [order]"
$command = New-Object System.Data.OleDb.OleDbCommand $sql,$connection
$connection.Open()
$adapter = New-Object System.Data.OleDb.OleDbDataAdapter $command
$tblDataList = New-Object System.Data.DataSet
[void] $adapter.Fill($tblDataList)
$connection.Close()
$rowsInDatalist=($tblDataList.Tables | Select-Object -Expand Rows)

#start looping through the results of the list I got
$i=0
foreach ($row in $rowsInDatalist)
{

# I guess I should create the object here to fill it with results? This object could be called $FinalList

    if(-NOT $row.TableName_Org[$i] -match "\`*") # checking if there is a wildcard in the tablename
    {

     #excute following query and add results to $FinalList:
     $sql = "SELECT 'SELECT  * FROM ' + quotename(replace(replace(s.name,'[',''),']',''))+'.'+quotename(replace(replace(t.name,'[',''),']','')) as SelectFullSchema
            FROM sys.schemas s
            INNER JOIN sys.tables t on s.schema_id = t.schema_id
            WHERE s.name like '%' "+ $row.SchemaName[$i] + "'%' and t.name like '%' "+ $row.TableName[$i] + "'%'"

    }
    else {

            # get $row.SelectQuery[$i] and add results to $FinalList:

    }

#execute all  queries from $FinalList

$i++
}

A: Actually solved in such a way that SQL delivered the list. I am intimately familiar with SQL. That way I did not need to build complexity in Powershell :


text:
Q: Why use ReactJS with ASP.NET CORE MVC? I have worked in ASP.NET CORE MVC, before.

*

*What are all the advantages in using ReactJS over ASP.NET CORE?

*Would not that additional library & its components, slow down the page
load, comparing plain Razor Views?

I tried web search, I am unable to get proper answers.

A: If you have independent apps in PC,Phones tablet,etc,you could just use React and core web api which is front-end and back-end separation.
By using Angular/React with api in server side:
1.You eliminate process of generating HTML in server side and you save CPU.
2.API produces small payload (json) and Razor (html) would be much larger in size, constant full page reloads and postback round trip. so API and SPA save bandwidth.
3.API and SPA could have different versioning, scaling and deployment scenarios.
4.By using API you can support mobile app too and if you start by Razor you may need api in future.
Below are some opinions on using Angular/React or razor:
1.Razor supports mobile,and both are optimized and fast in their own way. Razor optimizes code by not using a tree like MVC does. React is client side so it doesn't really use a tree, but also optimizes data in the HTML to an extent.
2.Angular (or React) is far superior in terms of performance.The model-binding aspects of Angular is a gigantic advantage of server-side rendering. Using Razor(or server side rendering in general) does, however, lend itself to better overall integrity as far as data goes and it makes for a better transition of data from front-end to back-end.
See ASP.NET Core 2.0 Razor vs Angular/React/etc

A:
What are all the advantages in using ReactJS over ASP.NET CORE?

ReactJS is high performance and rapid development client side framework, you can use it throw asp.net core or any other server side framework to handle client side operations.

Would not that additional library & its components, slow down the page
  load, comparing plain Razor Views?

ReactJS designed to be a single page application, and this kind of apps is more faster than multiple page applications, also ReactJS processing the DOM in different and smarter way.
If you want to use ReactJS in asp.net core you must keep in mind that asp.net core is the api part just to return the data (json or xml) or to receive your ajax request to post data.
All clients side parts will handled by ReactJS, no razor views, you can have only one to reference your reacts application or simply you can reference it using plain html page.


text:
Q: How to iterate through a list in python to calculate the distance I have been trying to calculate a distance between two locations from a given latitude and longitude.
The variables are random and coming from a generated semantic annotations.
for coordinates in g.objects(None, predicate=URIRef('http://www.w3.org/ns/prov#generatedAtCoordinates')):
  final_coordinates = coordinates
  data = final_coordinates.split(",")
  latitude = float(data[0])
  longitude = float(data[1])
  calc_distance = (latitude, longitude)
  print(geopy.distance.distance(calc_distance, calc_distance).km)

The printing of the calc_distance is:
(41.40254048829099, 2.095129446086901)
(41.409459057215216, 2.0941780489196367)
(41.40506757803259, 2.0903966716404754)
(41.40081272870648, 2.0936534707551835)
(41.40569962731158, 2.0947062169907373)
(41.40513399283631, 2.09682546591496)

These are randomly generated values, and I want to move forward from this moment. I am using geopy distance calculator.
I think I can't do it, because I am all the time in the same loop, how can I define a global variable, save them in a list, then iterate through that list to calculate the distances in Python?
I am sorry if the question is too basic, or overwhelming but my brain stopped and I can't think.
The original script was:
import geopy.distance

coords_1 = (41.43737599306035, 2.1302325410348084)
coords_2 = (41.42535528994254, 2.1898592767949556)

print(geopy.distance.distance(coords_1, coords_2).km)

Hence, it would start from the first value, then distance between first and second, then second and third, then third and forth etc.

A: A simple way to solve this is to append all the points into a list. Then separate the list however you want, lets say you want the distance of adjacent points. Then iterate over the list to get the distance of every two. So something like this:
distance_list = []
for coordinates in g.objects(None, predicate=URIRef('http://www.w3.org/ns/prov#generatedAtCoordinates')):
  final_coordinates = coordinates
  data = final_coordinates.split(",")
  latitude = float(data[0])
  longitude = float(data[1])
  calc_distance = (latitude, longitude)
  print(geopy.distance.distance(calc_distance, calc_distance).km)
  distance_list + geopy.distance.distance(calc_distance, calc_distance).km

for dis_1, dis_2 in zip(distance_list, distance_list[1:])[::2]
   # Split the list into groups of two
   print(geopy.distance.distance(dis_1, dis_2).km)

Here is an example of how to split a list into pairs.


text:
Q: Is there a complete set of equivalence principles for first-order logic? There is a sound and complete set of equivalence principles for classical propositional logic in the sense that for all propositional logic sentences $\varphi$ and $\psi$: $\varphi$ and $\psi$ are logically equivalent if and only if through the application of these equivalence principles, $\varphi$ and be transformed into $\psi$.
Here is such a set:
Double Negation
$\neg \neg P \Leftrightarrow P$
Commutation
$P \land Q \Leftrightarrow Q \land P$
$P \lor Q \Leftrightarrow Q \lor P$
Association
$P \land (Q \land R) \Leftrightarrow (P \land Q) \land R$
$P \lor (Q \lor R) \Leftrightarrow (P \lor Q) \lor R$
DeMorgan
$\neg(P \land Q) \Leftrightarrow \neg P \lor \neg Q$
$\neg(P \lor Q) \Leftrightarrow \neg P \land \neg Q$
Distribution
$P \land (Q \lor R) \Leftrightarrow (P \land Q) \lor (P \land R)$
$P \lor (Q \land R) \Leftrightarrow (P \lor Q) \land (P \lor R)$
Idempotence
$P \land P \Leftrightarrow P$
$P \lor P \Leftrightarrow P$
Complement
$P \land \neg P \Leftrightarrow \bot$
$P \lor \neg P \Leftrightarrow \top$
Identity
$P \land \top \Leftrightarrow P$
$P \lor \bot \Leftrightarrow P$
To prove that this set is complete, you can show that this set of equivalences allows you to put any propositional logic statement into its 'canonical CNF (or DNF)'
My question is: is there such a (finite!) set for first-order logic?
My thoughts:
First, let's list some basic FOL equivalences:
Quantifier Negation
Where $\varphi$ is any formula and $x$ and any variable:
$\neg \exists x \ \varphi \Leftrightarrow \forall x \ \neg \varphi$
$\neg \forall x \ \varphi \Leftrightarrow \exists x \ \neg \varphi$
Null Quantification
Where $\varphi$ is any formula that does not have $x$ as a free variable:
$\forall x \ \varphi \Leftrightarrow \varphi$
$\exists x \ \varphi \Leftrightarrow \varphi$
Replacing Variables
With $x$ and $y$ any variables, and where the free variables $x$ in $\varphi(x)$ occur on the same place as the free variables $y$ in $\varphi(y)$, and where $\varphi(x)$ and $\varphi(y)$ are otherwise the same:
$\forall x \ \varphi(x) \Leftrightarrow \forall y \ \varphi(y)$
$\exists x \ \varphi(x) \Leftrightarrow \exists y \ \varphi(y)$
Swapping Quantifiers of Same Type
$\forall x \forall y \ \varphi(x,y) \Leftrightarrow \forall y \forall x \ \varphi(x,y)$
$\exists x \exists y \ \varphi(x,y) \Leftrightarrow \exists y \exists x \ \varphi(x,y)$
Quantifier Distribution
$\forall x (\varphi(x) \land \psi(x)) \Leftrightarrow \forall x \ \varphi(x) \land \forall x \ \psi(x)$
$\exists x (\varphi(x) \lor \psi(x)) \Leftrightarrow \exists x \ \varphi(x) \lor \exists x \ \psi(x)$
Prenex Laws
Where $\varphi$ is any formula and where $x$ is not a free variable in $\psi$:
$ \forall x \ \varphi \land \psi \Leftrightarrow \forall x (\varphi \land \psi)$
$  \psi \land \forall x \ \varphi  \Leftrightarrow \forall x (\psi \land \varphi)$
$ \exists x \ \varphi \land \psi \Leftrightarrow \exists x (\varphi \land \psi)$
$  \psi \land \exists x \ \varphi  \Leftrightarrow \exists x (\psi \land \varphi)$
$ \forall x \ \varphi \lor \psi \Leftrightarrow \forall x (\varphi \lor \psi)$
$  \psi \lor \forall x \ \varphi  \Leftrightarrow \forall x (\psi \lor \varphi)$
$ \exists x \ \varphi \lor \psi \Leftrightarrow \exists x (\varphi \lor \psi)$
$  \psi \lor \exists x \ \varphi  \Leftrightarrow \exists x (\psi \lor \varphi)$
Now, using the Prenex Laws, together with Quantifier Negation and Swapping Variables, and all the propositional logic equivalences listed earlier all FOL statements can be put into Prenex Normal Form (is that right?) ... so I was thinking that maybe one could show that all FOL statements can be put into some kind of 'canonical PNF' (and here something like Swapping Quantifiers of Same Type would probably come in handy) ... but what would that look like?
On the other hand, the Distribution of $\forall$ over $\land$, and $\exists$ over $\lor$ feel 'nasty' to me ... I assume I cannot prove them from the others ... which makes me feel that there are probably lots of such other 'nasty interplays' that would require such a principle ... and probably non-recursively many.
Then again, completeness of FOL gives me hope that there is a complete set ... but then the undecidability of FOL makes me fear there is not such a set. I can't really wrap my head around as to which result would be more applicable here.


text:
Q: Fourth level menu option not working I am using a fourth level Active Menu on my app, everything works perfect but when I select one item on the Menu fourth level, the system is not calling onOptionsItemSelected anymore, so I can't get the selected item on my app.
Here is my code
EDIT 1: the dash - in the Id's are making confusion, I am removing them from the code. Sorry for that
public class Main extends FragmentActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
// .... some code
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.Level1: {
       Toast.makeText(getBaseContext(), "Level 1", Toast.LENGTH_SHORT).show();
       break;
    }
    case R.id.Level2: {
       Toast.makeText(getBaseContext(), "Level 2", Toast.LENGTH_SHORT).show();
       break;
    }
    case R.id.Level3: {
       Toast.makeText(getBaseContext(), "Level 3", Toast.LENGTH_SHORT).show();
       break;
    }
    case R.id.Level4: {
       Toast.makeText(getBaseContext(), "Level 4", Toast.LENGTH_SHORT).show();
       break;
    }}
    return true;
}

and here the XML file main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item  android:id="@+id/Level1"
    android:showAsAction="ifRoom"
    android:title="@string/Level1">
    <menu>
    <item android:id="@+id/Level2"
          android:title="@string/Level2">
          <menu>
          <item android:id="@+id/Level3"
              android:title="@string/Level3">
              <menu>
              <item android:id="@+id/Level4"
                  android:title="@string/Level4"/>
              </menu>
          </item>
          </menu>
    </item>
    </menu>
</item>
</menu>

I was reading the documentation but it doesn't states a limit for nested sub-menus.
Finally my solution was to append a android:onClick="onOptionsItemSelected" to the fourth level item like:
              <menu>
              <item android:id="@+id/Level4"
                  android:onClick="onOptionsItemSelected"
                  android:title="@string/Level4"/>
              </menu>

to force the call to onOptionItemSelected, it works but is there a better solution???
EDIT 2: I just found that this walk-around doesn't works with Android version 4.0.3 or earlier.!!! not even using onMenuItemSelected...!!!
Now I am in problem, please help...!!


text: Q: Trainer в transformers на Python Прогнал пять эпох, т.к. датасет маленький, модель обучилась плохо. Снова запустил trainer.train() и после первой эпохи на валидации все съехало. Переопределил датасеты, запускаю обучение, перестали метрики меняться, они тупо одинаковые до последнего знака после запятой. Получается надо сбрасывать ядро и сразу выставлять увеличенное количество эпох?


text:
Q: What are the string property names of MQConstants.USE_MQCSP_AUTHENTICATION_PROPERTY and JMSConstants.USER_AUTHENTICATION_MQCSP? I want to set the MQConstants.USE_MQCSP_AUTHENTICATION_PROPERTY and JMSConstants.USER_AUTHENTICATION_MQCSP in  WAS console > Resources > JMS > Queue connection factories > QueueConnFactoryDEV > Custom properties, does anyone know the property values? Thank you in advance.

*

*In IBM MQ classes for Java, set the property MQConstants.USE_MQCSP_AUTHENTICATION_PROPERTY to true in the properties hashtable passed to the com.ibm.mq.MQQueueManager constructor.

*

*Is the property value USE_MQCSP_AUTHENTICATION_PROPERTY?

*In IBM MQ classes for JMS, set the property JMSConstants.USER_AUTHENTICATION_MQCSP to true, on the appropriate connection factory prior to creating the connection.

*

*Is the property value USER_AUTHENTICATION_MQCSP?

*Globally, set the System Property com.ibm.mq.cfg.jmqi.useMQCSPauthentication to a value indicating true, for example, by adding -Dcom.ibm.mq.cfg.jmqi.useMQCSPauthentication=Y to the command line.

*

*How to set this in websphere?

EDIT:
Instead of
cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);

I want to set
cf.setBooleanProperty("USER_AUTHENTICATION_MQCSP", true);

since I will be putting it in custom properties.

A: These constants appear in the WMQConstants API. Seems to have been a reorg  in later releases.
However, are you sure you're taking the right approach given that you're accessing WMQ within WebSphere Application Server (rather than through a standalone Java program)?
WMQ in particular and JMS providers in general are managed resources within the app server, so along with connection pooling you get a set of server-integrated authentication options like an auth alias.   See here and here and here for more reading on authentication and WMQ in the app server in general.


text:
Q: Python add small matrix inside big one or matrices, and I want to fit the "map" 2d array inside of "cmap", which is +2 bigger, in fact I want to use "cmap" as a frame of "map", but I wanted to do without using one single array (also because I want to randomly generate the characters inside of the "map" 2d array... Did you have any suggestions?
rows, cols = (9, 9)
crows, ccols = (rows + 2, cols + 2)
print(crows, ccols)
cmap = [["#" for x in range(crows)] for y in range(ccols)]
map = [["#" for x in range(rows)] for y in range(cols)]

A: Characters and maps - looks like you may be making a game!
Try:
border = 1
for i in range(border,len(cmap)-border):
  cmap[i][border:-border] = map[i-border]


text:
Q: Discrete maths fundamentals Which is a good book to refresh discrete maths fundamentals for a grad student?
It would be great if the book has short and terse explanations of concepts with lots of worked out examples(/to be worked out exercises) to set the brain rolling.
Can someone suggest a similar refresher for graduate level algorithms?

A: Concrete Mathematics by Knuth is useful as a refresher AFAIK. But this is not a research level question so not really belongs here :).

A: Kleinberg and Tardos is a good book. I followed this book for an Introductory Graduate Discrete Mathematics course. It starts from basics and covers a good amount of material in depth. Kleinberg and Tardos has a lot of Exercises at the end of each chapter.
Algorithms book by S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani is an equally good book and is probably well-written than Kleinberg and Tardos. I have not read this book completely though.

A: I don't think it's a graduate textbook, but I really like the discrete math book by Matousek and Nesetril.  It presents the topics more succinctly than the standard discrete math undergraduate texts and has much more interesting exercises.


text:
Q: Where are Sticky Notes stored (Windows 10)? Up until Windows 8, they are apparently stored in %AppData%\Microsoft\Sticky Notes, but that location does not exist in Windows 10.
From where can I (programmatically) obtain the contents of sticky notes from?

A: Microsoft keeps moving these around and obscuring the content.  That's their right I guess.. :)
Try:
C:\Users\<your user name>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState
You will need a (free) viewer capable of reading a SQLite database file.  Any SQLite viewer should do.
You will need to poke around to figure out the format they are using (I am not going to do that for you) but I assure you that the data you seek is there.  I just poked around my own copy :) .. thanks!  .. I wouldn't have known where they moved this stuff if you hadn't asked.  BTW, I used the SystemInternals Process Monitor to figure out where the data was getting written.


text:
Q: Dataflow setting Controller Service Account I try to set up controller service account for Dataflow. In my dataflow options I have:
options.setGcpCredential(GoogleCredentials.fromStream(
                         new FileInputStream("key.json")).createScoped(someArrays));
options.setServiceAccount("xxx@yyy.iam.gserviceaccount.com");

But I'm getting:
WARNING: Request failed with code 403, performed 0 retries due to IOExceptions,
         performed 0 retries due to unsuccessful status codes, HTTP framework says
         request can be retried, (caller responsible for retrying):
         https://dataflow.googleapis.com/v1b3/projects/MYPROJECT/locations/MYLOCATION/jobs
Exception in thread "main" java.lang.RuntimeException: Failed to create a workflow
         job: (CODE): Current user cannot act as
         service account "xxx@yyy.iam.gserviceaccount.com.
         Causes: (CODE): Current user cannot act as
         service account "xxx@yyy.iam.gserviceaccount.com.
    at org.apache.beam.runners.dataflow.DataflowRunner.run(DataflowRunner.java:791)
    at org.apache.beam.runners.dataflow.DataflowRunner.run(DataflowRunner.java:173)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:311)
    at org.apache.beam.sdk.Pipeline.run(Pipeline.java:297)

...
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "(CODE): Current user cannot act as service account
                 xxx@yyy.iam.gserviceaccount.com. Causes: (CODE): Current user
                 cannot act as service account xxx@yyy.iam.gserviceaccount.com.",
    "reason" : "forbidden"
  } ],
  "message" : "(CODE): Current user cannot act as service account
               xxx@yyy.iam.gserviceaccount.com. Causes: (CODE): Current user
               cannot act as service account xxx@yyy.iam.gserviceaccount.com.",
  "status" : "PERMISSION_DENIED"
}

Am I missing some Roles or permissions?

A: I've been hitting this error and thought it worth sharing my experiences (partly because I suspect I'll encounter this again in the future).
The terraform code to create my dataflow job is:
resource "google_dataflow_job" "wordcount" {
  # https://stackoverflow.com/a/59931467/201657
  name              = "wordcount"
  template_gcs_path = "gs://dataflow-templates/latest/Word_Count"
  temp_gcs_location = "gs://${local.name-prefix}-functions/temp"
  parameters = {
    inputFile = "gs://dataflow-samples/shakespeare/kinglear.txt"
    output = "gs://${local.name-prefix}-functions/wordcount/output"
  }
  service_account_email = "serviceAccount:${data.google_service_account.sa.email}"
}

The error message:

Error: googleapi: Error 400: (c3c0d991927a8658): Current user cannot act as service account serviceAccount:dataflowdemo@redacted.iam.gserviceaccount.com., badRequest

was returned from running terraform apply. Checking out the logs provided a lot more info:
gcloud logging read 'timestamp >= "2020-12-31T13:39:58.733249492Z" AND timestamp <= "2020-12-31T13:45:58.733249492Z"' --format="csv(timestamp,severity,textPayload)" --order=asc

which returned various log records, including this:

Permissions verification for controller service account failed. IAM role roles/dataflow.worker should be granted to controller service account dataflowdemo@redacted.iam.gserviceaccount.com.

so I granted that missing role grant
gcloud projects add-iam-policy-binding $PROJECT \
  --member="serviceAccount:dataflowdemo@${PROJECT}.iam.gserviceaccount.com" \
  --role="roles/dataflow.worker"

and ran terraform apply again. This time I got the same error in the terraform output but there were no errors to be seen in the logs.
I then followed the advice given at https://cloud.google.com/dataflow/docs/concepts/access-control#creating_jobs to also grant the roles/dataflow.admin:
gcloud projects add-iam-policy-binding $PROJECT \
  --member="serviceAccount:dataflowdemo@${PROJECT}.iam.gserviceaccount.com" \
  --role="roles/dataflow.admin"

but there was no discernible difference from the previous attempt.
I then tried turning on terraform debug logging  which provided this info:
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: ---[ REQUEST ]---------------------------------------
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: POST /v1b3/projects/redacted/locations/europe-west1/templates?alt=json&prettyPrint=false HTTP/1.1
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Host: dataflow.googleapis.com
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: User-Agent: google-api-go-client/0.5 Terraform/0.14.2 (+https://www.terraform.io) Terraform-Plugin-SDK/2.1.0 terraform-provider-google/dev
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Content-Length: 385
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Content-Type: application/json
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: X-Goog-Api-Client: gl-go/1.14.5 gdcl/20201023
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Accept-Encoding: gzip
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: {
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:  "environment": {
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:   "serviceAccountEmail": "serviceAccount:dataflowdemo@redacted.iam.gserviceaccount.com",
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:   "tempLocation": "gs://jamiet-demo-functions/temp"
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:  },
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:  "gcsPath": "gs://dataflow-templates/latest/Word_Count",
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:  "jobName": "wordcount",
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:  "parameters": {
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:   "inputFile": "gs://dataflow-samples/shakespeare/kinglear.txt",
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:   "output": "gs://jamiet-demo-functions/wordcount/output"
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:  }
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: }
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:
2020-12-31T16:04:13.129Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: -----------------------------------------------------
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: 2020/12/31 16:04:14 [DEBUG] Google API Response Details:
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: ---[ RESPONSE ]--------------------------------------
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: HTTP/1.1 400 Bad Request
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Connection: close
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Transfer-Encoding: chunked
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Alt-Svc: h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Cache-Control: private
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Content-Type: application/json; charset=UTF-8
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Date: Thu, 31 Dec 2020 16:04:15 GMT
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Server: ESF
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Vary: Origin
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Vary: X-Origin
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: Vary: Referer
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: X-Content-Type-Options: nosniff
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: X-Frame-Options: SAMEORIGIN
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: X-Xss-Protection: 0
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: 1f9
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: {
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:   "error": {
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:     "code": 400,
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:     "message": "(dbacb1c39beb28c9): Current user cannot act as service account serviceAccount:dataflowdemo@redacted.iam.gserviceaccount.com.",
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:     "errors": [
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:       {
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:         "message": "(dbacb1c39beb28c9): Current user cannot act as service account serviceAccount:dataflowdemo@redacted.iam.gserviceaccount.com.",
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:         "domain": "global",
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:         "reason": "badRequest"
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:       }
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:     ],
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:     "status": "INVALID_ARGUMENT"
orm-provider-google_v3.51.0_x5:   }
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: }
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: 0
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5:
2020-12-31T16:04:14.647Z [DEBUG] plugin.terraform-provider-google_v3.51.0_x5: -----------------------------------------------------

The error being returned from dataflow.googleapis.com is clearly evident:

Current user cannot act as service account serviceAccount:dataflowdemo@redacted.iam.gserviceaccount.com

At this stage I am puzzled as to why I can see an error being returned from the Google's dataflow API but there is nothing in the GCP logs indicating that an error occurred.
Then tho I had a bit of a lightbulb moment. Why does that error message mention "service account serviceAccount"? Then it hit me, I'd defined the service account incorrectly. Terraform code should have been:
resource "google_dataflow_job" "wordcount" {
  # https://stackoverflow.com/a/59931467/201657
  name              = "wordcount"
  template_gcs_path = "gs://dataflow-templates/latest/Word_Count"
  temp_gcs_location = "gs://${local.name-prefix}-functions/temp"
  parameters = {
    inputFile = "gs://dataflow-samples/shakespeare/kinglear.txt"
    output = "gs://${local.name-prefix}-functions/wordcount/output"
  }
  service_account_email = data.google_service_account.sa.email
}

I corrected it and it worked straight away. User error!!!
I then set about removing the various permissions that I'd added:
gcloud projects remove-iam-policy-binding $PROJECT \
  --member="serviceAccount:dataflowdemo@${PROJECT}.iam.gserviceaccount.com" \
  --role="roles/dataflow.admin"
gcloud projects remove-iam-policy-binding $PROJECT \
  --member="serviceAccount:dataflowdemo@${PROJECT}.iam.gserviceaccount.com" \
  --role="roles/dataflow.worker"

and terraform apply still worked. However, after removing the grant of role roles/dataflow.worker the job failed with error:

Workflow failed. Causes: Permissions verification for controller service account failed. IAM role roles/dataflow.worker should be granted to controller service account dataflowdemo@redacted.iam.gserviceaccount.com.

so clearly the documentation regarding the appropriate roles to grant (https://cloud.google.com/dataflow/docs/concepts/access-control#creating_jobs) is spot on.
As may be apparent, I started writing this post before I knew what the problem was and I thought it might be useful to document my investigation somewhere. Now that I've finished the investigation and the problem turns out to be one of PEBCAK its probably not so relevant to this thread anymore, and certainly shouldn't be accepted as an answer. Nevertheless, there is probably some useful information in here about how to go about investigating issues with terraform calling Google APIs, and it also reiterates the required role grants, so I'll leave it here in case it ever turns out to be useful.

A: I just hit this problem again so posting my solution up here as I fully expect I'll get bitten by this again at some point.
I was getting error:

Error: googleapi: Error 403: (a00eba23d59c1fa3): Current user cannot act as service account dataflow-controller-sa@myproject.iam.gserviceaccount.com. Causes: (a00eba23d59c15ac): Current user cannot act as service account dataflow-controller-sa@myproject.iam.gserviceaccount.com., forbidden

I was deploying the dataflow job, via terraform, using a different service account, deployer@myproject.iam.gserviceaccount.com
The solution was to grant that service account the roles/iam.serviceAccountUser role:
gcloud projects add-iam-policy-binding myproject \
    --member=serviceAccount:deployer@myproject.iam.gserviceaccount.com \
    --role=roles/iam.serviceAccountUser

For those that prefer custom IAM roles over predefined IAM roles the specific permission that was missing was iam.serviceAccounts.actAs.

A: Maybe someone is going to find it helpful:

*

*For controller it was: Dataflow Worker and Storage Object Admin (that was found in Google's documentation).

*For executor it was: Service Account User.

A: Issue Got Resolved!
Go to GCP -> Console -> IAM -> ServiceAccount Email -> Add Permission -> Service Account User. as below


text:
Q: Left Join without duplicate rows from left table Please look at the following query:
tbl_Contents
Content_Id  Content_Title    Content_Text
10002   New case Study   New case Study
10003   New case Study   New case Study
10004   New case Study   New case Study
10005   New case Study   New case Study
10006   New case Study   New case Study
10007   New case Study   New case Study
10008   New case Study   New case Study
10009   New case Study   New case Study
10010   SEO News Title   SEO News Text
10011   SEO News Title   SEO News Text
10012   Publish Contents SEO News Text

tbl_Media
Media_Id    Media_Title  Content_Id
1000    New case Study   10012
1001    SEO News Title   10010
1002    SEO News Title   10011
1003    Publish Contents 10012

QUERY
SELECT
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC

RESULT
10002   New case Study  2014-03-31 13:39:29.280 NULL
10003   New case Study  2014-03-31 14:23:06.727 NULL
10004   New case Study  2014-03-31 14:25:53.143 NULL
10005   New case Study  2014-03-31 14:26:06.993 NULL
10006   New case Study  2014-03-31 14:30:18.153 NULL
10007   New case Study  2014-03-31 14:30:42.513 NULL
10008   New case Study  2014-03-31 14:31:56.830 NULL
10009   New case Study  2014-03-31 14:35:18.040 NULL
10010   SEO News Title  2014-03-31 15:22:15.983 1001
10011   SEO News Title  2014-03-31 15:22:30.333 1002
10012   Publish         2014-03-31 15:25:11.753 1000
10012   Publish         2014-03-31 15:25:11.753 1003

10012 are coming twice...!
My query is returning duplicate rows from tbl_Contents (left table in the join)
Some rows in tbl_Contents has more than 1 associated rows in tbl_Media.
I need all rows from tbl_Contents even if there are Null values exists in the tbl_Media BUT NO DUPLICATE RECORDS.

A: Try an OUTER APPLY
SELECT
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
    ) m
ORDER BY
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results
SELECT
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.
The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

A: You can do this using generic SQL with group by:
SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:
SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases.  Could be top.  Or rownum = 1.  Or fetch first 1 rows.  Or something like that.

A: Using the DISTINCT flag will remove duplicate rows.
SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC

A: The table tbl_media has the content_id 10012 appearing two times, so when tbl_content joins with tbl_media, it will capture 10012 twice, creating one row with media_id = 1003 and another one with media_id = 1000 (so if you consider both content_id and media_id, the information is actually not duplicated).
The question becomes, what is the correct media to prioritize for content 10012 (1000 or 1003)? Once you determine this relationship, you can adjust the IDs tbl_media and join the tables without creating duplicates on media_id level.


text:
Q: Django: Calling ModelForm via instance method - seperate fields Is it possible to output a ModelForm using a class method; for example:
def edit_form(self, *args, **kwargs):
    from smf.node.forms import MediaBaseForm
    return MediaBaseForm(instance=self)

(MediaBaseForm is a ModelForm subclass for model Media), and then in the view:
form = node.edit_form()
(node contains the instance)

This code executes without raising errors; however, when viewing the page, no form fields are generated when I try to render each field separatly. The form does display when I use {{ formset }} but not using {% for form in formset.forms %}} ..etc. {% endfor %}  -->
I need this:
{{ formset.management_form }}
    {% for form in formset.forms %}

        {{ form.id }}

Title: {{ form.title }}

Description:
 {{ form.description }}

Comment settings:
 {{ form.comment }}

Promoted to frontpage:
 {{ form.promote }}

Sticky:
 {{ form.sticky }}

Ready for Publishing:
 {{ form.status }}
    {% endfor %}

instead of this:
{{ formset }}

Is it not possible to call a form this way or am i doing something wrong?
Complete view:
def node_edit(request, nid):
        #Build the standard node form
        node = node_load(nid)
        obj = node_get_model(node.type, True)
        #modelFormset = modelformset_factory(obj, max_num=1)
        form = node.edit_form()

    if request.method == 'POST': # If the form has been submitted...
        #form = modelFormset(request.POST, request.FILES)
        form = node.edit_form()
        if form.is_valid():
            instances = form.save(commit=False)
            for instance in instances:
                instance.save()
            node_post_process(node, request, obj)

            if 'save_edit' in request.POST:
                id = int(nid)
                return HttpResponseRedirect('/edit/%i' %(id))
            if 'save' in request.POST:
                #id = node_callback_value.Node_ptr
                id = int(nid)
                return HttpResponseRedirect('/content/%i' %(id))
            if 'savenew' in request.POST:
                return HttpResponseRedirect('/content/add/%s' %(node.type))
    else:
        output = {}
        #form = modelFormset(queryset=obj.objects.filter(node_ptr=nid))
        form = node.edit_form(instance=node)
    output = {
    'formset': form,
    'node': node,
    }
    try:
        return render_to_response('node/forms/%s.edit.html' %(node.type), output)
    except TemplateDoesNotExist:
        return render_to_response('node/forms/default.form.html', {
            'formset': form,
        })

A: I can't understand what you're trying to do. There are a number of problems with your approach, though.
Firstly, there's no way of passing the POSTed values to the form instantiation. As a result, form.is_valid() will always be False.
Secondly, the result of node.edit_form() appears to be a single form, not a formset. So I don't know why you are passing it to the template context as formset and trying to iterate through formset.forms.


text:
Q: Dreamweaver mismatching/broken code at http links I have a strange issue with dreamweaver, editing HTML/PHP code.
When I save a .php or .html file and then re-open it in dreamweaver, it is showing broken href links, sometimes with missing closing " therefore breaking the code from that point on.
Here is an example:
This is the code when I save the file:

            Route:
GOOGLE MAPS

BUT, when I reopen the same file, dreamweaver will show me this:

            Route:
GOOGLE MAPS

so this bit is missing here: target="
Another one on the same page:
Saved this:
GOOGLE MAPS

When close and re-open the file, shows this:
GOOGLE MAPS

If I open the file in another app like Notepad++, it's fine there.
Have had this issue with other type of links too, e.g. facebook pixel etc.
Any ideas?


text:
Q: finding missing digits using divisibility rules find the missing digits of 33^15=$x9938945498y6542054345z$
My Attempt:I have found that $z=7$ because its like the first digit of $3^3$. But I cannot find $x$ and $y$. Which divisibility rules should I use?

A: The result is divisible by both $9$ and $11$. Since $x$ and $y$ are digits of different parity, this allows you to determine them:
\begin{align}
x+y+113&\equiv0\mod9\;,\\
x-y+58-55&\equiv0\mod11\;,
\end{align}
where $113$ is the sum of the remaining digits, $58$ is the sum of the remaining digits that have the same parity as $x$ and $55$ is the sum of the remaining digits that have the same parity as $y$. So
\begin{align}
x+y&\equiv4\mod9\;,\\
x-y&\equiv8\mod11\;.
\end{align}
Since $x$ and $y$ are decimal digits, this leaves the options $x+y=4$ or $x+y=13$ and $x-y=-3$ or $x-y=8$. Since $x+y$ and $x-y$ have the same parity, we must have either $x+y=4$ and $x-y=8$ or $x+y=13$ and $x-y=-3$. The first option doesn't yield decimal digits, so the second option is the only solution, yielding $x=5$ and $y=8$.

A: Divisibility by 9 will give you information about $x + y + z$.  So will the divisibility by $11$ test. Can you use those?

A: 1) Divisibility by eleven means the sum of the even digits minus the sum of the odd digits is a multiple of eleven.
So x9938945498y6542054345z divisible by 11 means
x + 9 +8 +4 + 4 + 8 + 6 + 4 + 0 + 4 + z = 9 + 3 + 9 + 5 + 9 + y + 5 + 2 + 5 + 3 + 5 + 11k
So
x + z = y + 55 - 47  + 11k
x + z = y + 8 or x + z = y - 3
2) Divisibility by 9 means the sum of the digits is a multiple of 9
So x + 9 +8 +4 + 4 + 8 + 6 + 4 + 0 + 4 + z + 9 + 3 + 9 + 5 + 9 + y + 5 + 2 + 5 + 3 + 5 = x + y + z  + 102 = x + y + z + 9x11 + 3
So x +  y + z is 6 more than a multiple of 9.
So x + y + z =6 or x + y + z = 15 or x + y + z = 24
3) $33^{15} \equiv  7 \mod 10$.  (You figurde that out.)
So z = 7
Put those 3 together and you've got it.

A: Recall some Stupid Divisibility Tricks,

The OP has left the following problem to be solved,
$\tag 1  10^{22} x +  10^{11} y + 9,938,945,498,065,420,543,457 = 33^{15}$
Applying the $\text{mod}(13)$ operator while using the 'trick', we calculate
$\quad 10^{22}  \text{ (3 block alt sum)} = -10  \equiv 3 \pmod{13}$
$\quad 10^{11}   \text{ (3 block alt sum)} = -100 \equiv 4 \pmod{13}$
$\quad 9,938,945,498,065,420,543,457 \equiv$
$\quad \quad \; -9+938-945+498-065+420-543+457  \text{ (3 block alt sum)} = 751 \equiv$
$\quad \quad \; 10 \pmod{13}$
To calculate $33^{15} \pmod{13}$ we'll use Fermat's little theorem,
$\quad 33^{15}  \equiv 2^{15} 10^{15} \equiv 2^{3} 10^{3} \equiv 5 \pmod{13}$
Putting all this together we get
$\tag 2 3x + 4y \equiv 8 \pmod{13}$
The fun part now is that we can reuse some of the above work while applying the $\text{mod}(7)$ operator,
$\quad 10^{22}  \text{ (3 block alt sum)} = -10  \equiv 4 \pmod{7}$
$\quad 10^{11}   \text{ (3 block alt sum)} = -100 \equiv 5 \pmod{7}$
$\quad 9,938,945,498,065,420,543,457 \equiv$
$\quad \quad \; -9+938-945+498-065+420-543+457  \text{ (3 block alt sum)} = 751 \equiv$
$\quad \quad \;  2 \pmod{7}$
To calculate $33^{15} \pmod{7}$ we'll use Fermat's little theorem,
$\quad 33^{15}  \equiv (-2)^{15} \equiv (-2)^{3}  \equiv 6 \pmod{7}$
Putting all this together we get
$\tag 3 4x + 5y \equiv 4 \pmod{7}$
Working with the two equations...
The digit pair $(x,y)$ solution set $A$  for $\text{(2)}$ is given by
$\quad A = \{(0,2),(2,7),(3,3),(5,8),(6,4),(7,0),(8,9),(9,5)\}$
The digit pair $(x,y)$ solution set $B$  for $\text{(3)}$ is given by
$\quad B = \{\color{red}{(0,5)}, (7,5), \color{red}{(1,0)}, (8,0), (1,7), (8,7), \color{red}{(2,2)}, (9,2), (2,9), (9,9),$
$\quad \quad \quad \; \,\color{red}{(3,4)},\color{red}{(4,6)},\color{red}{(5,1)}, (5,8), \color{red}{(6,3)}\}$
Since $A \cap B = \{(5,8)\}$, we've found the answer to OP's question using divisibility rules.


text:
Q: Eclipse+Pydev (1) Ctrl+F3 jumps to site-packages; (2) "setup.py install" affects imports I have two questions about python development with Eclipse+Pydev on a project that already has been set up to use "python setup.py install". It's a decent-size project (100+ python modules, 10+ packages).
Question 1: If I have multiple entry functions (i.e. different starting files to run my code) is it possible to have Eclipse+PyDev automatically run "python setup.py install" before executing any file in my project? Or is the best way just to have a line in the beginning of every starting file to run "python setup.py install"? I originally wanted to just do all of the development within Eclipse w/o having to do "python setup.py install" at all, but that requires changing the way the import statements are done across the project (see below more details about this).
Question 2: Suppose my project is named "X", whenever I press Ctrl+F3 to jump to a file containing a function definition, if that file is not already open in an editor, then Eclipse will open the "C:/Python27/Lib/site-packages/X/some-package/some-module.py" instead of the file ../UserMe/X/some-package/some-module.py. Is it possible to make it so that Eclipse knows to only access the local files and not the ones made from "python setup.py install" that are in the site-packages folder?
More Details:
Right now everything is "working" (i.e. compiling and running):
Currently, in order to run my project I do the following:
cd <top-level-dir>
python27 setup.py install
# then run my script
python27 startup/script1.py

Different kinds of imports
It seems that in Eclipse+PyDev there are two different ways of doing imports for my project. My project name is "X". If I'm not using "python setup.py install", and just running everything from within Eclipse, Eclipse seems to want my imports like the following
import package.module1
import package.module2
... etc

However, since I'm using "python setup.py install" I need to have my imports like the following:
from X.package import module1, module2

But when I do this, Eclipse+Pydev code analysis complains that my imports are broken unless I do "python setup.py install" before each run. So I end up just running "python setup.py install" and then my startup script in a terminal outside of Eclipse.
Other Details

*

*Using python2.7

Thank you! I appreciate any tips relating to this. I consider myself new to big project development using python.

A: I think you have gotten ahead of things with python setup.py install, what you want is python setup.py develop so that your code that you are developing is not installed, but instead special links are set-up.
See Python setup.py develop vs install and its answers too.


text:
Q: How to retry input after an InputMismatchException? I am creating a program that takes input from the user.Now I want to re-run the input option if a user enters an invalid command. Like here only integer input are preferred but if the user inputs text, then I want to catch the exception and rerun the method.
I have tried this but it turns me into an infinite loop.What would be the best way to achieve this. It would be great if someone helps me on this.
    boolean retry = true;

    while(retry){

        try{
            //considering response from the user
            System.out.print("\nEnter Your Command : ");
             f_continue =  processresponse(scanner.nextInt());
             retry = false;
        }catch(InputMismatchException e){

            System.err.println("\nPlease Input a Valid Command from 1-5 or 0 for Exit");

        }

    }

A: If you enter something other than an integer, nextInt() will throw an exception, and what was entered will still be in the input buffer, so the next time you call nextInt(), you will read the same bad input. You should first call hasNextInt() to see if the input is an integer; if not, just call nextLine() to skip the bad input (and write a message telling the user to re-try).
Or you can just call scanner.nextLine() in the catch block.


text:
Q: Python Pandas: Json to Excel just one row exports issue I have a issue with Python Pandas. My code is showing first element but not showing another. How can I solve this issue? I shared a screenshot. My code added just Admin parent, HAKAN MISIRLI child.
My Json:

{
  "ADMİN" : {
    "HAKAN MISIRLI" : [ 33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  },
  "AKPINAR GES" : {
    "BAHRİ KAŞARCI" : [ 44444444444, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  },
  "Gölbaşı Ges" : {
    "MOLLA AHMET ŞAHİN " : [ 555555555555, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  }
}

My code:

url = "the url of my Json file "

    with urllib.request.urlopen(url + ".json") as url:
        data = json.loads(url.read().decode())
        role = list(data.keys())[0]
        name = list(data[role].keys())[0]
        listson = data[role][name]
        columns = ["Saha", "İsim", "TC Kimlik"] + list(range(1, len(listson)))
        rows = ["Personel"]
        dfson1 = pd.DataFrame([role, name] + listson).T
        dfson1.columns = columns
        dfson1.index = rows

    dfson1.to_excel("export.xlsx")

Export from this code:
screenshot from my code export

A: Doesn't look like you looped over the json as it's not in a list. Here's an alternative to consider. You can go line by line to see what the code is doing.
Try:
data = '''{
  "ADMİN" : {
    "HAKAN MISIRLI" : [ 33333333333, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  },
  "AKPINAR GES" : {
    "BAHRİ KAŞARCI" : [ 44444444444, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  },
  "Gölbaşı Ges" : {
    "MOLLA AHMET ŞAHİN " : [ 555555555555, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
  }
}'''

dataj = json.loads(data)
df = pd.concat([pd.json_normalize(j) for j in [dataj]])
df1 = df.T.reset_index()
df1[["Saha", "İsim"]] = df1['index'].str.split('.', expand=True)
dft = pd.DataFrame(df1[0].tolist())
df_final = pd.concat([df1[["Saha", "İsim"]], dft], axis=1)
df_final.rename(columns={0:'TC Kimlik'}, inplace=True)

Ouput
          Saha                İsim     TC Kimlik  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31
0        ADMİN       HAKAN MISIRLI   33333333333  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
1  AKPINAR GES       BAHRİ KAŞARCI   44444444444  0  0  0  0  0  0  0  0  0   0   0   0   1   0   0   1   1   1   0   0   0   0   0   0   0   0   0   0   0   0   0
2  Gölbaşı Ges  MOLLA AHMET ŞAHİN   555555555555  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0


text:
Q: Rubymine does not autocomplete paths where the resource is plural Let's say I have the following routes:
resources :users do
  collection do
    get :welcome
    get :search
  end
  member do
    post: invite
    post :block
  end
end

Then if I type invite_u, rubymine suggests: invite_user_path. Good.
But if I type: welcome_u, rubymine suggests: welcome_user_path. Not good. It should be welcome_users_path. Why rubymine gets it wrong ?

A: From the JetBrains Bug Tracker:
wrong name resolved from routes.rb by inspector and code hint in view
This bug was for version 4.5.2 and marked as resolved. What version are you on? If you are on a newer version I would file a new bug report with them. Or update to the latest version if you are not on it already.


text:
Q: "MiKTeX Configuration Utility did not succeed" when trying to extend compiler limits I'm trying to add several plots to a report using pgfplots and I got an error about "TeX capacity exceeded". I saw this solution, but when I tried to enact it, I got a different error related to missing MiKTeX updates. I'd opened up a question here earlier on the subject, but I screwed something up in the mean time and, long story short, ended up having to reinstall MiKTeX altogether.
When I try to update the LaTeX format files, as it says in the previous link, I get the error in my question and a message saying "The log file hopefully contains the information to get MiKTeX going again". The aforementioned log file contains the following:
2019-11-24 17:56:07,950Z INFO  initexmf - starting: MiKTeX Configuration Utility 2.9.7251 (MiKTeX 2.9.7250 64-bit)
2019-11-24 17:56:07,951Z INFO  initexmf - Operating on the private (per-user) MiKTeX setup
2019-11-24 17:56:07,951Z INFO  initexmf - starting with command line: initexmf --edit-config-file=pdflatex
2019-11-24 17:56:07,991Z INFO  initexmf - finishing with exit code 0
2019-11-24 17:56:28,937Z INFO  initexmf - starting: MiKTeX Configuration Utility 2.9.7251 (MiKTeX 2.9.7250 64-bit)
2019-11-24 17:56:28,937Z INFO  initexmf - Operating on the private (per-user) MiKTeX setup
2019-11-24 17:56:28,938Z INFO  initexmf - starting with command line: initexmf --dump=pdflatex
2019-11-24 17:56:28,943Z INFO  initexmf - running: miktex-makefmt.exe --engine=pdftex --dest-name=pdflatex --no-dump pdflatex.ini --engine-option=-tcx=cp227.tcx --enable-installer --miktex-disable-maintenance
2019-11-24 17:56:29,321Z ERROR initexmf - sub-process error output has been saved to 'C:\Users\XXXXX XXXXX\AppData\Local\MiKTeX\2.9\miktex\log\miktex-makefmt_2019-11-24-175629.out'
2019-11-24 17:56:29,321Z FATAL initexmf - The executed process did not succeed.
2019-11-24 17:56:29,321Z FATAL initexmf - Info: fileName="D:\Programas\MiKTeX\miktex\bin\x64\miktex-makefmt.exe", exitCode="1"
2019-11-24 17:56:29,321Z FATAL initexmf - Source:
2019-11-24 17:56:29,321Z FATAL initexmf - Line: 0

I changed my name to "XXXXX XXXXX" for privacy and because it does contain a space. It also contains an accented character, in case that's relevant.
Can anyone shed some light on why this is happening?


text:
Q: Parsing code with caseless keyword with Tatsu / grako I try to parse Fortran code with keyword which are caseless with Tatsu h!
Is there a smarter way to define the keyword caseless than these :
@@ keyword :: integer INTEGER etc...

Thanks

A: You may use the @@ignorecase directive, as explained here


text:
Q: Limiting decimal places of coordinate values in GEOJSON file using QGIS? Using "QGIS 2.0.1-Dufour", I try to convert a vector layer into GEOJSON file using "Save As" sub menu. I get the GEOJSON  file, but the coordinates of points have values up to 15 decimal places.
How can I round off the values at the desired number of decimal places?

A: I don't know if it is possible to limit the number of the coordinates' values when you save a  vector layer as a GeoJSON file, using QGIS, but I'll show you an alternative way using a simple (but powerful) text editor: Notepad++.
Of course, you can use any similar software you like, only assure yourself it can perform search an replace using regular expressions.
Assuming you have already the GeoJSON file, just open it using Notepad++:

Then go to Search > Replace and use these expressions:
in the Find what field:
([0-9]+\.[0-9]{2})([0-9]+)

and in the Replace with field:
\1

(Remember that Regular expression must be checked)
This is the result after pressing Replace all:

If you want a different number of decimals just replace {2} with the new desired value:

A: It's very easy to limit the coordinates when exporting GeoJson, as QGIS just uses the ogr2ogr program for the export, and it allows you to pass in additional parameters when you save the file. Here's a pic:

That will ensure only 2 decimal places in the coordinates.


text:
Q: How to get class constant via .GetType() I will try to explain.
I have 3 classes : EnemyTeleport, EnemyZigZag, EnemyNormal. They all inherit base class Enemy.
Each of these 3 classes has his own const -> KillPoints.
So in other class. For example Form Class, I need to get these constants.
These EnemyTeleport, EnemyZigZag, EnemyNormal are located in public Enemy EnemyInstance;
For example
EnemyInstance = new EnemyTeleport();

So how can I get Kill Points from EnemInstance? I don't want to to check each possible variant?
Is there smarter way?
Like EnemInstance.GetType().KillPoints (doesn't work)
Again. EnemyInstance is Enemy type which holds EnemyTeleport. Constant keeps in EnemyTeleport

A: Why don't you expand your base-class Enemy with a property for the KillPoints. In the constructor of a inherited class you can set the KillPoints to the specific value of the certain enemy
But if you don't want to put it into a base-class:
Make the KillPoints as a property in the certain Enemy like:
public class TeleportEnemy : Enemy
{
   public int KillPoints{get;private set;}
   public TeleportEnemy()
   {
      this.KillPoints = 666;
   }
}

The code to access the Killpoints by an instance of Enemy looks like:
Enemy enemy = new TeleportEnemy();
        PropertyInfo propertyInfo = enemy.GetType().GetProperty("KillPoints");
        int value = (int)propertyInfo.GetValue(enemy, null);

A: I suggest you to use
public abstract class Enemy
{
   public abstract List<int> KillPoints;
}

For each specific class define the value of KillPoints (You can use TemplateMethod pattern to calculate your KillPoints)
link : http://www.dofactory.com/Patterns/PatternTemplate.aspx
But in your Main you use base class Enemy for your services
So :
Enemy enemy = new EnemyTeleport();
var result = enemy.KillPoints;

A: Your hierarchy could be defined as follows. Note how Enemy class is abstract, while concrete enemies implement property KillPoints. Your main implementation has to know only about abstract class Enemy, while concrete implementation should be created elsewhere, depending on some flag in your game.
public abstract class Enemy
{
    public abstract int KillPoints {get;}
}

public class EnemyTeleport : Enemy
{
    public override int KillPoints
    {
        get{return 6;}
    }
}

public class EnemyZigZag : Enemy
{
    public override int KillPoints
    {
        get{return 10;}
    }
}

Now you can take advantage of polymorphic call to  KillPoints
private Enemy EnemyInstance;

void Main()
{
    EnemyInstance = new EnemyTeleport();

    Console.WriteLine(EnemyInstance.KillPoints);
}


text:
Q: Macro (VBA) crashing Microsoft word (Find and replace) I using a VBA code to batch find and replace highlighted text. The macro finds and replaces the words in the document. It works well with a few number of highlighted text on a small document (1-2 pages). However, when I use this macro on a large documents which has over a 100 pages, Microsoft word crashed and becomes unresponsive so I have to forced to quit.
The code is to help make it easy to redact information. I am replacing the highlight text which occur also in tables with XXXXX and highlighted black.
Does anyone have any tips to make the code more efficient?
Here is the code
Sub FindandReplaceHighlight()
  Dim strFindColor As String
  Dim strReplaceColor As String
  Dim strText As String
  Dim objDoc As Document
  Dim objRange As Range

  Application.ScreenUpdating = False

  Set objDoc = ActiveDocument

  strFindColor = InputBox("Specify a color (enter the value):", "Specify Highlight Color")
  strReplaceColor = InputBox("Specify a new color (enter the value):", "New Highlight Color")
  strText = InputBox("Specify a new text (enter the value):", "New Text")

  With Selection
    .HomeKey Unit:=wdStory
    With Selection.Find
      .Highlight = True

      Do While .Execute
        If Selection.Range.HighlightColorIndex = strFindColor Then
          Set objRange = Selection.Range
          objRange.HighlightColorIndex = strReplaceColor
          objRange.Text = strText
          objRange.Font.ColorIndex = wdBlack
          Selection.Collapse wdCollapseEnd
        End If
      Loop
    End With
  End With

  Application.ScreenUpdating = True
End Sub

A: Try:
Sub FindandReplaceHighlight()
Application.ScreenUpdating = False
Dim ClrFnd As Long, ClrRep As Long, strTxt As String
Const StrColors As String = vbCr & _
"  1 Black" & vbCr & _
"  2  Blue" & vbCr & _
"  3  Turquoise" & vbCr & _
"  4  Bright Green" & vbCr & _
"  5  Pink" & vbCr & _
"  6  Red" & vbCr & _
"  7  Yellow" & vbCr & _
"  8  White" & vbCr & _
"  9  Dark Blue" & vbCr & _
"10 Teal" & vbCr & _
"11 Green" & vbCr & _
"12 Violet" & vbCr & _
"13 Dark Red" & vbCr & _
"14 Dark Yellow" & vbCr & _
"15 Gray 50" & vbCr & _
"16 Gray 25%"

ClrFnd = InputBox("Specify the old color (enter the value):" & StrColors, "Specify Highlight Color")
ClrRep = InputBox("Specify the new color (enter the value):" & StrColors, "New Highlight Color")
strTxt = InputBox("Specify the new text (enter the value):", "New Text")

With ActiveDocument
  With .Range
    With .Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Highlight = True
      .Forward = True
      .Wrap = wdFindStop
    End With
    Do While .Find.Execute
      If .HighlightColorIndex = ClrFnd Then
        .HighlightColorIndex = ClrRep
        .Text = strTxt
        .Font.ColorIndex = wdBlack
        .Collapse wdCollapseEnd
      End If
    Loop
  End With
End With
Application.ScreenUpdating = True
End Sub


text:
Q: How many 5-bead necklaces can be made with beads of 21 colours? How many 5-bead necklaces can be made with beads of 21 colors?
I get the answer using Polya's Enumeration Theorem as 413 049. Can someone confirm?
Does it include cases other than all five beads being distinct?
Many thanks.

A: The answer has been found correct by comparing with
http://oeis.org/A060446/list


text:
Q: Wireless Access Point with login/landing page I´m investigating how to setup a Wireless Access Point in a Linux (Ubuntu, in my case) PC where is mandatory to login/register using a backend module that I have developed.
I know that exist some software solutions like Chilli or Easyhotspot that may satisfy the requirements for most people, but I want to implement a custom solution. The workflow should be as follows:
When the user tries to connect to Internet via my Wireless Access Point a custom landing page always appears. In other words, the Wireless Access Point must redirect always to a (for example) index.html page.
The page contains a login/registration form that points to some backend endpoints.
The backend endpoints that enable login and registration are my own and are deployed in a Web server.
If the login/registration operation is success then the user get Internet access.
I´ve read ton of blog posts, forum threads, etc. but I found nothing. What I want to do looks simple, but I don´t know how to develop something like that. I don´t mind if I have to develop that solution in Python, C, Bash scripting... Any tutorial, tips, suggestions would be very appreciated.
Thank you very much in advance for your help!
Best regards,
Luis Cappa.


text:
Q: Git reflog expiration time I have known that reflog entries gets deleted which are older than 90 days. I have not made any change in git config too regarding this.
Today when I did git reflog master --date=local, I can see entries of 10 months before in it. How is that possible ?I should only be seeing entries dating back to 3 months before only ?

A: Git will automatically run git gc periodically, provided you don't disable it.  But the period for this automatic GC is not defined anywhere, and in fact, it's not based on time at all.  Instead, it's based on a quick survey that git gc --auto makes of the state of the repository.  Moreover, it's actually kicked off by running some other Git command, which simply runs git gc --auto at the end of its work.  That git gc --auto then decides whether to run git gc, and if so, that git gc runs git reflog expire with the 90 day expiration.
In this case, perhaps either you have not run a Git command that ran git gc --auto, or git gc --auto chose not to do anything, for 10 months.  That seems a bit excessive,1 so it's more likely you disabled automatic GC by setting gc.auto to 0.  It's also possible you have hit an interesting bug: see this answer by VonC to one of the "see also" questions below, which has a fix for a bug that did bite people.
See also List of all commands that cause git gc --auto, Understanding git gc --auto, and How often should you use git-gc?

1How excessive this is depends on how active the repository is.  A fairly quiet repo might not accumulate enough loose objects to make git gc --auto do anything for many months; a busy one will need automatic gc pretty frequently.

A:
How is that possible?

Pretty simple explanation - that is possible if you don't run git reflog expire or git gc regularly. If you did that and they are still there, please amend your question. Else, that's it.
Type git gc and see them disappear.


text:
Q: angular - Attempting to post authorization header but getting 404 whereas same post works in Postman I am relatively new to Angular, but not to development.
I understand how the http post is supposed to work. My own function is based on the Hero Service tutorial post example.
The problem is that this post works perfectly fine in Postman. I receive an authorization token as expected. However, when I run the angular app and see my console, I receive a 404 not found which is exactly what I receive if I do GET to the same URL in Postman.
{
    "statusCode": 404,
    "error": "Not Found"
}

Below is my service and some screenshots that may be helpful.
Any ideas?
Need additional information I can provide?
Thanks in advance.
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class TheService {
  private baseUrl = 'https://someserver.com';
  private authUrl = this.baseUrl + '/auth';

  constructor(private http: Http) { }

  getAuth(apiKey: string): Promise<string> {
    let headers = new Headers();
    headers.append('Authorization', 'Basic ' + apiKey);

    console.log('headers: ' + headers.get('Authorization'));

    return this.http
      .post(this.authUrl, '', {headers: headers})
      .toPromise()
      .then(function(response) {
        console.log('response:' + response.toString());
        return response.toString();
      })
      .catch(this.handleError);
  }

    private handleError(error: any): Promise<any> {
      console.error('An error occurred', error);
      return Promise.reject(error.message || error);
    }

}