text:
Q: I coudn't get slide show images on my html page I tried to create a small website for that I've added below code in my html for getting slide show images.
I get only slides but images doesn't display, I couldn't understand what causes the problem.
so, please can anyone give me a solution for this problem.
should I make any changes in below code.
is java script needed for this code ?

 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>home</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">

            <input type="radio" name="r" id="r1" checked>
            <input type="radio" name="r" id="r2">
            <input type="radio" name="r" id="r3">
            <input type="radio" name="r" id="r4">
            <input type="radio" name="r" id="r5">


text:
Q: how to fix this IE6 input bug var check = function(){
   return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
submit.onclick = check;
_submitSpan.appendChild(submit);

i created a form and append a input button, but i found it can't work in IE6, when click the button, the form auto submitted. can anybody help me.thank you.

A: It might be an idea to hook into a 3rd party lib to handle event inconsistencies et al, YUI does a fine job, as does jquery.

A: Instead of explicitly setting the onclick attribute, try binding dynamically to the nodes' onclick event instead. Or perhaps you should be looking at the onsubmit event of the form.
function bindEvent(target, event, handler) {
    if (typeof target.addEventListener != 'undefined') {
        target.addEventListener(event, handler, false);
    } else if (typeof target.attachEvent != 'undefined') {
        target.attachEvent('on' + event, handler);
    }
}

function check(e) {
   // Cancel W3 DOM events
   if (typeof e.preventDefault != 'undefined') {
        e.preventDefault();
   }
   // Cancel for old IE event model
   e.returnValue = false;

   return false;
}

var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";

_submitSpan.appendChild(submit);

// Bind click event to submit button...
bindEvent(submit, 'click', check);

// ...or perhaps you want to bind submit event to form
bindEvent(submit.form, 'submit', check);

A: For IE you might have to use the addAttribute method instead of .onclick()
submit.addAttribute('onclick', check);

A: From W3C HTML 4.01 Specs:
image

Creates a graphical submit button. The value of the src attribute specifies the URI of the >image that will decorate the button. For accessibility reasons, authors should provide >alternate text for the image via the alt attribute.

Do not use an <input type="image"> like a checkbox. The best way to make an image-checkbox is something like:
<label for="input">
<input id="input" style="display:none;" type="checkbox">
<img src="img.gif" alt="Check">
</label>

The label will treat the image as a checkbox, and automatically check the hidden checkbox if the image is clicked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A reduction-step on a proof of Kronecker-Weber theorem I am trying to follow a proof of the Kronecker-Weber theorem (if $K$ is a number field with abelian Galois group then it is contained in a cyclotomic field) but I cannot understand one step.
I could understand that one can only consider the case where $K$ is an abelian extension of prime power degree (say $p^n$) such that $p$ is the only ramified prime. Specifically, one proves the following:

Every abelian extension of $\mathbb{Q}$ is the compositum of abelian extensions of prime power degree.

Let $G=\text{Gal}\left (K/\mathbb{Q}\right )$. Since $G$ is abelian, it is the direct sum of its Sylow subgroups. If $\left |G\right |=p_1^{n_1}\cdots p_r^{n_r}$ is the prime decomposition of the order of $G$, then we take $G_i$ to be the direct sum of all $p_j$-Sylow subgroups of $G$ with $j\neq i$. The fixed field $K_{G_i}$ has degree $p_i^{n_i}$ for each $i$, therefore $K$ is the composite of all $K_{G_i}$ because that composite has degree $p_1^{n_1}\cdots p_r^{n_r}$ (this is because the degrees are pairwise coprime). $\blacksquare$
Therefore the theorem is reduced to the case where $K$ is an abelian extension of prime power degree. Now, one can prove the following:

Let $K$ be an abelian extension of $\mathbb{Q}$ with $\left [K:\mathbb{Q}\right ]=p^m$. Suppose $q$ is a prime $\neq p$ which is ramified in $K$.
Fix $Q$ a prime of $K$ lying over $q$. Then the ramification index $e=e(Q|q)$ divides $q-1$. Let $L$ be the unique subgroup of $\mathbb{Q}(\xi)$ of degree $e$, where $\xi=e^{\frac{2\pi i}{q}}$.
Let $U$ be a prime of $KL$ lying over $Q$ and $K'$ denote the inertia field $\left (KL\right )_{E\left (U|q\right )}$. Then $E\left (U|q\right )$ is cyclic and $e(U|q)=e$. Also, $q$ is unramified in $K'$ and every prime of $\mathbb{Z}$ which is unramified in $K$ is also unramified in $K'.$
Finally, $KL=K'L$ and $K'$ has prime power degree over $\mathbb{Q}$.

I won't do the details. Essentially, all we did is obtain a new number field which also has prime power degree, where $q$ has no ramification and the primes unramified in $K$ are still unramified in $K'$. Therefore, repeating the procedure we obtain a number field of degree $p^k$ in which the only ramified prime is $p$.
Up to now I understood everything. But by a further reduction we can consider that $K$ is a cyclic extension, but I do not understand the proof, which is the following:

Since any abelian group is a direct sum of cyclic group of prime power order, any abelian extension is a composite of cyclic extensions of prime power degree. The proposition above allows us to assume that $p$ is the only ramified prime in each of these cyclic extensions. $\blacksquare$

I get that the abelian extension is the composite of cyclic extensions of prime power degree, but I do not understand why the above proposition guarantees that the number field $K'$ constructed above is still a cyclic extension of $\mathbb{Q}$. Any help?
EDIT:
User @reuns asked me to put more detail on the construction of $L$ and $K'$. Specifically, this is a little amount of exercises on Chapter $4$ of Marcus's Number Fields, and the specific exercise is the following:


text:
Q: Should I create a new Flurry analytics app id if I upgrade my app version? I want to analyse the user behavior in different version of my app, should I create different app id in Flurry  analytics like DemoApp1.0, DemoApp1.1 etc,
Or Flurry analytics will automatically records the different version?
Thanks

A: No. you should not create a separate app id, nor would any analytics service require you to create a seaprate id.
Havign the same id helps you to see the numbers and compare versions etc.
(btw, all this should be there in flurry faq)

A: No, I think flurry has application's version management function.

A: In your app delegate, before he Flurry startSesstion call, try:
[FlurryAnalytics setAppVersion:@"1.2"];


text:
Q: How can I create a REGEXP constraint on a column? I am trying to put a regexp constraint on a field "StaffAdress" such that it should only end with " street".
This is my attempt, but it still doesn't seem to be valid. I tried regexp '.*street$' and regexp 'street$' but both did not let me add "test street" in the table.
CREATE TABLE MsStaff (
   `StaffId` CHAR(4) PRIMARY KEY CHECK (`StaffId` regexp 'S[0-9][0-9][0-9]'),
    `StaffName` VARCHAR(100) NOT NULL,
    `StaffGender` VARCHAR(6) NOT NULL,
    `StaffAddress` VARCHAR(100) NOT NULL CHECK ('StaffAddress' regexp '.*street$')
)

I'm using 10.4.19-MariaDB

A: I think your problem is that you are comparing a literal string, not a column, to your regex.
...CHECK ('StaffAddress' regexp '.*street$')

should be (don't forget the space)
...CHECK (StaffAddress regexp '.* street$')

A: 'StaffAddress' regexp '.*street$' will always return false. Column names have to be quoted in backticks, not in single quotes.
Correct would be:
`StaffAddress` VARCHAR(100) NOT NULL CHECK (`StaffAddress` regexp '\w*\ street$')


text:
Q: Changing/looping text in label I want to make my label change text every 5 seconds from rLabel.text = "\(update) free trial" wait for another 5 second then change it rLabel.text = "upgrade now!" ~ on repeat.
rLabel.text = "\(update) free trial"
    if daysLeft <= 5 {
            let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
            timer.fire()
        }
    } else {
        rLabel.text = "\(update) free trial"
    }
@objc func update() {
    rLabel.text = "upgrade now!"
}

A: You can simply use a boolean to switch the text every 5 sec
override func viewDidLoad() {
     let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}

var isShowingText1 = false
@objc func updateText(){
    rLabel.text = isShowingText1 ? "Text 2" : "Text 1"
    isShowingText1 = !isShowingText1
}

A: You can keep track of current text by having index property. Also you can use Timer with block closure and you can avoid having Obj-C-ish #selector
var index = 0 {
    didSet {
        if index > 1 { index = 0 }
    }
}

var text: String {
    return ["\(update) free trial", "upgrade now!"][index]
}

func foo() {
    rLabel.text = text
    Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
        self.index += 1
        self.rLabel.text = self.text
    }
}


text:
Q: Entity Framework: Set default limit for queries I've just started working on some code that uses EF6 (Code First) and quite badly written. I discovered many cases where several thousand rows were returned from queries before they were paged (paging was applied after enumerating over the queryable).
Is there a way to intercept all IQueryable executions by default and apply .Take(128)?

A: If you have bad code, the best you can do is to fix it of course, and not by adding weird workarounds..
One option you could try to use as weird workaround is (relatively new?) IDbCommandTreeInterceptor which allows you to rewrite the expression tree at the "expressions" level:
public class LimitInterceptor : IDbCommandTreeInterceptor
{
    public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
    {
        if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
        {
            var queryCommand = interceptionContext.Result as DbQueryCommandTree;
            if (queryCommand != null)
            {
                var newQuery = queryCommand.Query.Accept(new LimitVisitor());
                interceptionContext.Result = new DbQueryCommandTree(
                    queryCommand.MetadataWorkspace,
                    queryCommand.DataSpace,
                    newQuery);
            }
        }
    }
}

// rewrite the tree - needs adjustment probably, looks like a very naive implementation (?)
public class LimitVisitor : DefaultExpressionVisitor
{
    public override DbExpression Visit(DbScanExpression expression)
    {
        // here we go!
        return DbExpressionBuilder.Limit(expression, 128);
    }
}

// will be automatically picked up
public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        AddInterceptor(new LimitInterceptor());
    }
}

Found about about IDbCommandTreeInterceptor from this post.
There is also another interception option (but it is for already-generated sql) IDbCommandInterceptor, maybe you'll be able to make some use of it.


text:
Q: use a variable multiple times in a sql statement with pymysql [edit: removed the where statement]
I'm trying to update a table when duplicate keys are passed in
I have a list like
examplelist = [[key1, value1], [key2, value2], [key3, value3]]

and a table with, for example, key1 and key3 already in the table with different values, so we want to update those rows and insert the key/value pair key2 value2 in. The table was created with:
cursor.execute('CREATE TABLE exampletable (keycolumn FLOAT, valuecolumn FLOAT)')
cursor.execute('CREATE INDEX keycolumn_index ON exampletable (keycolumn DESC)')

I was trying to use
sql = "INSERT INTO exampletable (keycolumn, valuecolumn) VALUES (%s, %s)"\
" ON DUPLICATE KEY UPDATE valuecolumn = VALUES(valuecolumn)"
cursor.executemany(sql, examplelist)

but I get a bunch of rows with the same keycolumn value
I can just change the input to a list of 3 element lists but this seems really sloppy, I imagine there's a more elegant way

A: The problem is using float type for the index. This leads to unpredictable behavior as equality checking doesn't work well for float types.
use something like DECIMAL(total_precision, decimal_precision) for the key type instead.
Also, the query can be simplified to initialize the key on declaring the table.
cursor.execute('CREATE TABLE exampletable (keycolumn DECIMAL(10,2) PRIMARY KEY, valuecolumn DECIMAL(10,2))')


text:
Q: My model is only saving some of the information This is a simple rails form using CKeditor.
I'm saving the content, it appears in the Update.
pp params[:email]["body"]
"
\r\nheyyy
\r\nbut now i am going to save this past 9 lines.
\r\ncuz  that's what this is all about
\r\n
\r\nI am crazy like that
\r\nc
\r\ncrazy
\r\ncrazy c
\r\ncrazy
\r\n
\r\nhere is another line..
\r\noh@!!&
\r\nfa
\r\nsdf
\r\nas
\r\ndf
\r\nasd
\r\nfa
\r\nsdfasdf
\r\n"

Then my controller goes like this :
@emails = Email.find(params[:id])

Then! After this is called, I type @emails.body in ruby-debug, and it outputs 1/2 of that! :
@emails.body
"
\r\nheyyy
\r\nbut now i am going to save this past 9 lines.
\r\ncuz  that's what this is all about
\r\n
\r\nI am crazy like that
\r\nc
\r\ncrazy
\r\ncrazy c
\r\ncrazy
\r\n
\r\nhere is another line..
\r\noh@!!&"

Why would that occur?
The attribute is saved as a string in my database.

A: What sort of column is body?  Could it be that it's a MySQL varchar(255) or something similar that's just being overloaded?

A: You're likely storing it in the database as a varchar instead of text. Depending on the length of the varchar, it will simply truncate the data instead of return an error. You can easily change the column type in a migration:
change_column :my_table, :my_column, :text

A: Are you sure you called:
 @emails.save

in the controller ??
If so, try calling:
 @emails.save!

It should raise an error if something goes wrong.


text:
Q: Python : How do I look for '100%' as a string in a .txt file I have a .txt file (eg. test.txt). Using python, I want to search the string "100%" in this .txt file. Please help.
       file = open('test.txt', 'r')
       for line in file.readlines():
           if '100%' in line:
               print "Successfully downloaded."

A portion of test.txt looks like:
6800K .......... .......... .......... .......... .......... 98% 11.1M 0s
  6850K .......... .......... .......... .......... .......... 99% 10.4M 0s
  6900K .......... .......... .......... .......... .         100% 12.6M=2.3s

And I want to look for '100%' in this file.

A: Depending on what you call "searching", here's a version:
lines = open('file.txt').readlines()
i = 1
for line in lines:
    if "100%" in line:
        print ("Line %s:" % i), line,
    i = i + 1

A: with open('test.txt') as f:
    for line in f:
        if '100%' in line:
            print 'found'

the with means that the file, which is opened as f, will be closed when you are done.  the for line in f gives you each line in turn (and may be more memory friendly than reading everything first with readlines()).
but what you have looks fine to me if you drop the "\" and indent the print.  what error do you get?


text:
Q: Windows 7 64bit, Qt 4: glGetVersion returns "1.1.0", nvogl32v.dll gets unloaded situation
I'm developing 32bit application that uses Qt 4, and I"m working on Windows 7 64bit.
My program has main non-OpenGL widget, and QGLWidget which is optionally opened by the user.
problem:
When I create that QGLWidget, glGetVersion reports "1.1.0" (my hardware supports OpenGL 4.3.0). As a result many functions I need do not work at all (obviosuly, because they are not available in OpenGL 1). This problem happens "sometimes".
additional info
IF I launch program using gDebugger everything works fine, and glGetVersion returns "4.3.0", as expected.
Adding this line:
QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags();

at the beginning of main() function also fixes the problem.
The application works fine on WinXP 32bit.
I wrote OpenGL subsystem for this app 2..3 years ago and the guys who used it said they had similar problem on virtual machines (Win7 or vista guest), but I don't remember how I dealt with this problem at that time.
OpenGL initialization
OpenGL initialization is performed by Qt 4, without glew or extra libraries, using QGLWidget.
There's only one QGLWidget in the program. To be precise, there's a class derived from QGLWidget, its initalization looks like this:
DisplayWidget::DisplayWidget(QWidget* parent)
    : QGLWidget(QGLFormat(QGL::DoubleBuffer | QGL::DepthBuffer), parent)

System configuration:
OS: Windows 7 64bit.
Compiler: MSVC2008 express SP1.
Qt: Qt 4.8.1 (compiled from source with OpenSSL support using MSVC2008).
Windows SDK: Windows Server 2008 and .NET 3.5.
GPU: GeForce 460 GTX
question:
What could be causing this problem?
--update--
"magical fix" (OpenGLVersionFlags) has stopped working after full rebuild, and now application constantly initializes software renderer, even when launched using gDebugger.
All other OpenGL applications on my machine work fine and can use shaders.
I use latest drivers.
Any ideas?
--update--
After some testing I found that somehow google chrome and steam client affect all Qt application that use OpenGL.
If I have Google Chrome and Steam open, eventually all programs will stop working properly and will no longer be able to get hardware accelerated OpenGL.
If I close google chrome and keep steam open, every 2nd attempt to launch hardware accelerated program will fail.
If I close both steam and chrome, then every program launch will be successful.
Why could this be happening?
--update--
I've read through debugger output, and found a very interesting thing:
'vdclient.exe': Loaded 'C:\Windows\SysWOW64\nvoglv32.dll'
First-chance exception at 0x777f47a5 (ntdll.dll) in vdclient.exe: 0xC0000005: Access violation reading location 0x05aa9000.
'vdclient.exe': Unloaded 'C:\Windows\SysWOW64\nvoglv32.dll'

Basically, when loading nvoglv32.dll, "something" crahses somewhere (debugger doesn't react to this event, byt the way), and system decides to unload nvoglv32.dll. Judging by its name it is nvidia system/driver component, and without this component there can be no hardware acceleration.
When opengl works properly, this part of log looks like this:
'vdclient.exe': Loaded 'C:\Windows\SysWOW64\nvoglv32.dll'
'vdclient.exe': Loaded 'C:\Windows\SysWOW64\ntmarta.dll', Symbols loaded (source information stripped).
'vdclient.exe': Loaded 'C:\Windows\SysWOW64\Wldap32.dll', Symbols loaded (source information stripped).
'vdclient.exe': Loaded 'C:\Windows\SysWOW64\powrprof.dll', Symbols loaded (source information stripped).
The thread 'Win32 Thread' (0x1744) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x1740) has exited with code 0 (0x0).
'vdclient.exe': Unloaded 'C:\Windows\SysWOW64\powrprof.dll'
The thread 'Win32 Thread' (0x1748) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x174c) has exited with code 0 (0x0).
'vdclient.exe': Loaded 'C:\Windows\SysWOW64\uxtheme.dll', Symbols loaded (source information stripped).

Ideas?

A: Are you specifying the OpenGL version using QGLFormat.setVersion + QGLFormat.setProfile ?
QGLFormat glFormat;
glFormat.setVersion( 3, 2 );
glFormat.setProfile( QGLFormat::CoreProfile );
glFormat.setSampleBuffers( true );

QGLWidget w( glFormat );

Another potential problem. Your glGetVersion should be called be after the OpenGL context has been initialized in the QGLWidget.initializeGL() method.

A: Okay, I give up.
I'll mark it as a driver bug or Google Chrome incompatibility.
I'm gonna add this quirk|problem to project's readme and ensure that app works fine(i.e. doesn't display artifacts) even if OpenGL is emulated.

A: OpenGL 3.0 and higher has a deprecation model for legacy features. In old OpenGL versions, the new version was a superset of the old version. I.e. if you wanted OpenGL 1.5 context and got OpenGL 2.0 context, that was fine. Once the possibility of removing old functionality came into being, that is no longer viable. Extension WGL_ARB_create_context was made:  it exposes a new function to replace wglCreateContext. Much like wglChoosePixelFormatARB, it adds an extensibility mechanism to the system that makes it possible to extend the options for context creation. It it impossible to create OpenGL 3.2+ Core Profile context without using this function.
Here is the official up-to-date documentation on how to create an OpenGL context: http://www.opengl.org/wiki/Creating_an_OpenGL_Context_(WGL)


text:
Q: Change words on tkinter Messagebox buttons I'm using tkinter's "askokcancel" message box to warn the user, with a pop-up, of an irreversible action.
from tkinter import Tk
Tk().withdraw()
from tkinter.messagebox import askokcancel
askokcancel("Warning", "This will delete stuff")

I'd like to change the text of the 'OK' button (from 'OK') to something like 'Delete', to make it less benign-looking.
Is this possible?
If not, what is another way to achieve it? Preferably without introducing any dependancies...

A: No, there is no way to change the text of the buttons for the built-in dialogs.
Your best option is to create your own dialog. It's not very hard to do, and it gives you absolute control over what is in the dialog widget.

A: It is true that you cannot change names in Tkinter messageboxes, but you can make your own class of messagebox so that you can reuse it several times. The following code is the same as Tkinter messagebox, but it has args and kwargs as arguments. It is just for convenience.
I am also learning, so the code does not have flash and alarm.
class Message(object):
    def __init__(self,parent, *args, **kwargs):
        self.parent=parent
        top=Toplevel(self.parent)
        top.geometry("400x200")
        top.transient(self.parent)

        top.title(args[0])
        f0=Frame(top)
        top.l1=Label(f0, text=args[1])
        top.l1.pack(pady=30)
        f0.pack()
        top.grab_set()
        top.f1=Frame(top)
        for key in kwargs:
            key=Button(top.f1, text=f"{kwargs[key]}")
            key.pack(side=LEFT)
        top.f1.pack()

The message box will look like this:

A: Why not open a child window thus creating your own box with your own button like this:
from tkinter import *
def messageWindow():
    win = Toplevel()
    win.title('warning')
    message = "This will delete stuff"
    Label(win, text=message).pack()
    Button(win, text='Delete', command=win.destroy).pack()
root = Tk()
Button(root, text='Bring up Message', command=messageWindow).pack()
root.mainloop()


text:
Q: In a github actions workflow, is there a way to have multiple jobs reuse the same setup? I recently hooked up my project with github actions for continuous integration. I created two separate jobs: the first one checks if the code in the pull request is accepted by our linter, and the second one checks if the code passes the test suite. I like that having two jobs like this shows up as two separate checkmarks in the Github webpage for the pull request:

The problem I'm having now is that there is some duplicated code in workflow YAML file: the first 3 steps, which install Lua and Luarocks. Not only is it annoying to maintain, but it also wastes CI minutes by running the same actions twice. Is there a way to avoid this? So that the setup code is only written in one place, and only runs once when the workflow executes?
But I am confused what would be the proper way to proceed:

*

*Should I create my own Github Action with the shared setup code?

*Should I create a Docker image that already has Lua and Luarocks pre-installed?

*Should I use a single job? Can I still have independent checkmarks for the linter and the test suite if they are steps of the same job?

*Something else?

Here is the current YAML file for my workflow:
name: Github Actions CI

on: [ pull_request ]

jobs:
    lint:
        name: Lint
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v2
            - uses: leafo/gh-actions-lua@v8.0.0
            - uses: leafo/gh-actions-luarocks@v4.0.0

            - run: luarocks install luacheck
            - run: ./run-linter.sh

    test:
        name: Test
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v2
            - uses: leafo/gh-actions-lua@v8.0.0
            - uses: leafo/gh-actions-luarocks@v4.0.0

            - run: luarocks install busted
            - run: ./build-project.sh
            - run: ./run-test-suite.sh

I tried searching for similar questions but couldn't find anything that exactly answered my question:

*

*Caching APT packages in GitHub Actions workflow: I can't use this solution because I don't have a way to precisely specify all the versions of all the dependencies that I am using, so that they may be cached. I also don't mind if separate runs of the workflow are not cached. I'm more worried about the code duplication.

*Github actions share workspace/artifacts between jobs? I don't want to have to manage uploading uploading artifacts to a separate service and then deleting them afterwards.

*Reuse portion of github action across jobs: In that question the only difference between the jobs is a single variable, so accepted answer is to use a build matrix. But I don't think a build matrix would work as well in my case, where only the setup code is the same?

A: As of today (August 2021) composite action is no longer limited to run. GitHub Actions: Reduce duplication with action composition
name: "Publish to Docker"
description: "Pushes built artifacts to Docker"

inputs:
  registry_username:
    description: "Username for image registry"
    required: true
  registry_password:
    description: "Password for image registry"
    required: true

runs:
  using: "composite"
  steps:
      - uses: docker/setup-buildx-action@v1

      - uses: docker/login-action@v1
        with:
          username: ${{inputs.registry_username}}
          password: ${{inputs.registry_password}}

      - uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          tags: user/app:latest

Old Answer
What you are looking for is composite action which help you reuse once defined set of steps.
jobs:
    lint:
        name: Lint
        runs-on: ubuntu-latest
        steps:
            - uses: octocat/say-hello@v1

            - run: luarocks install luacheck
            - run: ./run-linter.sh

    test:
        name: Test
        runs-on: ubuntu-latest
        steps:
            - uses: octocat/say-hello@v1

            - run: luarocks install busted
            - run: ./build-project.sh
            - run: ./run-test-suite.sh

octocat/say-hello/action.yml:
runs:
  using: "composite"
  steps:
    - run: echo "Nice to meet you!"
      shell: pwsh

For more details you can also check's ADR here.
And why you can't simply run it once for all jobs, because each job may run on a different machine.

A job is a set of steps that execute on the same runner. By default, a workflow with multiple jobs will run those jobs in parallel. You can also configure a workflow to run jobs sequentially. For example, a workflow can have two sequential jobs that build and test code, where the test job is dependent on the status of the build job. If the build job fails, the test job will not run.

A: There are 3 main approaches for code reusing in GitHub Actions:

*

*Reusable Workflows

*Dispatched workflows

*Composite Actions
There is an article describing their pros and cons.
In your case if the duplicated steps are in the single workflow you also can:

*

*extract them to the "preparation" job

*upload build artifacts

*add "preparation" job to "needs" key of both jobs

*download build artifact in both jobs

A: The below code snippet should do the work for you. Instead of creating two jobs, one for lint and another for test, you can use one job and create multiple tasks
name: Github Actions CI

on: [ pull_request ]

jobs:
    lint:
        name: Lint and Test
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v2
            - uses: leafo/gh-actions-lua@v8.0.0
            - uses: leafo/gh-actions-luarocks@v4.0.0

            - name: Install Luacheck
              run: luarocks install luacheck

            - name: Run Lint Check
            - run: ./run-linter.sh

            - name: Install Busted
              run: luarocks install busted

            - name: Build Project
              run: ./build-project.sh

            - name: Run Test Suite
            - run: ./run-test-suite.sh


text:
Q: How to Iterate Map values inside BaseAdapter's GetView() method? I am trying to parse the following Json.
{
"effect_list": [{
      "1":[
         {
            "effects_id":"1",
            "effects_name":"Band 1"
         },
         {
            "effects_id":"2",
            "effects_name":"Band 2"
         }

      ],
      "2": [
         {
            "effects_id":"4",
            "effects_name":"Background Blur"
         },
         {
            "effects_id":"5",
            "effects_name":"Blemish Removal"
         }
      ]
   }]
}

My BaseAdapter shows only first Item in the ListView. I am trying to retrieve values in Map. During iteration the values gets override.When I print the values, It's printing properly.
MyContactAdapter2.java
public class MyContactAdapter2 extends BaseAdapter {
        List<Map<String, List<EffectList>>> contactList;
        Context context;
        private LayoutInflater mInflater;

        // Constructors
        public MyContactAdapter2(Context context, List<Map<String, List<EffectList>>> objects) {

            this.context = context;
            this.mInflater = LayoutInflater.from(context);
            contactList = objects;
        }

        public MyContactAdapter2() {
            System.out.println("hai");
        }

        @Override
        public int getCount() {
            int count = contactList.size();
            System.out.println("Count size" + count);
            return count;
        }

        @Override
        public Map<String, List<EffectList>> getItem(int position) {
            return contactList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            System.out.println(10);

            final MyContactAdapter2.ViewHolder vh;
            if (convertView == null) {
                View view = mInflater.inflate(R.layout.get_layout_row_view, parent, false);
                vh = MyContactAdapter2.ViewHolder.create((RelativeLayout) view);
                view.setTag(vh);

            } else {
                vh = (MyContactAdapter2.ViewHolder) convertView.getTag();
            }

            for (Map<String, List<EffectList>> map : contactList) {
                for (Map.Entry<String, List<EffectList>> entry : map.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    System.out.println("key :" + key + "value :" + value);

                        EffectList item = getItem(position).get(key).get(0);

                        vh.textViewName.setText(item.getEffectsId());
                        vh.textViewEmail.setText(item.getEffectsName());

                }
            }

            return vh.rootView;
        }

        private static class ViewHolder {
            public final RelativeLayout rootView;
            public final ImageView imageView;
            public final TextView textViewName;
            public final TextView textViewEmail;

            private ViewHolder(RelativeLayout rootView, ImageView imageView, TextView textViewName, TextView textViewEmail) {
                this.rootView = rootView;
                this.imageView = imageView;
                this.textViewName = textViewName;
                this.textViewEmail = textViewEmail;
            }

            public static MyContactAdapter2.ViewHolder create(RelativeLayout rootView) {
                ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
                TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
                TextView textViewEmail = (TextView) rootView.findViewById(R.id.textViewEmail);
                return new MyContactAdapter2.ViewHolder(rootView, imageView, textViewName, textViewEmail);
            }
        }
    }

So my Question is, how can I iterate the "Map" values inside "GetView()" in "BaseAdapter"?
Is it possible to iterate values inside GetView() method in BaseAdapter?

A: Can't you do:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // ... blah blah ...

    final Map<String, List<EffectList>> effectMap = getItem(position);

    for (Map.Entry<String, List<EffectList>> entry : effectMap.entrySet()) {
        final String key = entry.getKey();
        final List<EffectList> value = entry.getValue();
        // ... do stuff ...
    }

    // ... blah blah
}

?


text:
Q: Construct full name from Active Directory like outlook/lync I would like to construct the full name based on Active Directory and show it like whart I can see in Outlook / Lync .
I tried to handle case by case but I believe there is general case for that and what I reached till now:
LastName, FirstName MiddleName (DisplayNameExtension)
like Thabet, Mohammed Ali (XYZ Enterprise)
Please let me know if you have the general pattern ?


text:
Q: Global keylistener The program is working at background and listening keyboard(like keylogger)
First I select a string on pdf or etc. Then I pressed the ctrl + rbutton the program must be pop up and it can be get my selected string.
For this;
[DllImport("User32.dll")]
private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

[DllImport("User32.dll")]
private static extern short GetAsyncKeyState(System.Int32 vKey);

string key = "";
private void timer1_Tick(object sender, EventArgs e)
{
    timer1.Interval = 5;
    foreach (System.Int32 i in Enum.GetValues(typeof(Keys)))
    {
        int x = GetAsyncKeyState(i);
        if ((x == 1) || (x == -32767))
        {
            keyBuffer += Enum.GetName(typeof(Keys), i);
        }
    }
    if (keyBuffer != "")
    {
        keyBuffer = keyBuffer.ToLower();
        if (keyBuffer.Contains("lcontrolkeyrbutton"))
        {
            // do somethings
            keyBuffer = "";
        }
    }
}

But after first performing, ctrl + rbutton it doesn't work. What's the wrong? And how can i get the selected string into my program?

A: Sounds like you want a clipboard hook (in addition to your global key hook). Take a look here: Clipboard event C#
If you want to capture the string without the user copying it into the clipboard manually, you could send ctrl+c to the application yourself: http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx

A: Here is the program funcional and tested
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CtrLetterCopy
{

    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        const int WM_COMMAND = 0x111;

        enum KeyModifier
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            WinKey = 8
        }

        public Form1()
        {
            InitializeComponent();
            this.ShowInTaskbar = false;
            int id_Ctrl = 0;     // The id of the hotkey.
            RegisterHotKey(this.Handle, id_Ctrl, (int)KeyModifier.Control, Keys.R.GetHashCode());
        }

        protected override void WndProc(ref Message m)
        {
            //const int WM_HOTKEY = 0x0312;
            if (m.Msg == 0x0312)
            {
                if (m.WParam.ToInt32() == 0)
                {
                    //do what you want here
                    SendKeyEvent();

                }
            }
            base.WndProc(ref m);
        }

        private void SendKeyEvent()
        {
            SendKeys.SendWait("^c");
            Thread.Sleep(500);
            string test3 = Clipboard.GetText();
            MessageBox.Show(test3);
        }
    }
}

A: You need to SendKeyEvent(Ctrl+C) of MainWindowsHandle First, then Using Clipboard capture your text to your Project.

A: Download and check out this code here:
http://www.codeproject.com/KB/cs/globalhook.aspx
Pre-tested, well-written and fully functional.
Best of luck!


text:
Q: how can foreach mysql result? I have 2 Columns in mysql. valami2 and playerID in table players_extra.
I will the following:
give 3000 coppers for the first row in valami2, then 2500 coppers for the second(then each row -500 coppers until the 5th place)....after the 5th place give 500 until the 10th place. for the CORRECT payerID.
            $aseco->console('>> Updating `hetimostfin` counts for all Players...');
        $hetimostfin = array();
        $line = 0;
        $coppers = 3000;
        $query = "
        SELECT
            `playerID`,
            COUNT(`valami2`) AS `Count`
        FROM `players_extra`
        GROUP BY `playerID`;
        ";
        $res2 = mysql_query($query);
        if ($res2) {
            if (mysql_num_rows($res2) > 0) {
                while ($row = mysql_fetch_object($res2)) {
                    $hetimostfin[$row->playerID] = $row->Count;
                }
                foreach ($hetimostfin as $id => $count) {
                    $res2 = mysql_query("
                        UPDATE `players_extra`
                        SET `valami2` =(`valami2`+'".$coppers."')
                        WHERE `playerID` = ". $id ."
                    ");
                    $line ++;
        $coppers=($coppers-500);

        if ($line >= 6) {
            $coppers=500;
        }
        if ($line == 10){
            break;
        }
        }
        }
        }

A: Try PDO. It's a much better and safer way of interacting with databases for PHP. http://php.net/manual/en/pdo.connections.php
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$hetimostfin = array();
$coppers = 3000;
$line = 0;

$query = <<<SQL
SELECT
   playerID,
   COUNT(valami2) AS `count`
FROM players_extra
GROUP BY playerID;
SQL;

foreach($dbh->query($query, PDO::FETCH_ASSOC) as $row) {
    $hetimostfin[[$row['playerID']] = $row['count'];
    // execute update statement
    $line++;
}


text:
Q: Is there a way to have a stop recursion in prolog after a certain number of iterations? This the code I have written,
passesBatonTo(bob, doug).
passesBatonTo(doug, steve).
passesBatonTo(steve, sam).
passesBatonTo(sam, bob).

getRelayTeam(X):-
    passesBatonTo(X, Y),
    write(Y), nl,
    getRelayTeam(Y).

I want the code give the full relay team but the code goes into infinite loop.

Eg: getRelayTeam(bob) should give bob, doug, steve, sam

or

getRelayTeam(steve) should give steve, sam, bob, doug

A: You could try this trick, with a countdown value:
passesBatonTo(bob, doug).
passesBatonTo(doug, steve).
passesBatonTo(steve, sam).
passesBatonTo(sam, bob).

% getRelayTeam(X,RelaysLeft)

getRelayTeam(X,0) :-
   !, % tell Prolog there is no point in trying the next clause if this head matched
   format("No more relays for you, ~q is the last carrier!\n",[X]).

getRelayTeam(X,RelaysLeft) :-
    RelaysLeft > 0, % make clear we want RelaysLeft > 0 (even though we use ! above)
    passesBatonTo(X, Y),
    format("Passed baton from ~q to ~q\n",[X,Y]),
    succ(RelaysLeftNow,RelaysLeft),
    getRelayTeam(Y,RelaysLeftNow).

And so:
?- getRelayTeam(bob,4).
Passed baton from bob to doug
Passed baton from doug to steve
Passed baton from steve to sam
Passed baton from sam to bob
No more relays for you, bob is the last carrier!
true.


text:
Q: Boolean value assigned is never used - Java / Android Studio I don't understand why Android Studio is telling me that the value assigned to isOne is never being used. I have set the value to be false and true within the if statement of the fade method. When I declare the variable isOne as a member variable instead of a local variable, however, the error is gone and it seems to work perfectly. I'm not sure why that fixed the error....Any thoughts ?
private ImageView img1;
private ImageView img2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    img1 = (ImageView) findViewById(R.id.porsche1);
    img2 = (ImageView) findViewById(R.id.porsche2);

    img1.setOnClickListener(this);
    img2.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    fade();
}

public void fade(){
   boolean isOne = true;

    if (isOne) {
        img1.animate().alpha(0).setDuration(2000);
        img2.animate().alpha(1).setDuration(2000);
        isOne = false;
    } else {
        img1.animate().alpha(1).setDuration(2000);
        img2.animate().alpha(0).setDuration(2000);
        isOne = true;
    }

}

}

A: Use this way, I hope it will help for you
boolean isOne = false;   // Use Globally

    public void fade(){

        if (isOne) {
            img1.animate().alpha(0).setDuration(2000);
            img2.animate().alpha(1).setDuration(2000);
        } else {
            img1.animate().alpha(1).setDuration(2000);
            img2.animate().alpha(0).setDuration(2000);
        }
    }

A: At the end of both the "if" and "else" blocks, you assign a value to isOne. You never use that value after setting it, so those assignments are unused. Each new invocation redeclares isOne, so that last assignment does not become the next invocation's initial value.
Fields are harder to analyze, since the last assignment of one invocation would be used as the initial value of the next invocation (assuming there two methods are invoked on the same instance).


text:
Q: Dúvidas criação, manipulação e eliminação de form Possuo as seguintes dúvidas:

*

*Ao criar um form, conforme o código abaixo, preciso destruir ele de alguma maneira quando o mesmo for finalizado pelo usuário?

F_PesqCli := TF_PesqCli.Create(self);
F_PesqCli.ShowModal;

*

*Como garantir que uma janela não seja aberta duplamente?

*Como faço para minimizar um form internamente, como no exemplo da imagem abaixo?

A: 1. Como garantir a liberação do form da memória?

Ao criar um form, conforme o código abaixo, preciso destruir ele de alguma maneira quando o mesmo for finalizado pelo usuário?
F_PesqCli := TF_PesqCli.Create(self);

O construtor Create padrão dos objetos TComponent no delphi recebe por parâmetro (AOwner: TComponent)
Se você passa o Owner como Self, você está dizendo que a instância atual de onde o código está é a dona do componente criado, no caso o TForm. Sendo assim, quando esse Dono for destruído, o form também será.
Se você quer que, quando o usuário finalizar um form, que ele seja destruído, no evento onClose do form basta você setar a ação desejada
Action := caFree;

Outra medida é gerenciar o ciclo de vida as janelas Modal durante a inicialização delas:
Form := TForm.Create(nil);
try
  Form.ShowModal;
finally
  Form.Free;
end;

2. Como garantir que uma janela não seja aberta duplamente?
A maneira mais segura é validar nos já criados na aplicação
function ValidaFormJaCriado(const ClassDoForm: TClass): Boolean;
var
  I: Integer;
begin
  Result := False;
  for I := 0 to Screen.FormCount - 1 do
  begin
    if Screen.Forms[I].Class = ClassDoForm then
    begin
      Result := True;
      Break;
    end;
  end;
end;

3. Como faço para minimizar um form internamente, como no exemplo da imagem abaixo?
O Form Principal deve ser setada a propriedade FormStyle para fsMDIForm
Os forms filhos devem ter o form pai como Owner e FormStyle para fsMDIChild


text:
Q: RtlQueryRegistryValues read REG_DWORD I'm writing a Uart16550 driver, and one of the things I have to do is read from the registry some initialization parameters using RtlQueryRegistryValues.
(a lot of code skipped...)
RTL_QUERY_REGISTRY_TABLE table[2];

and
table[1].QueryRoutine = NULL;
table[1].Name = NULL;

The parameter is stored in the registry as a REG_DWORD and I'm trying to set my table with:
unsigned long buffer;

(because DWORD is not defined in ntddk.h and I'm not sure if I break anything including WinDef.h)
and
table[0].EntryContext = &buffer;

The status of the call to RtlQueryRegistryValues is STATUS_SUCCESS
status =  RtlQueryRegistryValues(
    RTL_REGISTRY_ABSOLUTE,
    path,
    table,
    NULL,
    NULL);

but when I try to
DbgPrint("registry: %lu", buffer)

I get way too big numbers (I expected the result to be 1 or 2).
Am I doing something wrong with the DbgPrint, or my parameters aren't set correctly for the query table?
And where is the RED_DWORD data type defined?
EDIT:
WCHAR keyname[20] = "parameter";
CHAR def[20] = "parameter";
WCHAR path[100] = L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services\\hello\\Parameters";
unsigned long buffer;
table[0].QueryRoutine = NULL;
table[0].Name = keyname;
table[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
table[0].EntryContext = &buffer;
table[0].DefaultType = REG_DWORD;
table[0].DefaultData = def;
table[0].DefaultLength = strlen(def) + 1;

A: table[0].DefaultData should be a pointer to an unsigned long.
table[0].DefaultLength should be sizeof(unsigned long).
Otherwise you may get back 1634886000 which is your default value converted to long ('para'). Everything else looks like it should work (assuming the key and value actually exists).

REG_DWORD is defined in winnt.h
#define REG_DWORD                   ( 4 )   // 32-bit number
#define REG_DWORD_LITTLE_ENDIAN     ( 4 )   // 32-bit number (same as REG_DWORD)
#define REG_DWORD_BIG_ENDIAN        ( 5 )   // 32-bit number


text:
Q: How do I automatically take data from a Google form and generate a new spreadsheet from each response then have it automatically format it? So basically I want to take the form response data in "Form Responses 1" and then feed the data into "John Doe Response". So every google form response would:
A) Generate a new sheet
B) Be automatically formatted into the format in the John Doe Sheet
C) Automatically name the tabs (ie John Doe Response) with the students name from question 1.
Here is my Google Form: https://docs.google.com/spreadsheets/d/11NW0OFf_jWLelKjw4i-F-holjCInZSluIeZCr0v9aZk/edit?usp=sharing
Unsure if this is possible but if so, that would be incredible! We are a school and definitely need the help on this.

Here is the code I am trying to work with, it errors out with: TypeError: Cannot read properties of undefined (reading 'values'). I think i need to substitute in the names of the spreadsheets? Please be explicit, I have little programming knowledge..
function onFormSubmit(e) {
  const [timestamp, name, homephone, cellphone, counselor, email, hobbies, activity, transport] = e.values;
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const template = ss.getSheetByName('Template');
  const sheetname = `${name} Response`;
  let sheet = ss.getSheetByName(sheetname);

  if (!sheet) {
    sheet = template.copyTo(ss).setName(sheetname);
  }

  sheet.getRange('B1:B5').setValues([
    [name],
    [homephone],
    [cellphone],
    [email],
    [counselor],
  ]);

  sheet.getRange('A7').setValue(hobbies);
  sheet.getRange('A11').setValue(activity);

  if (transport === 'Yes') {
    sheet.getRange('C14').check();
  }
}

A:
TypeError: Cannot read properties of undefined (reading 'values')

The code you show seems fine. It is designed to run on an installable trigger. If you run the code in the script editor, the code will error out, because the event object e will be undefined in that context.

TypeError: Cannot read properties of null (reading 'copyTo')

The second error you have received, but did not mention in the question, comes because there is no sheet named 'Template' in the spreadsheet.
To make your code work, first create a template sheet whose name matches that specified in the code. Then create a trigger from left-hand pane in the spreadsheet's script editor. Finally, submit a new response to make the code run. To view any errors, open the project's execution log.
I need to point out that it is usually a bad idea to scatter your data to many sheets. It is almost always better to keep all the data in one sheet, and use filter views to sort rows and choose which rows are displayed at a given time. This approach lets you and other users only view and edit one type of data at a time, without disturbing others. You can view all the data easily, and let others focus on just the data that is relevant to them, while keeping just one master copy of everything.
For additional ease of use, you can insert links in the frozen section of the sheet to easily switch between filter views, instead of having to go to Data > Filter views to switch. See the Filter views example spreadsheet for an illustration.


text:
Q: Prove the determinant identity (2) For any natural $n$  prove that
\begin{gather*}
{\frac {  q \left|\begin {array}{ccc} {q}^{n+2}&
 \left( {\frac {p}{q}} \right) ^{n+2}& \left( {p}^{-1} \right) ^{n
+2}\\ {q}&  {\frac {p}{q}} &  {p}^{-1} \\ 1&1&1
\end {array} \right|  - p \left|\begin {array}{ccc} {q}^{n+1}&
 \left( {\frac {p}{q}} \right) ^{n+1}& \left( {p}^{-1} \right) ^{n
+1}\\ {q}&  {\frac {p}{q}} &  {p}^{-1} \\ 1&1&1
\end {array} \right|   }{   \left|
\begin {array}{ccc} {q}^{2}&{\frac {{p}^{2}}{{q}^{2}}}&{p}^{-2}
\\ q&{\frac {p}{q}}&{p}^{-1}\\ 1&1
&1\end {array} \right|   }}\\|| \\q\frac{\begin{vmatrix} q^{n+1} & p^{-(n+1)} \\ 1 & 1 \end{vmatrix}}{\begin{vmatrix} q& p^{-1} \\ 1 & 1 \end{vmatrix}}.
 \end{gather*}
I can prove it by brute force expansion but I hope there are more elegant way to do it.
See also My old similar question


text:
Q: Unable to join domain from Site-to-Site VPN Server I work for a small business that is looking to expand to the cloud so that our remote workers can access more of our systems. As a software dev and keen IT enthusiast, I jumped at the opportunity to get my hands dirty with this project. After spending the last 2 weeks attempting to get a test solution working on my PC with HyperV, I have a new found admiration for networking majors.
My Solution
Since we still have most people working in the office on a daily basis, I thought that we should make use of a Site-to-Site VPN connection and treat our office as a branch and the cloud like head office. Simple, right?
To test all this out, I set up my environment in HyperV, with all firewalls turned off, just to make communication a bit easier. Please be aware that my selection of subnet came from a tutorial.
All servers are running Windows Server 2019 Standard
Cloud Servers - 10.1.1.0/24

*

*SRV01   (Domain Controller)

*

*10.1.1.4

*VPN01  (Remote Access)

*

*10.1.1.10

*192.168.15.20 External IP
Office - 10.1.2.0/24

*VPN02 (Remote Access)

*

*10.1.2.150

*192.168.15.21 External IP
The Issue
Besides my limited knowledge, the issue that I am having is connecting VPN02 to the domain. I have the Site-to-Site VPN working, and I can ping SRV01 from VPN02, but I am unable to ping the other way. VPN01 can ping both servers, and vice versa. Running nslookup from VPN02 has seemingly good results as I can get the IP as well as the server name of both "cloud" servers.
I have setup 2 sites in AD Sites and Services, added the correct subnets to each site and linked them. I'm not really sure where to go from here. I know that I don't have the experience, but I also don't have the budget to get a professional in so I am all that I have. Plus, I like to add more things to my IT toolbelt.
Thanks in advanced.
EDIT: Adjusted IP ranges to not be on the same subnet. Still same issues though.


text:
Q: Why the adjective "vague" comes after the noun "change"? In Longman dictionary there is an example for disingenuous which says "Keeping the details of the tax changes vague is disingenuous."
the adjective vague precedes the verb is and follows the noun change

A: The word vague is applied to "the details of the tax changes". The word is then calls "Keeping the details ... vague" disingenuous.
In other words, the example asserts that it is disingenuous to "keep the details ... vague".


text:
Q: VBA / IE: How to use VBA to click a button on a website I am new to VBA and hope someone here can help me with the following:
I would like to use VBA to open a website and then click two different buttons on this website.
My challenges with this are:
1) How can I tell the code to wait until the webpage is fully loaded so that I can make sure the button that I want to click is actually visible ?
2) How do I address the button correctly using it's unique ID ?
My code so far:
Dim varResults As New DataObject
Dim varButtonID As String
Dim i As Long
Dim objIE As Object
Dim objElement As Object
Dim objCollection As Object

varResults.SetText TxtSql.Text
varResults.PutInClipboard

' assign button ID
varButtonID = "Oracle_setExplainOptionsSpan"

' create IE object
Set objIE = CreateObject("InternetExplorer.Application")

With objIE
    .navigate "https://myURL"
    .Visible = True
End With

While objIE.ReadyState <> 4: Wend

objIE.document.getElementById(varButtonID).Click

Many thanks in advance for any help with this,
Mike

A: You can try to find the button by class name to click the button.
With ie.document
    Set elements = .getelementsbytagname("input")
    For Each e In elements
        If (e.getattribute("className") = "btnComment") Then
            e.Click
            Exit For
        End If
    Next e
End With

I can't think of a VBA command that waits until your page is loaded but you can enter a wait statement with a fixed time to wait.
Application.Wait(Now + #0:00:01#)

A: I always use the Do While loop to wait until a page has loaded before continuing.
Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop


text:
Q: Difference between @media and viewport How does @media only screen and (min-width: 1200px) differ from meta name="viewport" content="width=device-width"
I tried to place them both but nothing changes.

A: @Media only screen support IE9-10 and windows phones-, where as meta name="viewport" content="width=device-width" only support browsers like Chrome, Safari, Fire-F and Opera

A: Viewport :You're setting your mobile browser's viewport's width to be equal to your device width.For all the devices and desktops
Media Queries:A media query consists of a media type and zero or more expressions that check for the conditions of particular media features. Separate mediaqueries  for each resolutions of the devices


text:
Q: Using SignalR With between .NET Core projects I have 2 projects in the same solution (one is MVC - project "A" and the other is a Web API - project "B") with Onion architecture
I am using SignalR to broadcast messages to clients:
The clients are connected trough a View (project "A") - when this view loads, data is also loaded into te view
When project "B" recieves some data, it calls the common service which saves data in the database and broadcasts the message to update the View in Project "A"
However, the data is not updated in real-time when project "B" calls this service, only when a manual refresh is done in the View on project "A", or when project "A" calls the service
Any thoughts?
Kind regards

A: (Reposting my comment as an answer)

Any thoughts?

SignalR runs within a single application instance: multiple web-applications cannot both host the same SignalR instance.
But what you can do, however, is to make Project-B become a SignalR client of Project-A so they can communicate that way. If you don't need two-way comms between A and B you could just add an ASP.NET Web API action/endpoint in A for B to invoke by sending a HTTP request to A - and inside this action/endpoint you'd do something with the DI-injected IHubContext<T>.
(Use the Microsoft.AspNetCore.SignalR.Client NuGet package to allow any .NET application, even console programs and WIndows services, to be SignalR clients that can have 2-way communication with the SignalR-hosting web-application).


text:
Q: Trouble printing array of titles and urls I'm not very good at PHP.
I have a folder of .html files that will change often, and then  I want to search through the folder, parse the
 tags, and then print/echo each
 tag and its url.
Getting the
 tags out of the .html files was easy enough with some Googling, but I cannot seem to print a list of
 titles and their corresponding URL's.
Here is what I have so far:
        $url_list = glob('posts/*.html'); // Searches for all files and folders in above directory that end in .html.

        foreach ($url_list as $url) { // Creates an array of post URL's and title
 tags.
            $post = new DOMDocument(); // Creates string to load blog post.
            $post->loadHTMLFile($url); // Loads blog post into string $post from its URL.

            $h1_tags = $post->getElementsByTagName('h1'); // Finds all
 tags.
            $first_h1 = $h1_tags->item(0); // Gets value of first
 tag.
            $title = $first_h1->nodeValue; // Sets $title to value of first
 tag.

            if (!empty($title)) { // Will only run on files which have a date in their metadata.
                $post_list[$url] = $title;
                $post_list[$title] = $url;
            }
        }

        sort($post_list); // Sorts list of posts in alphabetical order.

        $num = 1;

        foreach ($post_list as $title) { //
            echo "
".($num++).". {$title} = {$url}
";
        }

A: You are adding the titles and URL's into the same list - but reversed.  If you build up your data as...
        if (!empty($title)) { // Will only run on files which have a date in their metadata.
            $post_list[$title] = $url;
        }

So this only adds it in once, and then output it like...
    foreach ($post_list as $title => $url) { //
        echo "
".($num++).". {$title} = {$url}
";
    }

Edit: change sort() to asort()


text:
Q: What is Firebase Firestore 'Reference' data type good for? I'm just exploring the new Firebase Firestore and it contains a data type called reference. It is not clear to me what this does.

*

*Is it like foreign key?

*Can it be used to point to a collection that is located somewhere else?

*If reference is an actual reference, can I use it for queries? For example can I have a reference that points directly to the user, instead of storing the userId in a text field? And can I use this user reference for querying?

A: If you don't use Reference data type, you need to update every document.
For example, you have 2 collections "categories" and "products" and you stored the category name "Fruits" in categories to every document of "Apple" and "Lemon" in products as shown below. But, if you update the category name "Fruits" in categories, you also need to update the category name "Fruits" in every document of "Apple" and "Lemon" in products:
collection | document | field

categories > 67f60ad3 > name: "Fruits"

collection | document | field

  products > 32d410a7 > name: "Apple", category: "Fruits"
             58d16c57 > name: "Lemon", category: "Fruits"

But, if you store the reference of "Fruits" in categories to every document of "Apple" and "Lemon" in products, you don't need to update every document of "Apple" and "Lemon" when  you update the category name "Fruits" in categories:
collection | document | field

  products > 32d410a7 > name: "Apple", category: categories/67f60ad3
             58d16c57 > name: "Lemon", category: categories/67f60ad3

This is the goodness of Reference data type.

A: For those looking for a Javascript solution to querying by reference - the concept is that, you need to use a 'document reference' object in the query statement
teamDbRef = db.collection('teams').doc('CnbasS9cZQ2SfvGY2r3b'); /* CnbasS9cZQ2SfvGY2r3b being the collection ID */
//
//
db.collection("squad").where('team', '==', teamDbRef).get().then((querySnapshot) => {
  //
}).catch(function(error) {
  //
});

(Kudos to the answer here: https://stackoverflow.com/a/53141199/1487867)

A: Adding below what worked for me using references in Firestore.
As the other answers say, it's like a foreign key. The reference attribute  doesn't return the data of the reference doc though. For example, I have a list of products, with a userRef reference as one of the attributes on the product. Getting the list of products, gives me the reference of the user that created that product. But it doesn't give me the details of the user in that reference. I've used other back end as a services with pointers before that have a "populate: true" flag that gives the user details back instead of just the reference id of the user, which would be great to have here (hopefully a future improvement).
Below is some example code that I used to set the reference as well as get the collection of products list then get the user details from the user reference id given.
Set a reference on a collection:
let data = {
  name: 'productName',
  size: 'medium',
  userRef: db.doc('users/' + firebase.auth().currentUser.uid)
};
db.collection('products').add(data);

Get a collection (products) and all references on each document (user details):
db.collection('products').get()
    .then(res => {
      vm.mainListItems = [];
      res.forEach(doc => {
        let newItem = doc.data();
        newItem.id = doc.id;
        if (newItem.userRef) {
          newItem.userRef.get()
          .then(res => {
            newItem.userData = res.data()
            vm.mainListItems.push(newItem);
          })
          .catch(err => console.error(err));
        } else {
          vm.mainListItems.push(newItem);
        }

      });
    })
    .catch(err => { console.error(err) });

A: References are very much like foreign keys.
The currently released SDKs cannot store references to other projects. Within a project, references can point to any other document in any other collection.
You can use references in queries like any other value: for filtering, ordering, and for paging (startAt/startAfter).
Unlike foreign keys in a SQL database, references are not useful for performing joins in a single query. You can use them for dependent lookups (which seem join like), but be careful because each hop will result in another round trip to the server.

A: According to the #AskFirebase https://youtu.be/Elg2zDVIcLo?t=276
the primary use-case for now is a link in Firebase console UI

A: A lot of answers mentioned it is just a reference to another document but does not return data for that reference but we can use it to fetch data separately.
Here is an example of how you could use it in the firebase JavaScript SDK 9, modular version.
let's assume your firestore have a collection called products and it contains the following document.
{
  name: 'productName',
  size: 'medium',
  userRef: 'user/dfjalskerijfs'
}

here users have a reference to a document in the users collection. we can use the following code segment to get the product and then retrieve the user from the reference.
import { collection, getDocs, getDoc, query, where } from "firebase/firestore";
import { db } from "./main"; // firestore db object

let productsWithUser = []
const querySnaphot = await getDocs(collection(db, 'products'));
querySnapshot.forEach(async (doc) => {
  let newItem = {id: doc.id, ...doc.data()};
  if(newItem.userRef) {
    let userData = await getDoc(newItem.userRef);
    if(userData.exists()) {
      newItem.userData = {userID: userData.id, ...userData.data()}
    }
    productwithUser.push(newItem);
  } else {
    productwithUser.push(newItem);
  }
});

here collection, getDocs, getDoc, query, where are firestore related modules we can use to get data whenever necessary. we use user reference returned from the products document directly to fetch the user document for that reference using the following code,
let userData = await getDoc(newItem.userRef);

to read more on how to use modular ver SDK refer to official documentation to learn more.

A: Belatedly, there are two advantages from this blog:

if I expect that I'll want to order restaurant reviews by rating, or publish date, or most upvotes, I can do that within a reviews subcollection without needing a composite index. In the larger top level collection, I'd need to create a separate composite index for each one of those, and I also have a limit of 200 composite indexes.

I wouldn't have 200 composite indices but there are some constraints.

Also, from a security rules standpoint, it's fairly common to restrict child documents based on some data that exists in their parent, and that's significantly easier to do when you have data set up in subcollections.

One example would be restricting to insert a child collection if the user doesn't have the privilege in the parent's field.

A: UPDATE 12/18/22 - I put this in a package.
Original Blog Post
What this package does is use RXJS to loop through each field in a document. If that document type is a Reference type, then it grabs that  foreign document type. The collection version grabs the foreign key value for each reference field in all documents in your collection. You can also input the fields manually that you wish to parse to speed up the searching (see my post). This is definitely not as efficient as doing manual aggregations with Firebase Functions, as you will get charged for lots of reads for each document you read, but it could come in handy for people that want a quick way to join data on the frontend.
This could also come in handy if you cache data and really only need to do this once.
J
install
npm i j-firebase

import
import { expandRef, expandRefs } from 'j-firebase';

https://github.com/jdgamble555/j-firebase

Original Post

Automatic JOINS:
DOC
expandRef<T>(obs: Observable<T>, fields: any[] = []): Observable<T> {
  return obs.pipe(
    switchMap((doc: any) => doc ? combineLatest(
      (fields.length === 0 ? Object.keys(doc).filter(
        (k: any) => {
          const p = doc[k] instanceof DocumentReference;
          if (p) fields.push(k);
          return p;
        }
      ) : fields).map((f: any) => docData<any>(doc[f]))
    ).pipe(
      map((r: any) => fields.reduce(
        (prev: any, curr: any) =>
          ({ ...prev, [curr]: r.shift() })
        , doc)
      )
    ) : of(doc))
  );
}

COLLECTION
expandRefs<T>(
  obs: Observable<T[]>,
  fields: any[] = []
): Observable<T[]> {
  return obs.pipe(
    switchMap((col: any[]) =>
      col.length !== 0 ? combineLatest(col.map((doc: any) =>
        (fields.length === 0 ? Object.keys(doc).filter(
          (k: any) => {
            const p = doc[k] instanceof DocumentReference;
            if (p) fields.push(k);
            return p;
          }
        ) : fields).map((f: any) => docData<any>(doc[f]))
      ).reduce((acc: any, val: any) => [].concat(acc, val)))
        .pipe(
          map((h: any) =>
            col.map((doc2: any) =>
              fields.reduce(
                (prev: any, curr: any) =>
                  ({ ...prev, [curr]: h.shift() })
                , doc2
              )
            )
          )
        ) : of(col)
    )
  );
}

Simply put this function around your observable and it will automatically expand all reference data types providing automatic joins.
Usage
this.posts = expandRefs(
  collectionData(
    query(
      collection(this.afs, 'posts'),
      where('published', '==', true),
      orderBy(fieldSort)
    ), { idField: 'id' }
  )
);

Note: You can also now input the fields you want to expand as a second argument in an array.
['imageDoc', 'authorDoc']
This will increase the speed!
Add .pipe(take(1)).toPromise(); at the end for a promise version!
See here for more info. Works in Firebase 8 or 9!
Simple!
J

A: 2022 UPDATE
let coursesArray = [];
const coursesCollection = async () => {
    const queryCourse = query(
        collection(db, "course"),
        where("status", "==", "active")
    )
    onSnapshot(queryCourse, (querySnapshot) => {
        querySnapshot.forEach(async (courseDoc) => {

            if (courseDoc.data().userId) {
                const userRef = courseDoc.data().userId;
                getDoc(userRef)
                    .then((res) => {
                        console.log(res.data());
                    })
            }
            coursesArray.push(courseDoc.data());
        });
        setCourses(coursesArray);
    });
}


text:
Q: How to setup domains reselling store front (website) I am Softlayer domains reseller (resellone.net)
I intend to setup my own website for selling domains that must have facilities:

*

*Search domains availability

*Register domains

*Billing

*Update prices if required

*My own graphic design (Header & Footer)

Best regards

A: The SoftLayer API provides direct control over every aspect of SoftLayer services, as well as your SoftLayer customer account.
It means that support for Domains and Billing information is available.
Regarding updating prices and setting up your own graphic design is a job that should be done by yourself.
These are some links that could help you with your requirements.
http://sldn.softlayer.com/
http://sldn.softlayer.com/reference/services/SoftLayer_Dns_Domain
Nevertheless, you could submit a ticket to SoftLayer, so that they might provide you further assistance.


text:
Q: Check if activation_code is not activeted at login. "ONLY" activation_code This is the code I use at login:
            $q = $lacz->query("SELECT email, pass, activation_code
                                    FROM users
                                    WHERE  email='". $nazwa_uz_l ."'
                                    AND pass = '". $haslo_l ."'
                                    AND activation_code IS NULL ");

        if($q->num_rows>0) {
            $_SESSION['prawid_uzyt'] = $nazwa_uz_l; }
        else
        {
            echo 'Pass or Log are wrong, or activation code is not confirmed (check email).';
            exit;
        }

In this query I check for all 3 things: email, password and activation code, and then output an error. What I want to do is to output an first error when Pass or Log are wrong and second error (something like elseif) when activation code IS not NULL. I tried else if and two queries, but I was getting the errors. Can You help me? I check the answers and give points, thanks.

A: Don't check the activation code in the query. Just get the user information, along with the activation code field:
SELECT email, pass, activation_code
..
WHERE email='foo' and pass='bar'

Then you can test the individual conditions in your code:
if (number_of_rows == 0) {
   ... bad username/password
} else if ($activation_code == '') {
   ... code is blank/null
}

A: If you remove the AND activation_code IS NULL from the query's WHERE clause, you'll be able to pull data for a user matching the given email/password. Then, with that, you'll be able to determine if the user exists, or if their activation code is empty:
$q = $lacz->query("SELECT email, pass, activation_code
        FROM users
        WHERE  email='". $nazwa_uz_l ."'
        AND pass = '". $haslo_l ."'");

if ($q->num_rows === 0) {
    echo 'Password or email address are wrong.';
    exit;
} else {
    $row = $result->fetch_assoc();
    if (empty($row['activation_code'])) {
        echo 'Activation code is not confirmed.';
        exit;
    } else {
        $_SESSION['prawid_uzyt'] = $nazwa_uz_l;
    }
}

Side-note (not answer related): I highly suggest using a parameterized query instead of directly inserting the values into the SQL; if you prefer the current way, make sure you're sanitizing the input first to prevent SQL Injection.

A: Remove "AND activation_code IS NULL" from your query and do something like
if($q->num_rows>0)
{
  $row = $q->fetch_assoc();
  if(!is_null($row['activation_code']))
  {
    $_SESSION['prawid_uzyt'] = $nazwa_uz_l;
  }
  else
  {
    echo 'Activation code is not confirmed (check email).';
    exit;
  }
}
else
{
  echo 'Pass or Log are wrong.';
  exit;
}


text:
Q: Diferença entre datas/horas em Python Estou precisando calcular a diferença entre duas datas em python, mas sempre da algum erro.
>>> from datetime import datetime
>>> data1 = datetime(2015, 8, 5, 8, 12, 23)
>>> data2 = datetime(2015, 8, 9, 6, 13, 23)
>>> difdata = data2 - data1
>>> '{0}:{2}'.format(*str(difdata).split())
'3:22:01:00'

quero fazer assim, mas quando tento abrir em outros sistemas da erro, quero criar um timestamp com as datas mas não estou conseguindo.

A: Quando você subtrai datas no formato datetime é retornado um objeto timedelta que tem um método total_seconds() que te dá os segundos totais:
from datetime import datetime
s = '2015/08/05 08:12:23'
t = '2015/08/09 08:13:23'
f = '%Y/%m/%d %H:%M:%S'
dif = (datetime.strptime(t, f) - datetime.strptime(s, f)).total_seconds()
print(dif)

A: Achei uma solução pesquisando a função DATETIME
s = '2015/08/05 08:12:23'
t = '2015/08/09 08:13:23'

date1 = int(datetime.datetime.strptime(s, '%d/%m/%Y %H:%M:%S').strftime("%s"))
date2 = int(datetime.datetime.strptime(t, '%d/%m/%Y %H:%M:%S').strftime("%s"))

difdate = date2 - date1

print(difdate)

Assim fica fácil transformar e calcular qualquer diferença.

A: Outra forma interessante de resolver esta questão é utilizando a biblioteca dateutil.
Dessa forma podemos implementar o seguinte código:
from datetime import datetime
from dateutil.relativedelta import relativedelta

a = "2015-08-05 08:12:23"
b = "2015-08-09 08:12:23"
f = "%Y-%m-%d %H:%M:%S"

ini = datetime.strptime(a, f)
fim = datetime.strptime(b, f)

di = abs(relativedelta(ini, fim))

print(f'{di.years} anos, {di.months} meses, {di.days} dias, {di.hours} horas, '
      f'{di.minutes} minutos e {di.seconds} segundos.')

Observe que o código recebe duas datas e horas no tipo string, as converte em  objetos datetime, e depois - com ajuda do método relativedelta - calcula a diferença.
Observe também que o resultado deste método consiste em uma tupla, com a qual podemos, posteriormente, recuperar cada um de seus elementos.
O resultado do print() nada mais é do que os valores de cada elemento da tupla gerada anteriormente.


text:
Q: How to insert Ajax Passed image as Blob In Mysql Using Mysqli(PHP) I am trying to upload image using ajax on client side and on server side i am using PHP. The Problem i am facing is, i am unable to save the image in Mysql database table as a blob using PHP. I am unable to define Receive function of image.
I need help on how to define receive function and save blob image in database column.
am i missing something in my PHP code below ??
Java Script:

HTML:
    <form id="uploadForm" action="" method="post">

    Upload Image File:

    <input name="userImage" type="file" class="inputFile" />
    <input type="submit" value="Submit" class="btnSubmit" />
    </form>

PHP:
$db = mysqli_connect("xxxx","xxx","xxx","xxx");

$image = addslashes(is_uploaded_file($_FILES['userImage']['tmp_name']));

    $query = "INSERT INTO images (id,image) VALUES('','$image')";

    $qry = mysqli_query($db, $query);

A: Try this...
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Add 'enctype="multipart/form-data"' in your form
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">

 $query = "INSERT INTO images (id,image) VALUES('','" . mysql_escape_string(file_get_contents($image)) . "')";

A: // Detect if POST
if($_SERVER["REQUEST_METHOD"] == "POST"){
  // Check $_FILES array
  if(isset($_FILES["inputFile"])){

    // Find location of uploaded file
    $tmpName = $_FILES["inputFile"]["tmp_name"];

    // Read data
    $fileHandle = fopen($tmpName, "r");
    $image = fread($fileHandle, filesize($tmpName));
    fclose($fileHandle);

    // Run query
    $db = mysqli_connect("xxxx","xxx","xxx","xxx");
    $query = "INSERT INTO images (id,image) VALUES('','$image')";
    $qry = mysqli_query($db, $query);
  }
}

Please remember to add your own security regarding file size and type. Here is the PHP file upload documentation.
Also, not sure why you pass an empty string into the id column in your table. If this field has auto_increment (such as with the SERIAL data type), then you can just leave that field blank in the SQL:
INSERT INTO images (image) VALUES('$image');


text:
Q: How to use raw query in join clause in laravel5? I am using multiple condition in join clause in laravel5 and there is one condition that is passed as a raw condition. How to pass it ?
I am getting this error
Call to undefined method Illuminate\Database\Query\JoinClause::whereRaw()
Code is
->leftjoin('log_simple_calory as LC',
function($join)use($tz_lccreated_date,$dateRange){
  $join->on('LC.user_id_fk','=','UA.user_id_fk');
  $join->on('LC.is_active','=',DB::raw('1'))
  ->whereRaw('date('.$tz_lccreated_date.')'. $dateRange);
})

A: The whereRaw should be outside the JoinClause :
->leftjoin('log_simple_calory as LC',
function($join)use($tz_lccreated_date,$dateRange){
  $join->on('LC.user_id_fk','=','UA.user_id_fk');
  $join->on('LC.is_active','=',DB::raw('1'))
})->whereRaw('date('.$tz_lccreated_date.')'. $dateRange);

A: If you are using laravel 5 and above, this site is very useful,
for writing raw queries and stuff
https://laravel.com/docs/5.4/queries


text:
Q: Number of spanning trees in $K_9$ with the degree of vertex $1$ being $4$ I believe I've gotten this problem, but I'm not sure whether I'm correct, because my familiarity with Prufer codes is very weak. I would appreciate any corrections / comments on the mistakes I've made. Thanks!
The problem is as stated in the title: Imagine $K_9$, with the restriction that vertex $1$ has degree $4$.
$ $
Then in the Prufer code for each spanning tree, there must be exactly three $1$'s, because the degree of each vertex is equal to the number of times the vertex's index appears in a Prufer code, plus one.
This leaves the remaining $4$ elements to be picked from the set $\{2,3,4,5,6,7,8,9\}$, with any number of repetitions and/or counts allowed.
So we first order the values: There are ${7 \choose 3}$ ways to order the three values that are $1$. There are $4^8$ ways to pick the remaining $4$ elements. So there are a total of ${7 \choose 3} 2^{16}$ spanning trees satisfying the given restriction.

A: According to Prüfers method you want the lists of length $9-2$ with the numbers $1$ through $9$ that contain the number $1$ three times. There are $\binom{7}{3}$ ways to select the spaces with the number $1$ and then $8^4$ ways to fill in the remaining numbers. So the answer is $\binom{7}{3}8^4$


text:
Q: SQL Query Balance I have query like this one...
+-----+------------+--------+---------+---------+
| seq | fld_Date   | CBU_IN | CBU_OUT | Balance |
+-----+------------+--------+---------+---------+
|  41 | 2012-10-08 | 150.00 | 0.00    | 150.00  |
|  42 | 2012-10-15 | 50.00  | 0.00    | 200.00  |
|  43 | 2012-10-22 | 50.00  | 0.00    | 250.00  |
|  44 | 2012-10-29 | 50.00  | 0.00    | 300.00  |
|  45 | 2012-11-05 | 50.00  | 0.00    | 350.00  |
|  46 | 2012-11-12 | 50.00  | 0.00    | 400.00  |
|  47 | 2012-11-19 | 50.00  | 0.00    | 450.00  |
+-----+------------+--------+---------+---------+

all I wanted is this kind of output where in the next row date are from the next row of fld_Date .
+-----+------------+---------------+--------+---------+---------+
| seq | fld_Date   | next_row_date | CBU_IN | CBU_OUT | Balance |
+-----+------------+---------------+--------+---------+---------+
|  41 | 2012-10-08 | 2012-10-15    | 150.00 | 0.00    | 150.00  |
|  42 | 2012-10-15 | 2012-10-22    | 50.00  | 0.00    | 200.00  |
|  43 | 2012-10-22 | 2012-10-25    | 50.00  | 0.00    | 250.00  |
|  44 | 2012-10-25 | 2012-11-05    | 50.00  | 0.00    | 300.00  |
|  45 | 2012-11-05 | 2012-11-12    | 50.00  | 0.00    | 350.00  |
|  46 | 2012-11-12 | 2012-11-16    | 50.00  | 0.00    | 400.00  |
|  47 | 2012-11-16 | 2012-11-26    | 50.00  | 0.00    | 450.00  |
+-----+------------+---------------+--------+---------+---------+

Can you help me with this one... Thanks...
here's my query...
 SELECT
        lms_savings.seq,
        lms_savings.fld_Date,
        FORMAT(lms_savings.CBU,2)AS CBU_IN,
        FORMAT(lms_savings.CBU_OUT,2)AS CBU_OUT,
    FORMAT(@Balance := @Balance + lms_savings.CBU - lms_savings.CBU_OUT,2) AS Balance
FROM lms_savings, (SELECT @Balance := 0) AS variableInit

A: put your query in place of "your query"
 select a.seq, a.fld_Date,b.fld_Date as next_row_date,
        a.CBU_IN,a.CBU_OUT,a.Balance
 from ( your query ) a left outer join (your query) b
 on a.seq = b.seq-1

A: select a.seq, a.fld_Date, b.fld_Date as next_row_date , a.CBU_IN, a.CBU_OUT, a.Balance
from table_name a, table_name b
where a.seq = b.seq+1


text:
Q: How to dynamically add / remove periodic tasks to Celery (celerybeat) If I have a function defined as follows:
def add(x,y):
  return x+y

Is there a way to dynamically add this function as a celery PeriodicTask and kick it off at runtime? I'd like to be able to do something like (pseudocode):
some_unique_task_id = celery.beat.schedule_task(add, run_every=crontab(minute="*/30"))
celery.beat.start(some_unique_task_id)

I would also want to stop or remove that task dynamically with something like (pseudocode):
celery.beat.remove_task(some_unique_task_id)

or
celery.beat.stop(some_unique_task_id)

FYI I am not using djcelery, which lets you manage periodic tasks via the django admin.

A: There is a library called django-celery-beat which provides the models one needs. To make it dynamically load new periodic tasks one has to create its own Scheduler.
from django_celery_beat.schedulers import DatabaseScheduler

class AutoUpdateScheduler(DatabaseScheduler):

    def tick(self, *args, **kwargs):
        if self.schedule_changed():
            print('resetting heap')
            self.sync()
            self._heap = None
            new_schedule = self.all_as_schedule()

            if new_schedule:
                to_add = new_schedule.keys() - self.schedule.keys()
                to_remove = self.schedule.keys() - new_schedule.keys()
                for key in to_add:
                    self.schedule[key] = new_schedule[key]
                for key in to_remove:
                    del self.schedule[key]

        super(AutoUpdateScheduler, self).tick(*args, **kwargs)

    @property
    def schedule(self):
        if not self._initial_read and not self._schedule:
            self._initial_read = True
            self._schedule = self.all_as_schedule()

        return self._schedule

A: This question was answered on google groups.
I AM NOT THE AUTHOR, all credit goes to Jean Mark

Here's a proper solution for this. Confirmed working, In my scenario,
  I sub-classed Periodic Task and created a model out of it since I can
  add other fields to the model as I need and also so I could add the
  "terminate" method. You have to set the periodic task's enabled
  property to False and save it before you delete it. The whole
  subclassing is not a must, the schedule_every method is the one that
  really does the work. When you're ready to terminate you task (if you
  didn't subclass it) you can just use
  PeriodicTask.objects.filter(name=...) to search for your task, disable
  it, then delete it.
Hope this helps!
from djcelery.models import PeriodicTask, IntervalSchedule
from datetime import datetime

class TaskScheduler(models.Model):

    periodic_task = models.ForeignKey(PeriodicTask)

    @staticmethod
    def schedule_every(task_name, period, every, args=None, kwargs=None):
    """ schedules a task by name every "every" "period". So an example call would be:
         TaskScheduler('mycustomtask', 'seconds', 30, [1,2,3])
         that would schedule your custom task to run every 30 seconds with the arguments 1,2 and 3 passed to the actual task.
    """
        permissible_periods = ['days', 'hours', 'minutes', 'seconds']
        if period not in permissible_periods:
            raise Exception('Invalid period specified')
        # create the periodic task and the interval
        ptask_name = "%s_%s" % (task_name, datetime.datetime.now()) # create some name for the period task
        interval_schedules = IntervalSchedule.objects.filter(period=period, every=every)
        if interval_schedules: # just check if interval schedules exist like that already and reuse em
            interval_schedule = interval_schedules[0]
        else: # create a brand new interval schedule
            interval_schedule = IntervalSchedule()
            interval_schedule.every = every # should check to make sure this is a positive int
            interval_schedule.period = period
            interval_schedule.save()
        ptask = PeriodicTask(name=ptask_name, task=task_name, interval=interval_schedule)
        if args:
            ptask.args = args
        if kwargs:
            ptask.kwargs = kwargs
        ptask.save()
        return TaskScheduler.objects.create(periodic_task=ptask)

    def stop(self):
        """pauses the task"""
        ptask = self.periodic_task
        ptask.enabled = False
        ptask.save()

    def start(self):
        """starts the task"""
        ptask = self.periodic_task
        ptask.enabled = True
        ptask.save()

    def terminate(self):
        self.stop()
        ptask = self.periodic_task
        self.delete()
        ptask.delete()

A: You can check out this flask-djcelery which configures flask and djcelery and also provides browseable rest api

A: The answer from @asksol is what's needed if in a Django application.
For non-django applications, you can use celery-sqlalchemy-scheduler which is modeled like django-celery-beat for Django since it also uses database instead of the file celerybeat-schedule.

*

*https://pypi.org/project/celery-sqlalchemy-scheduler/

*https://github.com/AngelLiang/celery-sqlalchemy-scheduler
Here is an example with runtime addition of a new task.
tasks.py
from celery import Celery

celery = Celery('tasks')

beat_dburi = 'sqlite:///schedule.db'

celery.conf.update(
    {'beat_dburi': beat_dburi}
)

@celery.task
def my_task(arg1, arg2, be_careful):
    print(f"{arg1} {arg2} be_careful {be_careful}")

Logs (Producer)
$ celery --app=tasks beat --scheduler=celery_sqlalchemy_scheduler.schedulers:DatabaseScheduler --loglevel=INFO
celery beat v5.1.2 (sun-harmonics) is starting.
[2021-08-20 15:20:20,927: INFO/MainProcess] beat: Starting...

Logs (Consumer)
$ celery --app=tasks worker --queues=celery --loglevel=INFO
-------------- celery@ubuntu20 v5.1.2 (sun-harmonics)
[2021-08-20 15:20:02,287: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672//

Database schedules
$ sqlite3 schedule.db
sqlite> .databases
main: /home/nponcian/Documents/Program/1/db/schedule.db
sqlite> .tables
celery_crontab_schedule       celery_periodic_task_changed
celery_interval_schedule      celery_solar_schedule
celery_periodic_task
sqlite> select * from celery_periodic_task;
1|celery.backend_cleanup|celery.backend_cleanup||1||[]|{}|||||2021-08-20 19:20:20.955246|0||1||0|2021-08-20 07:20:20|

Now, while those workers are already running, let's update the schedules by adding a new scheduled task. Note that this is at runtime, without the need to restart the workers.
$ python3
>>> # Setup the session.
>>> from celery_sqlalchemy_scheduler.models import PeriodicTask, IntervalSchedule
>>> from celery_sqlalchemy_scheduler.session import SessionManager
>>> from tasks import beat_dburi
>>> session_manager = SessionManager()
>>> engine, Session = session_manager.create_session(beat_dburi)
>>> session = Session()
>>>
>>> # Setup the schedule (executes every 10 seconds).
>>> schedule = session.query(IntervalSchedule).filter_by(every=10, period=IntervalSchedule.SECONDS).first()
>>> if not schedule:
...     schedule = IntervalSchedule(every=10, period=IntervalSchedule.SECONDS)
...     session.add(schedule)
...     session.commit()
...
>>>
>>> # Create the periodic task
>>> import json
>>> periodic_task = PeriodicTask(
...     interval=schedule,                  # we created this above.
...     name='My task',                     # simply describes this periodic task.
...     task='tasks.my_task',               # name of task.
...     args=json.dumps(['arg1', 'arg2']),
...     kwargs=json.dumps({
...        'be_careful': True,
...     }),
... )
>>> session.add(periodic_task)
>>> session.commit()

Database schedules (updated)

*

*We can now see that the newly added schedule has reflected to the database which is continuously read by the celery beat scheduler. So should there be any updates with the values of the args or kwargs, we can easily perform SQL updates on the database and it should reflect in realtime with the running workers (without the need of restart).

sqlite> select * from celery_periodic_task;
1|celery.backend_cleanup|celery.backend_cleanup||1||[]|{}|||||2021-08-20 19:20:20.955246|0||1||0|2021-08-20 07:20:20|
2|My task|tasks.my_task|1|||["arg1", "arg2"]|{"be_careful": true}||||||0||1||0|2021-08-20 07:26:49|

Logs (Producer)

*

*Now, the new task is being enqueued every 10 seconds

[2021-08-20 15:26:51,768: INFO/MainProcess] DatabaseScheduler: Schedule changed.
[2021-08-20 15:26:51,768: INFO/MainProcess] Writing entries...
[2021-08-20 15:27:01,789: INFO/MainProcess] Scheduler: Sending due task My task (tasks.my_task)
[2021-08-20 15:27:11,776: INFO/MainProcess] Scheduler: Sending due task My task (tasks.my_task)
[2021-08-20 15:27:21,791: INFO/MainProcess] Scheduler: Sending due task My task (tasks.my_task)

Logs (Consumer)

*

*The newly added task is correctly executed on time every 10 seconds

[2021-08-20 15:27:01,797: INFO/MainProcess] Task tasks.my_task[04dcb40c-0a77-437b-a129-57eb52850a51] received
[2021-08-20 15:27:01,798: WARNING/ForkPoolWorker-4] arg1 arg2 be_careful True
[2021-08-20 15:27:01,799: WARNING/ForkPoolWorker-4]

[2021-08-20 15:27:01,799: INFO/ForkPoolWorker-4] Task tasks.my_task[04dcb40c-0a77-437b-a129-57eb52850a51] succeeded in 0.000763321000704309s: None
[2021-08-20 15:27:11,783: INFO/MainProcess] Task tasks.my_task[e8370a6b-085f-4bd5-b7ad-8f85f4b61908] received
[2021-08-20 15:27:11,786: WARNING/ForkPoolWorker-4] arg1 arg2 be_careful True
[2021-08-20 15:27:11,786: WARNING/ForkPoolWorker-4]

[2021-08-20 15:27:11,787: INFO/ForkPoolWorker-4] Task tasks.my_task[e8370a6b-085f-4bd5-b7ad-8f85f4b61908] succeeded in 0.0006725780003762338s: None
[2021-08-20 15:27:21,797: INFO/MainProcess] Task tasks.my_task[c14d875d-7f6c-45c2-a76b-4e9483273185] received
[2021-08-20 15:27:21,799: WARNING/ForkPoolWorker-4] arg1 arg2 be_careful True
[2021-08-20 15:27:21,799: WARNING/ForkPoolWorker-4]

[2021-08-20 15:27:21,800: INFO/ForkPoolWorker-4] Task tasks.my_task[c14d875d-7f6c-45c2-a76b-4e9483273185] succeeded in 0.0006371149993356084s: None

A: This was finally made possible by a fix included in celery v4.1.0. Now, you just need to change the schedule entries in the database backend, and celery-beat will act according to the new schedule.
The docs vaguely describe how this works. The default scheduler for celery-beat, PersistentScheduler, uses a shelve file as its schedule database. Any changes to the beat_schedule dictionary in the PersistentScheduler instance are synced with this database (by default, every 3 minutes), and vice-versa. The docs describe how to add new entries to the beat_schedule using app.add_periodic_task. To modify an existing entry, just add a new entry with the same name. Delete an entry as you would from a dictionary: del app.conf.beat_schedule['name'].
Suppose you want to monitor and modify your celery beat schedule using an external app. Then you have several options:

*

*You can open the shelve database file and read its contents like a dictionary. Write back to this file for modifications.

*You can run another instance of the Celery app, and use that one to modify the shelve file as described above.

*You can use the custom scheduler class from django-celery-beat to store the schedule in a django-managed database, and access the entries there.

*You can use the scheduler from celerybeat-mongo to store the schedule in a MongoDB backend, and access the entries there.

A: No, I'm sorry, this is not possible with the regular celerybeat.
But it's easily extensible to do what you want, e.g. the django-celery
scheduler is just a subclass reading and writing the schedule to the database
(with some optimizations on top).
Also you can use the django-celery scheduler even for non-Django projects.
Something like this:

*

*Install django + django-celery:
$ pip install -U django django-celery

*Add the following settings to your celeryconfig:
DATABASES = {
    'default': {
        'NAME': 'celerybeat.db',
        'ENGINE': 'django.db.backends.sqlite3',
    },
}
INSTALLED_APPS = ('djcelery', )

*Create the database tables:
$ PYTHONPATH=. django-admin.py syncdb --settings=celeryconfig

*Start celerybeat with the database scheduler:
$ PYTHONPATH=. django-admin.py celerybeat --settings=celeryconfig \
    -S djcelery.schedulers.DatabaseScheduler

Also there's the djcelerymon command which can be used for non-Django projects
to start celerycam and a Django Admin webserver in the same process, you can
use that to also edit your periodic tasks in a nice web interface:
   $ djcelerymon

(Note for some reason djcelerymon can't be stopped using Ctrl+C, you
have to use Ctrl+Z + kill %1)

A: I was looking for the same solution for Celery + Redis that can be flexible add/remove. Check out this one, redbeat, same guy from Heroku, even they put as well the Redis + Sentinel.
Hope helps :)

A: Celery can realize the dynamic periodic task with databases and calling itself.
But APSchedule is better.
Because dynamic periodic task always means long countdown or eta. Too many of these periodic tasks can take up a lot of memory, making it time-consuming to restart and execute non-delayed tasks.
tasks.py
import sqlite3
from celery import Celery
from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)

app = Celery(
    'tasks',
    broker='redis://localhost:6379/0',
    backend='redis://localhost:6379/1',
    imports=['tasks'],
)

conn = sqlite3.connect('database.db', check_same_thread=False)
c = conn.cursor()
sql = '''
CREATE TABLE IF NOT EXISTS `tasks`
(
   `id` INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT,
   `name` TEXT,
   `countdown` INTEGER
);
'''
c.execute(sql)

def create(name='job', countdown=5):
    sql = 'INSERT INTO `tasks` (`name`, `countdown`) VALUES (?, ?)'
    c.execute(sql, (name, countdown))
    conn.commit()
    return c.lastrowid

def read(id=None, verbose=False):
    sql = 'SELECT * FROM `tasks` '
    if id:
        sql = 'SELECT * FROM `tasks` WHERE `id`={}'.format(id)
    all_rows = c.execute(sql).fetchall()
    if verbose:
        print(all_rows)
    return all_rows

def update(id, countdown):
    sql = 'UPDATE `tasks` SET `countdown`=? WHERE `id`=?'
    c.execute(sql, (countdown, id))
    conn.commit()

def delete(id, verbose=False):
    sql = 'DELETE FROM `tasks` WHERE `id`=?'
    affected_rows = c.execute(sql, (id,)).rowcount
    if verbose:
        print('deleted {} rows'.format(affected_rows))
    conn.commit()

@app.task
def job(id):
    id = read(id)
    if id:
        id, name, countdown = id[0]
    else:
        logger.info('stop')
        return

    logger.warning('id={}'.format(id))
    logger.warning('name={}'.format(name))
    logger.warning('countdown={}'.format(countdown))

    job.apply_async(args=(id,), countdown=countdown)

main.py
from tasks import *

id = create(name='job', countdown=5)
job(id)
# job.apply_async((id,), countdown=5)  # wait 5s

print(read())

input('enter to update')
update(id, countdown=1)

input('enter to delete')
delete(id, verbose=True)

A: Some time ago I needed to dynamically update periodic tasks in Celery and Django, and I wrote an article about my approach (code for article).
I was using django-celery-beat package. It provides database models for PeriodicTask and IntervalSchedule. By manipulating PeriodicTask objects, you can add/remove/update/pause periodic tasks in Celery.
Create periodic task
from django_celery_beat.models import IntervalSchedule, PeriodicTask

schedule, created = IntervalSchedule.objects.get_or_create(
    every=instance.interval,
    period=IntervalSchedule.SECONDS,
)

task = PeriodicTask.objects.create(
    interval=schedule,
    name=f"Monitor: {instance.endpoint}",
    task="monitors.tasks.task_monitor",
    kwargs=json.dumps(
        {
            "monitor_id": instance.id,
        }
    ),
)

Remove periodic task
PeriodicTask.objects.get(pk=task_id).delete()

Change interval in a periodic task
task = PeriodicTask.objects.get(pk=your_id)
schedule, created = IntervalSchedule.objects.get_or_create(
    every=new_interval,
    period=IntervalSchedule.SECONDS,
)
task.interval = schedule
task.save()

Pause periodic task
task = PeriodicTask.objects.get(pk=your_id)
task.enabled = false
task.save()

Beat service
When using django-celery-beat you need to pass scheduler argument when starting beat service:
celery -A backend beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler --max-interval 10