text:
Q: resizing bootstrap accordion I have a section of a site that uses an h2, followed by an accordion. I am trying to have the accordion and h2 pull-left, however the accordion is the wrong size, unless it is expanded in which it enlarges itself. I have a sidebar column set up as so:

thus I want the h2, and accordion to be to the right of that but take up the full screen on the right of that. My accordion and h2 is set up as follows:

Action Strategies: What We Can Do Now

with each panel like so:

      Teachers and Support Staff

A: As I understood your problem, pull-right is causing it. Please see the attached snippets if this is was you need.

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Sidebar

Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro esse officiis ipsa, placeat praesentium laborum rerum iste aspernatur omnis ratione exercitationem eligendi. Soluta id ipsa nisi ex! Cumque, voluptatum laudantium hic, ea cum, vitae aperiam expedita delectus autem iusto nam voluptatem dolorum fugiat? Laudantium minima, eos eius harum voluptatem error!

Action Strategies: What We Can Do Now

                    Teachers and Support Staff 1

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos architecto atque nemo nisi explicabo dolor. Magni perferendis modi vero pariatur officia consectetur, vitae id. Aspernatur officia nam ipsum ea dolorum laborum error maxime quidem provident rerum facere eum, unde? Ducimus quos provident adipisci, odit porro itaque eligendi beatae obcaecati tenetur minima officiis libero, nesciunt quidem autem ex cupiditate ratione veniam repellat est consequuntur quibusdam aut suscipit at. Provident quod, dolor quae incidunt vitae non neque, molestiae minus veritatis deleniti eligendi laboriosam blanditiis nostrum eum quia qui voluptas nemo expedita aliquam dolorum nihil. Quas dolor neque voluptatibus quos optio reprehenderit, impedit?

                    Teachers and Support Staff 2

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui ex laboriosam libero suscipit natus, voluptatibus, perferendis eos omnis impedit minima fugit a ipsum ipsa rem numquam placeat provident magnam asperiores mollitia vero magni laudantium pariatur. Obcaecati error rem dolor itaque quidem eligendi, voluptas vero voluptatem, labore adipisci perferendis quia velit reiciendis illo libero optio. Aliquam autem labore voluptas veritatis praesentium, in a tempore accusamus error ad laboriosam omnis consequuntur, pariatur dolor voluptates dolores vel. Repellat animi tenetur expedita nobis est a natus hic adipisci eligendi aliquam quo minus, dolorum nihil provident odit delectus suscipit omnis nostrum quod magni, voluptatum. Laboriosam!

                    Teachers and Support Staff 3

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati, voluptatem, itaque cumque dolorem dicta eveniet porro voluptatibus unde ad nostrum est accusantium veniam, iste natus incidunt quis consectetur quod placeat deserunt corporis veritatis quidem! Eaque facilis quasi, rem reiciendis! Voluptatibus quasi, necessitatibus repellendus impedit, fugit minima vero eius, perferendis dignissimos vel nulla velit! Error commodi veniam maxime reprehenderit aut sint voluptatem id culpa autem corrupti optio expedita blanditiis odit dolorem obcaecati vitae delectus ea necessitatibus beatae laboriosam aliquid, eos eveniet nobis quos quidem? Quia itaque dicta quasi perferendis earum, fuga illo aperiam architecto nisi iure suscipit omnis esse facilis, saepe.


text:
Q: How can I run my python script in the background on a schedule? I have a small python script that creates a graph of data pulled from MySQL. I'm trying to figure out a way to run the script in the background all time on a regular basis. I've tried a number of things:

*

*A Cron Job that runs the script

*A loop timer

*Using the & command to run the script in the background

These all have there pluses and minuses:

*

*The Cron Job running more then every half hour seems to eat up more resources then it's worth.

*The Loop timer put into the script doesn't actually put the script in the background it just keeps it running.

*The Linux & command backgrounds the process but unlike a real Linux service I can't restart/stop it without killing it.

Can someone point me to a way to get the best out of all of these methods?

A: The cron job is probably a good approach in general, as the shell approach requires manual intervention to start it.
A couple of suggestions:
You could use a lock file to ensure that the cron job only ever starts one instance of the python script - often problems occur when using cron for larger jobs because it starts a second instance before the first instance has actually finished. You can do this simply by checking whether the lock file exists, then, if it does not, 'touch'ing the file at the beginning of the script and 'rm'ing it as your last action at the end of the script. If the lock file exists -- simply exit the script, as there is already one instance running. (Of course, if the script dies you will have to delete the lock file before running the script again).
Also, if excessive resource use is a problem, you can ensure that the script does not eat too many resources by giving it a low priority (prefix with, for example, nice -n 19).

A: Why don't you try to make your script into a proper daemon. This link is a good place to start.
import os
import subprocess
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/your-pid-name.pid'
        self.pidfile_timeout = 5
    def run(self):

        try:
            while True:

                ### PUT YOUR SCRIPT HERE ###

                time.sleep(300)

        except Exception, e:
            raise

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

You can start/stop/restart this script just like any other linux service.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does shift operators affect unsigned numbers Suppose x is unsigned int
Then is x << n equal to x * 2n
I know it's true for signed integers.
Is x * 15 equal to x << 4 - x?

A: This answer is for the C language. There seems to be subtle differences in the C++ specification for this particular question.
If x is unsigned and if n >= 0 and less than the number of value bits in the type of x, x << n is indeed the same as multiplying x by the n-th power of 2.
If this computation overflows, the result will reduced modulo the largest value for the type of x plus 1.
If x is signed, it must be non-negative the result must not overflow or you will get undefined behavior. A common case of undefined behavior on 32-bit architectures is this:
unsigned x = 1 << 31;   /* undefined behavior: 1 is signed, 31 is too large */

The correct version is:
unsigned x = 1U << 31;   /* correct on 32 bit architectures */

Incidentally, Since C++14, the C++ Standard has a specific provision for this very case:
the value of a << b is a times 2b if it is representable in the unsigned version of the return type (which is then converted to signed: this makes it legal to create INT_MIN as 1 << 31), otherwise the behavior is undefined.
Regarding your second question, is x * 15 equal to x << 4 - x?
The answer is no because x << 4 - x is parsed as x << (4 - x).
If you parenthesize your expression, then indeed x * 15 == (x << 4) - x.
Note however that it is not correct for signed values, because the intermediary result x << 4 could overflow for large values of x for which the result of x * 15 would not.


text:
Q: can I use a subquery in a case clause the following code generates the following error:
Teradata prepare: Illegal expression in WHEN clause of CASE expression
the code:
SELECT  t1.account_id,
            t1.Expanded_Account_Name_REV,
            t2.account_start_date,
            t2.acct_economic_sector,
            CASE
                WHEN t1.account_id IN (SELECT DISTINCT account_id
                                       FROM dwp1_view.GH140_OWNER_ACCOUNT_WARNINGS
                                       WHERE warning_type_code in (251,323)
                                       AND warning_end_date > date
                                       )
                THEN 1
                ELSE 0
            END AS warning_ind
FROM (SELECT *
          FROM compliance.gmah
          ) t1
    LEFT JOIN gc01_account t2
    ON t1.account_id = t2.account_id
    LEFT JOIN (SELECT *
               FROM T0120_Account_Attribute
               WHERE 1=1
               AND Account_Attribute_Code = 821
               AND History_Ind = 0
               ) t3
    ON t1.account_id = t3.account_id

A: You must rewrite the logic as a *Correlated Scalar Subquery"
        CASE
            WHEN t1.account_id = (SELECT max(account_id)
                                   FROM dwp1_view.GH140_OWNER_ACCOUNT_WARNINGS as oaw
                                   WHERE warning_type_code in (251,323)
                                   AND warning_end_date > date
                                   AND oaw.account_id = t1.account_id
                                  )
            THEN 1
            ELSE 0
        END AS warning_ind

But those subqueries tend to have a strange plan, rewriting it using another Outer Join might be more efficient:
SELECT  t1.account_id,
            t1.Expanded_Account_Name_REV,
            t2.account_start_date,
            t2.acct_economic_sector,
--************
            CASE WHEN oaw.warning_ind IS NULL THEN 0 ELSE 1 end AS warning_ind
--************
FROM (SELECT *
          FROM compliance.gmah
          ) t1
    LEFT JOIN gc01_account t2
    ON t1.account_id = t2.account_id
    LEFT JOIN (SELECT *
               FROM T0120_Account_Attribute
               WHERE 1=1
               AND Account_Attribute_Code = 821
               AND History_Ind = 0
               ) t3
    ON t1.account_id = t3.account_id
--************
    LEFT JOIN
    (
      SELECT DISTINCT account_id
      FROM dwp1_view.GH140_OWNER_ACCOUNT_WARNINGS
      WHERE warning_type_code IN (251,323)
      AND warning_end_date > DATE
    ) AS oaw
    ON t1.account_id = oaw.account_id
--************


text:
Q: Angular Material Data Table with sorting, pagination, and filtering using Firestore I currently have a table that is being populated with data coming from Firestore.  I'm having trouble implementing sorting, pagination, and filtering to this and I was hoping someone could shed some light on this for me.  Below is my service, component, and html.  I've seen the different examples on material.angular.io but the example database they use throws me off.
service:
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Account } from './../models/account.model';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AccountService {
  accountsCollection: AngularFirestoreCollection<Account>;
  accounts: Observable<Account[]>;

  constructor(public afs: AngularFirestore) {
    this.accountsCollection = afs.collection('accounts');

    this.accounts = this.accountsCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        const data = a.payload.doc.data() as Account;
        data.id = a.payload.doc.id;
        return data;
      });
    });
  }

  getAccounts() {
    return this.accounts;
  }

 }

component:
import { Account } from './../../../models/account.model';
import { Component, ViewChild, OnInit } from '@angular/core';
import { DataSource } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { Observable } from 'rxjs/Observable';
import { AccountService } from '../../../services/account.service';

@Component({
  selector: 'app-account-table',
  templateUrl: './account-table.component.html',
  styleUrls: ['./account-table.component.css']
})
export class AccountTableComponent implements OnInit {
  dataSource = new AccountDataSource(this.accountService);
  displayedColumns = [
    'salesStep',
    'status',
    'idn',
    'hospital',
    'state',
    'regionalManager',
    'accountExecutive',
    'clientLiaison',
    'gpo'
  ];

  constructor(private accountService: AccountService) {}

  ngOnInit() {

  }

}

export class AccountDataSource extends DataSource<any> {

  constructor(private accountService: AccountService) {
    super();
  }

  connect(): Observable<Account[]> {
    return this.accountService.getAccounts();
  }

  disconnect() {}

}

html:

  <mat-form-field>
    <input matInput #filter placeholder="Search">
  </mat-form-field>

<mat-card class="example-container">

  <mat-table #table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="salesStep">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Sales Step </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.salesStep}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Status </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.status}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="idn">
      <mat-header-cell *matHeaderCellDef mat-sort-header> IDN </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.idn}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="hospital">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Hospital </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.hospital}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="state">
      <mat-header-cell *matHeaderCellDef mat-sort-header> State </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.state}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="regionalManager">
      <mat-header-cell *matHeaderCellDef mat-sort-header> RM </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.regionalManager}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="accountExecutive">
      <mat-header-cell *matHeaderCellDef mat-sort-header> AE </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.accountExecutive}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="clientLiaison">
      <mat-header-cell *matHeaderCellDef mat-sort-header> CL </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.clientLiaison}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="gpo">
      <mat-header-cell *matHeaderCellDef mat-sort-header> GPO </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.gpo}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
  </mat-table>

  <mat-paginator #paginator
                [length]="(accountService.accounts | async)?.length"
                [pageIndex]="0"
                [pageSize]="25"
                [pageSizeOptions]="[5, 10, 25, 100]">
  </mat-paginator>
</mat-card>

A: I was able to implement pagination, sorting, and filtering by installing the snapshot build (npm install --save angular/material2-builds angular/cdk-builds) and using MatTableDataSource.  For examples on how to use this: https://material2-docs-dev.firebaseapp.com/components/table/examples


text:
Q: Casting a reflected object to another type with a GenericTypeArgument during runtime Situation:
Using Asp.net Core(2.1) and EFCore(2.1)
In an api controller I get a string of a type and need to get a working Iqueryable from this.
I can get something from this through reflection on the dbcontext, which has all the objects I would need as DbSet<Type>, which I then do AsQueryable() on.
Problem is that the only way to get the Correct DbSet from the context is through reflection. But this only return an object of type Object.
I don't know any way to cast this object back to it's DbSet<Type> during runtime and I was wondering if someone else knew of it.


text:
Q: Problem connecting to localhost db using Tedious I'm trying to create a simple backend for my website. I'm writing a file to handle my database operations, but for some reason I am getting (node:13680) UnhandledPromiseRejectionWarning: ConnectionError: Connection lost - Unable to process incoming packet when I'm following the mssql documentation.
Code
db.ts
require('dotenv').config();
var sql = require("mssql");

const config: object = {
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    server: process.env.DB_SERVER,
    database: process.env.DB_DATABASE,
    port: 3306 // process.env.DB_PORT doesn't work for some reason
};

(async () => {
 await sql.connect(config);

})();

.env config
DB_USER="root"
DB_PASSWORD=""
DB_SERVER="localhost"
DB_DATABASE="app"
DB_PORT=3306

Error
(node:6388) UnhandledPromiseRejectionWarning: ConnectionError: Connection lost - Unable to process incoming packet
    at C:\Projects\Javascript\Typescript App\node_modules\mssql\lib\tedious\connection-pool.js:71:17
    at Connection.onError (C:\Projects\Javascript\Typescript App\node_modules\tedious\lib\connection.js:1038:9)    at Object.onceWrapper (events.js:482:26)
    at Connection.emit (events.js:387:35)
    at Connection.emit (C:\Projects\Javascript\Typescript App\node_modules\tedious\lib\connection.js:1061:18)
    at Connection.socketError (C:\Projects\Javascript\Typescript App\node_modules\tedious\lib\connection.js:1663:12)
    at MessageIO.<anonymous> (C:\Projects\Javascript\Typescript App\node_modules\tedious\lib\connection.js:1440:14)
    at MessageIO.emit (events.js:375:28)
    at IncomingMessageStream.<anonymous> (C:\Projects\Javascript\Typescript App\node_modules\tedious\lib\message-io.js:46:12)
    at IncomingMessageStream.emit (events.js:387:35)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6388) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:6388) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

A: It seems that you're not using the right driver to handle the server connection.
Remember that SQL Server !== MySQL server, and you're using de mssql package, which is the one for handling SQL Server connections.
Try installing a mysql package using npm i mysql or yarn add mysql (depending on the package manager you use), and try setting up a quick test connection to see if it works. =D
Click here to MySQL package documentation.


text:
Q: Wrapping a quoted function in emacs-lisp I use the cscope emacs extension (and find it quite useful).  Unfortunately, it's default behaviour of only searching the current directory and below is insufficient for me, so I use the cscope-set-initial-directory to the directory of my choice.  Unfortunately this has become insufficient for me as well because I have multiple different projects each with their own "initial" directory.
I have set up hot keys for the three cscope methods I use the most in emacs
(global-set-key [f9] 'cscope-find-this-text-string)
(global-set-key [f8] 'cscope-find-global-definition)
(global-set-key [f7] 'cscope-find-this-symbol)

I figured it would be pretty easy to somehow wrap those calls with a function to run cscope-set-initial-directory on a given path (generated by looking at what the buffer-file-name is).  But I have as-yet been unsuccessful!
(global-set-key [f9] (lambda () (interactive) (cscope-set-initial-directory "blah") 'cscope-find-this-text-string))

doesn't work.  I've also tried adding hooks to the two cscope-hooks, but neither of those seem to ever get called during my normal usage patterns.  I wouldn't even mind running it once every time I switch buffers, but I didn't see a hook for that anywhere either :/.
Can someone help? :)

A: Disclaimer: I've not installed cscope so cannot test this.
(global-set-key (kbd "<f9>") 'my-cscope-find-this-text-string)
(defun my-cscope-find-this-text-string (dir)
  (interactive "DRoot area to start search:")
  (let ((default-directory dir))
    (call-interactively 'cscope-find-this-text-string)))

The basic idea being you want to prompt for a directory to start from: that's the call to interactive.  Then you set the directory: the let statement does that for you.  Then you call the original routine you wanted, and by calling it with 'call-interactively you get prompted.
You'd wrap the other two routines similarly.
Once that's working for you, you can get fancier by customizing prompt for a root area to have its own history variable that's shared across the three routines.
Regarding your initial solution, that was a good try.  Most don't realize the need for 'interactive to turn the function into a command.  The reason the quoted name doesn't work for you is that the quote simply tells the interpreter to treat the symbol as a symbol and not do to anything with it.  To call the routine, you'd generally do:
(lambda ()
    (c-scope-find-this-text-string "some-string"))

Unfortunately, with a direct call like the one just above, you have to provide an argument (the string to search for).  So, you can either add some code to prompt for the string, or use the command's built-in code to do the prompting.  That's what the 'call-interactively is used for, it calls the command and invokes its 'interactive form which does the prompting.
Also, it's generally a good idea to bind keystrokes to names of commands, as opposed to bare lambdas, for two reasons: first, if you ever do C-h k (M-x describe-key), you get a meaningful command name, and second, if/when you modify the function, you can do so without having to muck with the binding as well.


text:
Q: Duplicate error messages in .NET Core - error CS0116 Steps to reproduce
dotnet new console
(introduce a bug in Program.cs)
dotnet restore
dotnet build

The typical output would be:
Microsoft (R) Build Engine version 15.1.548.43366 Copyright (C) Microsoft Corporation. All rights reserved.

Program.cs(5,5): error CS0116: A namespace cannot directly contain members such as fields or methods [/Users/xxx/Documents/myproj/myproj.csproj]

Build FAILED.

Program.cs(5,5): error CS0116: A namespace cannot directly contain members such as fields or methods [/Users/xxx/Documents/myproj/myproj.csproj]
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:01.77

You can see the error CS0116 is reported twice.
Is there a way to avoid the duplication in the reporting of errors?

A: The second error is part of the console logger's summary. This can be disabled by passing in /clp:NoSummary to msbuild. However, there is currently a bug in the CLI when it is the first MSBuild argument to dotnet build. Add any other MSBuild command before it to make it work. Since you want to reduce the verbosity, let's just use /nologo for the workaround:
dotnet build -c Release /nologo /clp:NoSummary

However, it works great if you use MSBuild directly:
dotnet msbuild /clp:NoSummary /p:Configuration=Release

In the upcoming 2.0.0 release, the CLI always overrides the summary parameter for dotnet build, so you'll have to use dotnet msbuild instead (I opened an issue on GitHub on that).

A: You can make your own MSBuild logger, instead of using the default console logger. There are really good instructions in Build loggers.
Essentially, you could make your own logger that captured all the data, and then emitted a simple summary at the end.
dotnet build /noconsolelogger /logger:YourCustomLogger.dll


text:
Q: Outlook rest api for on premises only setup I am trying to compare the usage of EWS vs Outlook REST Apis for an application that needs to connect to an on-prem exchange server. From what I understand, Exchange 2016 onwards supports REST Apis which are leveraged by Graph APIs as well internally when it determines that the mailbox is on-prem.
My question is, is there any way my application directly use the REST APIs to talk to the on-prem exchange, similar to EWS, if I dont need to support cloud \ hybrid setups?
For example, can I use https://my-on-prem-exchnagehost/api/v2.0/me/messages to connect to and talk to my-on-prem-exchnagehost?
All resources about the Outlook REST APIs talk about a hybrid deployment but non about on-prem only setups. My intention is to use one implementation for both on-prem and cloud where just the API endpoints change in the application, example https://my-on-prem-exchnagehost/api/v2.0/me/messages for on-prem and https://graph.microsoft.com/api/v2.0/me/messages for cloud.

A: Yes, the REST APIs should be accessible on an on-prem server.  Documentation here.  Note that the Exchange REST API and the Graph APIs are different and it's not a drop-in replacement with the Graph's interface.

A: You should note that currently it is NOT supported to use the REST APIs in a pure on-premises environment.  It may work (you can fire requests at the /Api endpoint and may get results), but if you hit any issues you are on your own.  Until Microsoft announces support for on-premises (which at the time of posting has not happened; I am not aware of any plans to change this), then you should not use it.


text:
Q: How to sum all amounts by date in pandas dataframe? I have dataframe with fields last_payout and amount. I need to sum all amount for each month and plot the output.
df[['last_payout','amount']].dtypes

last_payout    datetime64[ns]
amount           float64
dtype: object

-
df[['last_payout','amount']].head

<bound method NDFrame.head of                last_payout  amount
0      2017-02-14 11:00:06          23401.0
1      2017-02-14 11:00:06          1444.0
2      2017-02-14 11:00:06          0.0
3      2017-02-14 11:00:06          0.0
4      2017-02-14 11:00:06          290083.0

I used the code from jezrael's answer to plot the number of transactions per month.
(df.loc[df['last_payout'].dt.year.between(2016, 2017), 'last_payout']
         .dt.to_period('M')
         .value_counts()
         .sort_index()
         .plot(kind="bar")
)

Number of transactions per month:

How do I sum all amount for each month and plot the output? How should I extend the code above for doing this?
I tried to implement .sum but didn't succeed.

A: PeriodIndex solution:
groupby by month period by to_period and aggregate sum:
df['amount'].groupby(df['last_payout'].dt.to_period('M')).sum().plot(kind='bar')

DatetimeIndex solutions:
Use resample by months (M) or starts of months (MS) with aggregate sum:
s = df.resample('M', on='last_payout')['amount'].sum()
#alternative
#s = df.groupby(pd.Grouper(freq='M', key='last_payout'))['amount'].sum()
print (s)
last_payout
2017-02-28     23401.0
2017-03-31      1444.0
2017-04-30    290083.0
Freq: M, Name: amount, dtype: float64

Or:
s = df.resample('MS', on='last_payout')['amount'].sum()
#s = df.groupby(pd.Grouper(freq='MS', key='last_payout'))['amount'].sum()
print (s)
last_payout
2017-02-01     23401.0
2017-03-01      1444.0
2017-04-01    290083.0
Freq: MS, Name: amount, dtype: float64

Then is necessary format x labels:
ax = s.plot(kind='bar')
ax.set_xticklabels(s.index.strftime('%Y-%m'))

Setup:
import pandas as pd

temp=u"""last_payout,amount
2017-02-14 11:00:06,23401.0
2017-03-14 11:00:06,1444.0
2017-03-14 11:00:06,0.0
2017-04-14 11:00:06,0.0
2017-04-14 11:00:06,290083.0"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), parse_dates=[0])
print (df)
          last_payout    amount
0 2017-02-14 11:00:06   23401.0
1 2017-03-14 11:00:06    1444.0
2 2017-03-14 11:00:06       0.0
3 2017-04-14 11:00:06       0.0
4 2017-04-14 11:00:06  290083.0

A: You can group by month-start ('MS') using resample:
df.set_index('last_payout').resample('MS').sum().plot(kind='bar')


text:
Q: Solving The 8 Puzzle With A* Algorithm I would like to solve/implement the 8 puzzle problem using the A* algorithm in Java. Am asking if someone can help me by explaining to me the steps i must follow to solve it. I have read on the net how the A* works but i don't know how to begin the implementation in Java.
I will be very grateful if you guys can help me and give me the guidelines so that i can implement it myself in Java. I really want to do it to be able to understand it, so i just need the guidelines to start.

I will use priority queues and will read the initial configuration from a text file which looks like for example this:
4  3  6
1  2  5
7  8

Pointers to other sites for more explanation/tutorials are welcome.

A: I'd begin with deciding how you want to represent the game board states,
then implement the operators (eg. move (blank) tile up, move (blank) tile down, ...).
Typically you will have a data structure to represent the open list (ie. those states
discovered but as yet unexplored (ie. compared with goal state) and another for the
closed list (ie. those states discovered and explored and found not to be the goal state).
You seed the open list with the starting state, and repeatedly take the "next" state to
be explored from the open list, apply the operators to it to generate new possible states
and so on ...
There is a tutorial I prepared many years ago at:
http://www.cs.rmit.edu.au/AI-Search/
It is far from the definitive word on state space searching though, it is simply an educational tool for those brand new to the concept.

A: Check http://olympiad.cs.uct.ac.za/presentations/camp1_2004/heuristics.pdf it describes ways of tackling this very problem.

A: A* is a lot like Djikstra's algorithm except it includes a heuristic. You might want to read that wiki or read about single-source shortest path algorithms in general.
A lot of the basic stuff is important but obvious. You'll need to represent the board and create a method for generating the possible next states.
The base score for any position will obviously be the minimum number of actual moves to arrive at it. For A* to work, you need a heuristic that can help you pick the best option of possible next states. One heuristic might be the number of pieces in the correct position.


text:
Q: Insert Command into Bash Shell Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this.
I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good.
If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it.
If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.

A: You can do this, but only if the shell runs as a subprocess of your Python program; you can't feed content into the stdin of your parent process. (If you could, UNIX would have a host of related security issues when folks run processes with fewer privileges than the calling shell!)
If you're familiar with how Expect allows passthrough to interactive subprocesses (with specific key sequences from the user or strings received from the child process triggering matches and sending control back to your program), the same thing can be done from Python with pexpect. Alternately, as another post mentioned, the curses module provides full control over the drawing of terminal displays -- which you'll want if this history menu is happening within the window rather than in a graphical (X11/win32) pop-up.

A: See readline module. It implements all these features.

A: If I understand correctly, you would like history behaviour similar to that of bash in
a python app. If this is what you want the GNU Readline Library is the way to go.
There is a python wrapper GNU readline interface but it runs only on Unix.
readline.py is seem to be a version for Windows, but I never tried it.

A: ncurses with its python port is a way to go, IMHO.


text:
Q: Gradient orientation My former multivariable calculus professor denoted the gradient as
$$\mathrm{grad}\,\mathit{f}\, (x;y)= \begin{pmatrix}x\\y\end{pmatrix}.$$
Completely forgot that. Since then I've always been writing the gradient as a row vector. Is there a difference? Googled it, but I'm not satisfied. Some even make a difference between the vector derivative and gradient. I'm a bit confused now. What is right? Is there an actual difference?
The reason for my question is a matrix derivate problem. In one of my older question I got a hint to a problem:
$$\frac {\partial(a^Tx)} {\partial x}=\frac {\partial(x^Ta)} {\partial x}=a$$
I tried to learn this rule. My thoughts are as follow. Both numerators are the same because they result in the same scalar. The $x$ in the denominator is a column vector. Therefore the result (here $a$) should be a column vector too when taking the derivate.
On the other hand, taking a vector derivative (or the gradient?) of a scalar (or a function) should result in a row vector $a^T$.
Additionally, if the numerator would be a vector instead of a scalar, then the result would be a Jacobean right? And Jacobeans have on one row all the derivatives respective to a $x_m$, and the $numerators_m$ in the columns. Keeping that form the output of the hint should be $a^T$, shouldn't it?


text:
Q: Usage of "As ..." in the beginning of a sentence, Any alternatives? I use the following type of sentences a lot, because I do not know any alternatives:
E.g.

As my child grows over time, I become older.

By which I mean that I my child is growing, and I am getting older, and this is a constant process.
What are the alternative ways to express such things?
Thanks!

A: You could replace "As" with "When" or "While".
Another structure is "X and Y  happen [or occur]
concurrently [or simultaneously, but that doesn't mean exactly the same thing]".

A: "I age in proportion to my child's development over time".


text:
Q: How to change selected value of dropdown in the powerapps? I have a checkbox and a dropdown in the powerapps form. The dropdown value will be changed based on the checkbox selection. How can I achieve this?

A: Hmm, This is quite interesting looks like via Rules these run-time value assignments are disabled at this point. However, there is a workaround
Filter(Issues,ID=If(Checkbox1.Value, 6,2))


text:
Q: get files from failed boot drive ubuntu 16 Im crossing my fingers that someone can help me out. I have a dell server that I use as a desktop. I have a 2tb boot drive and three addition 2tb drives in a raid 0. The boot drive has been acting funny the last couple weeks in that I need to run a manual fsck every time I boot or reboot. I bought a new 2tb drive last week thinking I'd just replace the drive this weekend. I booted the server, and the hard drive wasn't found. I tried to boot from a usb and I can see the raid but cannot access it at all (no permissions), and I still can't see the failed boot drive. I unfortunately have work on the boot drive that is unfinished and not backed up yet... uhh, flog me. Id really like to figure out how to access whatever files maybe remaining on this drive and hopefully recover whatever is remains of my project. Any ideas?
EDIT: per the discussion in the comments, an Ubuntu based solution was not found, this is a hardware issue. If I find a solution I'll edit this post for the benefit of others in need.


text: Q: C API's for Packages/Binaries integrity check on already installed packages/binaries? debums is verifying from /var/lib/dpkg/info/*md5sums and this file can be modified easily by root user, looking for alternative like database or something else.


text:
Q: Genymotion startup commands I'm new to genymotion.  How do I send startup commands to the emulator?  I would like it to startup up with out the "Android" graphic and to scale the screen to a smaller size.  I know how to do this with the google android emulator, but am unsure with genymotion.  Any ideas are appreciated.  Thanks.

A: You can start the emulator in command line. All the information are available on this other StackOverflow thread
Concerning the screen scaling, this is not currently possible through Genymotion tools. You can maybe find other tools for your specific host platform.


text:
Q: Problem concerning Numerical Solutions of Nonlinear Systems of Equations (Burden and Faires) I need help with this particular question:
The nonlinear system

*

*$3x_1 - \cos (x_2 x_3) - \frac{1}{2} = 0$

*$x{_1}^2 - 625x{_2}^2 - \frac{1}{4}=0$

*$\exp ^{-x_1x_2} + 20x_3 + \frac{10\Pi -3}{3}=0$

has a singular Jacobian matrix at the solution. Apply Newton's method with x$^{(0)} = (1,1,-1)^t$. Note that convergence may be slow or may not occur within a reasonable number of iterations.
My attempt on Maple:
What am I doing wrong here?
Solving it by-hand is a pain.

A: In your NewtonMV procedure, try changing,
 A := subs(s,f);

to,
 A := eval(J, [s]);

or to,
 A := subs(s, J);

Also, change the call LinearSolve(...) to :-LinearAlgebra:-LinearSolve(...) so that it gets the right export from the right top package, regardless of whether you've loaded any subpackage of Student.
Personally, I'd rather see evalf wrapped around each of the two arguments to LinearSolve than around its call, if only so that the very first iteration doesn't attempt an exact subcomputation.
So, something like,
 dx := :-LinearAlgebra:-LinearSolve( evalf(A), evalf(-fx) );

Please note that you can inline code into your Questions and Answers here see the menubar above the editing region. It's not so helpful to paste images of code.
[edited, after all the typos have been resolved]
You might want to consider additional stopping criteria. Apart from a maximal number of iterations to allow, you could stop when either the increment dx got small enough, or when the evaluation of f got close enough to zero (ie. x is considered a root).
restart:

NewtonMV:=proc(f,v,x0,n,xtol,ftol)
local i,result,J,x,fx,A,dx,s;
J:=VectorCalculus:-Jacobian(f,v);
x:=x0;
dx:=Vector([infinity,infinity,infinity]);
fx:=Vector([infinity,infinity,infinity]);
result:=convert(x0,list);
for i from 1 to n
  while :-LinearAlgebra:-Norm(dx)>xtol
    and :-LinearAlgebra:-Norm(fx)>ftol do
   s:=[seq(v[i]=x[i],i=1..nops(v))];
   fx:=evalf(eval(f,s));
   A:=evalf(eval(J,s));
   dx:=:-LinearAlgebra:-LinearSolve(evalf(A),evalf(-fx));
   if indets(dx,name)<>{} then
      dx:=subs([seq(p=0,p=indets(dx,name))],dx);
   end if;
   x:=x+dx;
   result:=result,convert(x,list);
end do;
printf("\nnumber of iterations: %a\n\n",i-1);
printf("final increment dx, and its norm:\n      %a ,  %a\n\n",
       convert(dx,list), :-LinearAlgebra:-Norm(dx));
printf("substitution of solution x into f, and its norm:\n      %a ,  %a\n\n",
       convert(eval(f,s),list), :-LinearAlgebra:-Norm(fx));
return [result];
end proc:

lhs1:=3*x1-cos(x2*x3)-1/2;
lhs2:=x1^2-625*x2^2-1/4;
lhs3:=exp(-x1*x2)+20*x3+(10*Pi-3)/3;

NewtonMV(Vector([lhs1,lhs2,lhs3]),[x1,x2,x3],
         Vector([1,1,-1]), 400, 1e-5, 1e-7);

That is not intended to be the epitome of great coding, but it might give you some ideas.


text:
Q: Visual Studio 2012 TypeScript project ignoring two files during compile
   I have a Visual Studio 2012 TypeScript project. When I first made the project I added 2 new .ts files these were Framework.ts & Graphics.ts. I recently added two more TypeScript files to be declaration files and named them .d.ts such as Framework.d.ts and Graphics.d.ts. The interesting part is that all 4 of these files have the Build Action Property set to TypeScriptCompile yet only 2 of them build (Framework.ts and Graphics.ts) the other .d.ts files still have the original .js build code regarding a shapes module. I thought perhaps there was a problem with the .d.ts extension and renamed these files to Framework_d.ts and Graphics_d.ts. This didn't build them either!
At this point I am at a loss. I looked at the csproj file:
<TypeScriptCompile Include="Framework\Framework.d.ts" />
<Content Include="Framework\Framework.d.js">
  <DependentUpon>Framework.d.ts</DependentUpon>
</Content>
<Content Include="Graphics\Graphics.d.js">
  <DependentUpon>Graphics.d.ts</DependentUpon>
</Content>
<Content Include="TestPages\SpriteBatch.html" />
<TypeScriptCompile Include="Framework\Framework.ts" />
<Content Include="Framework\Framework.js">
  <DependentUpon>Framework.ts</DependentUpon>
</Content>
<Content Include="Graphics\Graphics.js">
  <DependentUpon>Graphics.ts</DependentUpon>
</Content>
<TypeScriptCompile Include="Graphics\Graphics.d.ts" />
<TypeScriptCompile Include="Graphics\Graphics.ts" />

And then the execute command for the typescript compiler:
<Target Name="BeforeBuild">
  <Exec Command=""$(PROGRAMFILES)\Microsoft SDKs\TypeScript\0.8.0.0\tsc" @(TypeScriptCompile ->'"%(fullpath)"', ' ')" />
</Target>

This really should build these files too. I just have no idea why it refuses to. Does anyone know how to fix this?

A: If they are as you say, declaration files, then they will have no javascript output.  I think you do not need to 'add' these to the project or at the very least, do not bother applying the TypeScriptCompile build action on them.  You can just include them in the other source files using
///<reference path="Framework\Framework.d.ts"
///<reference path="Graphics.d.ts"

so they see the declarations.

A: I'm not sure this is your case or not,
but there are some issues regarding with .ts file encoding.
Unfortunately TypeScript cannot compile UTF-8 with signature.
You might choose another save option by
"FILE"-->"Advanced Save Options"--> Select "UTF-8 without signature".
Check current issue.
http://typescript.codeplex.com/workitem/85
Thanks


text:
Q: Getting "Aspect ratio constraints with Xcode versions prior to 5.1" error Just upgraded to recent Xcode 5.1 version and accidentally found cool feature in storyboards - pin two elements vertically and keeping aspect ratio between of them. However, getting an error during the compilation. Then I read Xcode release notes about this new feature but still it's unclear - is it supported for iOS7.1 only (was unable to find in specs) or other things need to be done.

A: If we open Storyboard then go to the right pane under the File Inspector tab, then we will find a section called Interface Builder Document. This section contains "Buid for" drop down list and so setting it to Xcode 5.1 fixes the problem. This setting manages storyboard file structure and minimum supported Xcode version.


text:
Q: Forget doesn't work If I try to remove an item from this collection
$examples = Example::where('example', '=', $data['example'])->get();

by doing
$examples->forget(20);

it doesn't remove the item from the collection, I still get back all the items that were in there originally. I have read the Laravel documentation and the api docs. And it should work (I think) but it doesn't.
Could someone point me out what I am doing wrong here?
This still returns an object.
$examples->forget(49);
return $examples->find(49);

P.S. Ever other method like push or get works.
Thanks alot!

A: You did a small mistake, actually you didn't notice that. I did myself :).
Forget use the array key to delete an object item from collection.
Array(0 => 'abc'
 1 => 'bcd'
 49 => 'aaa'
)

$examples->forget(49);
                  ^^ array key 49

Where as, find use the id to find an object from an collection
table: examples

id example
1   abc
49  bce

$examples->find(49);
                ^^ `example id`

A: According to the documentation it says that forget() works by key. The word "key" is ambiguous because what they mean to say is array key also known as "index" and not model key which is the id.
However, in the other methods such as find() or contains() they use the word "key" to mean model key so you can see the confusion.
When you look at the source you can see that the forget() method is found in the Illuminate\Support\Collection class and not in Illuminate\Database\Eloquent\Collection.
My theory is that the support class is supposed to be more generic so it doesn't consider the model keys, but really I don't know.

A: I just wanted to add on to the Anam's answer. Once you have a collection you can then loop through it like this to delete by ID
function forgetById($collection,$id){
    foreach($collection as $key => $item){
        if($item->id == $id){
            $collection->forget($key);
            break;
        }
    }
    return $collection;
}

$examples = Example::where('example', '=', $data['example'])->get();

$examples = forgetById($examples,20);

A: you could do
$examples->reject(20);

Like most other collection methods, reject returns a new collection instance; it does not modify the collection it is called on.


text:
Q: Как получить возможность редактировать css код со встроенного скрипта есть код, для вставки на сайт
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

я хотел бы видоизменить input и кнопку
возможно ли это сделать?

A: Один из наиболее простых и правильных способов - повышение специфичности селектора. Специфичность селектора рассчитывается следующим образом:

*

*подсчитайте количество селекторов ID в селекторе (= a)

*подсчитать количество селекторов классов, селекторов атрибутов и
псевдоклассов в селекторе (= b)

*подсчитать количество селекторов типов и псевдоэлементов в селекторе
(= c)

*игнорировать универсальный селектор
Селекторы внутри псевдокласса
отрицания учитываются как любые другие, но само отрицание не
считается псевдоклассом.

Конкатенация трех чисел abc (в системе счисления с большим основанием) дает специфичность.
Примеры с возрастающе специфичностью:
* /* a=0 b=0 c=0 -> специфичность = 0 */
LI /* a=0 b=0 c=1 -> специфичность = 1 */
UL LI /* a=0 b=0 c=2 -> специфичность = 2 */
UL OL+LI /* a=0 b=0 c=3 -> специфичность = 3 */
H1 + *[REL=up] /* a=0 b=1 c=1 -> специфичность = 11 */
UL OL LI.red /* a=0 b=1 c=3 -> специфичность = 13 */
LI.red.level /* a=0 b=2 c=1 -> специфичность = 21 */
#x34y /* a=1 b=0 c=0 -> специфичность = 100 */
#s12:not(FOO) /* a=1 b=0 c=1 -> специфичность = 101 */

Исходя из вышеописанного есть такого рода решение:

html body .sb_block .sb_btn{
  border-radius: 50%;
}

html body .sb_block #user-data-form
.justify-content-center .wh-form-field
.form-control,
html body .sb_block #user-data-form
.justify-content-center .wh-form-field
.input-phone-wrapper
div.select-mask
{
  background: #14a7d5;
  color: white;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Другой более сложный способ - непосредственно воздействовать на стили. Сложен он прежде всего тем что нужно будет учитывать  каскадность практически вслепую, хотя позволяет добавлять стили абсолютно любого характера, например такие как :hover
Пример чтение всех подключенных к документу списков стилей
function getStyleSheet(unique_title) {
  for (const sheet of document.styleSheets) {
    if (sheet.title === unique_title) {
      return sheet;
    }
  }
}

Пример вставки правила:
 myStyle.insertRule('#blanc { color: white }', 0);

Так же на MDN можно найти примеры по другим методам например deleteRule()


text:
Q: Extract value of Polars literal If I have a Polars literal, how can I extract the value?
import polars as pl

expr = pl.lit(0.5)

val = float(expr)
# TypeError: float() argument must be a string or a real number, not 'Expr'

A: Like so:
val = pl.select(expr).item()

Explanation: a polars literal is an Expr object. An Expr object can be evaluated using pl.select(). That returns a DataFrame. To get the scalar value from the dataFrame, you can use  DataFrame.item().
Note: .item() was added in release 0.15.9 of polars. If you are using a version prior to this, you can use pl.select(expr)[0, 0] as an alternative.


text:
Q: Rails Nested Model Form with has_many through Relationship and build call I'm building a one page form that will create a model and it's relations. I've gone through a ton of resources around the net as well as the complex forms series on Railscasts but can't seem to find the solution to my problem.
Here's what I have.
class Campaign < ActiveRecord::Base
  has_many :artwork_groups
  has_many :artwork_locales, :through => :artwork_groups

  accepts_nested_attributes_for :artwork_groups
  accepts_nested_attributes_for :artwork_locales
end

class ArtworkGroup < ActiveRecord::Base
  belongs_to :campaign
  has_many :artwork_locales
end

class CampaignsController < ApplicationController
  def new
    @campaign = Campaign.new
    @locales = Locale.all

    # Build the artowrk groups and locales for the new campaign
    2.times do
      @campaign.artwork_groups.build do |ag|
        @locales.each do |locale|
          ag.artwork_locales.build(:locale_id => locale.id)
        end
        logger.debug ag.artwork_locales
      end
    end

    @games = GameVersion.all(:order => "game_key").group_by(&:game_family).sort_by{|k| k.first.name }

    respond_to do |format|
      format.html
    end
  end

In my view I have the following (markup removed):
<% form_for @campaign, :html => { :multipart => true } do |campaign| %>

  <%= campaign.error_messages %>
  <%= flash[:campaign_wizard] %>

  <%= campaign.label :title %>
  <%= campaign.text_field :title %>

  <%= campaign.label :url %>
  <%= campaign.text_field :url %>

  <%= campaign.label :start_date %>
  <%= campaign.text_field :start_date, {:class=>"datetimepicker"} %>

  <%= campaign.label :end_date %>
  <%= campaign.text_field :end_date, {:class=>"datetimepicker"} %>

  <% campaign.fields_for :artwork_groups do |aw| %>

    <%= aw.label :name, "Artwork Group Name"  %>
    <%= aw.text_field :name %>

    <% aw.fields_for :artwork_locales do |al| %>

      <%= al.label :locale_id %>
      <%= al.text_field :locale_id %>

      <%= al.label :language %>
      <%= al.text_field :language %>

      <%= al.label :upstate %>
      <%= al.text_field :upstate %>

    <% end %>

  <% end %>

  <%= campaign.submit 'Save Campaign & Publish' %>

<% end %>

I'm getting the 2 artwork group sections in my view but I'm only getting one artwork locale per artwork group. I was expecting one for each locale I've got loaded. I'm assuming this is an issue with the has_many through relationship or the nested build calls in my controller.
Any help will be greatly appreciated.

A: Have you tried adding accepts_nested_attributes_for :artwork_locales to ArtworkGroup?


text:
Q: how to pass html string to another activity webView I want to pass html string to another activity webView.
Here my html string and Main_Activity Code. What is Another_Activity.java Code.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">String Passing</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

    <string name="html_data">
 <![CDATA[

       Everton plotting loan swoop for Man United youngster James Wilson
       The Toffees were quick to register an early interest for the 19-year-old striker at the turn of the year.
     Goodison Park boss Roberto Martinez has had his eye on a number of Old Trafford fringe players, although Wilson remains the most likely.
     Wilson, who scored twice for United last season, is also a target for West Bromwich Albion, having been recommended to them by former United midfielder Darren Fletcher.
     United will overhaul their striker department this summer following the release of Colombian striker Radamel Falcao and the continued uncertainty surrounding the future of Robin van Persie.
     United have made no decision yet on Wilson and boss Louis van Gaal will assess his pre-season before sitting down with the teenager and discussing all the options.

  ]]>
    </string>

    <string name="title_activity_another_">Another_Activity</string>

</resources>

Main_Activity.Java

package com.nasir.stringpassing;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 Button Nasir;

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

  Nasir = (Button) findViewById(R.id.Nasir);
  Nasir.setOnClickListener(new OnClickListener() {

//   String myString = getString(R.string.html_data);

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub

    Intent intent = new Intent(MainActivity.this, Second_Activity.class);
    intent.putExtra("header", getString(R.string.html_data));
    startActivity(intent);
   }
  });

 }

}

Please Write Another_Activity.Java code to show WebView text.

A: Create webview.xml in layout folder
<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

then create Second_Activity like this.
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class Second_Activity extends Activity {

    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        String customHtml = getIntent()..getStringExtra("header");;
        webView.loadData(customHtml, "text/html", "UTF-8");

    }

}

A: You can use String myString = getIntent().getStringExtra("header"); in the second Activity, but if your html code is in string.xml, you just can get it as you do in the first activity - String myString = getString(R.string.html_data); and it will gives you the same.


text:
Q: Identifying a maybe bad SOT23 transistor To give a bit of background, I'm trying to fix a friend's NeoGeo CD console which doesn't read disc: The disc doesn't spin at all, the laser assembly and lens are moving, the diode turns on. But it seems it didn't detect any disc and so never make it spin. The spinning motor seems to work, applying 1 V makes it turns. The driver IC seems Ok too (it drives the carriage motor correctly).
My friend thought the laser assembly was bad, and order a new one and so asked me to replace it. This replacement comes from Ali Express, and even if it uses the same SHARP IC, the PCB and wiring on it doesn't seems to be the same as the original one. So it might be bad, as long as the original one. But with either one or the other, there's no spinning at all.
But after making some research on google, I found an old thread post of someone having similar issue (disc not spinning), and the guy said he founded a bad transistor (didn't say which one) on the cd drive controller board (he did have another working NeoGeo and could swap controller board to confirm that the issue comes from it).
So I went ahead and try to test (in circuit ...) with a DMM (in diode mode) the 5 transistors on the PCB, and found one suspicious, in a SOT23 package (sorry for the picture quality, I should have clean the board):

With the diode tester, I find only a connection between 2 pins of the transistor. And I couldn't find what kind of transistor this one is (I know it can be hard with smd marking).
Fortunately, there's another one on the board, which I could test (and which seems to be OK):

I'm absolutely not an expert, so when I tried to identify the transistor and its pinout, so I'm not sure at all that this is correct. It seems it's an NPN, but the pinout seems uncommon (as far as I know most SOT23 transistor has a common pinout?). Also what I think it's the base is connected to ground (on both transistors), which also seems uncommon (common base?).
Considering it's an SOT23, I don't think I can easily unsolder it from the board (I do have a cheap hot air desoldering station), test it, and put it back if it's OK. I would preferred to replace it with an equivalent TO92,  if it's worth it. Also I don't want to do any useless damage to the PCB.


text:
Q: ng-class within ng-repeat when object comes from other object/array PLUNKER
I have an app that allows users to see info about live music and favorite the shows they like. Pushing the star button does this.  They can then see this information on their own music calendar page.

I'm able to save and update the favoriting data into my database just fine now.  But I can't figure out how to style the star buttons (favoriting buttons) based on whether the user has favorited the item or not.  They should change color/style if they are favorited or not.
There is data that comes from the music shows and data about the user (their personal info or favorites).  These are separate bits of data.  So when I bring the shows info in via ng-repeat, this is different than the info I have on whether the user has favorited that show.
The jist of the question, then, is how to style items/icons using ng-class within an ng-repeat when the info on whether those items have been favorited (true or false) comes from another object or array (can create either).  Most of the examples with ng-repeat and ng-class are a alot simpler because the data on whether something is selected or not is within that same object.
HTML

{{show.properties.price}}

{{show.properties.tags}}

{{show.properties.artist}}

{{show.properties.venue}}

The pertinent part of the html is around   That's what creates the star icon.
Controller
I'll include the plunker so as not to have to jam this up.
The object where the user favorites are stored looks like this
$scope.loggedInUserFavorites = Object { $$conf: Object, $id: "favorites", $priority: null, show0: true, show1: false, show3: true, show5: false }
using Angular.foreach I pared it down to this:
Object { 0: false, 1: false, 3: true, 5: false }
How can I access those true/false properties of $scope.loggedInUserFavorites on my template to style the star icon?
PLUNKER

A: Actually this should work:

As scopes prototypically inherit from their parents, you do actually have access to both the show model from the ng-repeat scope, and loggedInUserFavorites from the StarredCtrl scope.
Cheers!

A: Try this (where shows[$index].starred is your logic to check if the show has been favorited)

A: I basically used both @sanghas26 and @HeberLZ's to come up with:

So I changed the h2 to fa and then used the full and empty stars as the css classes.  I really don't know why fillgreen and fillblue didn't work here.  Will continue to investigate.
Anyway, it works.  This took 6 weeks to figure out.


text:
Q: Print the environment variables using environ How to print the environment variables in a C program using environ.
extern char **environ

A: Do you mean
int main(int argc, char **argv, char **envp)
{
    while(*envp!=null) {
        printf("%s\n", *envp);
        envp++;
    }
    return 0;
}

A: #include <unistd.h>
#include <stdio.h>

extern char **environ;
//...

int i = 0;
while(environ[i]) {
  printf("%s\n", environ[i++]); // prints in form of "variable=value"
}


text:
Q: Solution of an ODE in sections The ODE $x'(t)=-\sqrt{x(t)}$ with $x(0)=1$ is given.
My solution I found is $x(t)=\frac{1}{4}t^2-t+1$.
I know that $x(t)=0$ is also a solution.
The book says the solution is given by
$x(t) =
\begin{cases}
(1-\frac{1}{2}t)^2 & \text{if } t \leq 2\\
0 & \text{if } t > 2\\
\end{cases}$
My question is:
Why is the solution $x(t)=\frac{1}{4}x^2-x+1$ true only for $t\leq2$? And why $x(t)=0$ only for $t>2$?

A: If one goes about naively solving the equation, then notice that $x=\sqrt{x}^2\implies{x'=2\sqrt{x}[\sqrt{x}]'}.$ So one has that $2\sqrt{x}[\sqrt{x}]'=-\sqrt{x},$ implying that $\sqrt{x}=0$ on some subset of the domain of $x,$ while $[\sqrt{x}]'=-\frac12$ everywhere else. The latter implies $$\int_0^t[\sqrt{x}]'\,\mathrm{d}s=\int_0^t-\frac12\,\mathrm{d}s\implies\sqrt{x(t)}-\sqrt{x(0)}=-\frac{t}2.$$ Since $x(0)=1,$ we have that $x(t)=\left(1-\frac{t}2\right)^2.$ But remember that this is only true on some subset of the domain, and on the complement of that subset we have $x(t)=0.$ So we do not know what exactly $x$ is yet in terms of a piecewise description. Instead, let us go back to the original equation. Notice that because $x'=-\sqrt{x}$, and because $\sqrt{x}\geq0$, we must have that $x'\leq0.$ Also, given $x(t)=\left(1-\frac{t}2\right)^2,$ we have $x'(t)=-\left(1-\frac{t}2\right)=\frac{t}2-1.$ Meanwhile, $-\sqrt{x(t)}=-\sqrt{\left(1-\frac{t}2\right)^2}=-\left|1-\frac{t}2\right|.$ The issue is that $\frac{t}2-1=-\left|1-\frac{t}2\right|$ is true if and only if $\left|1-\frac{t}2\right|=1-\frac{t}2,$ which is only true when $1-\frac{t}2\geq0$, which is equivalent to $t\leq2.$ Thus, it is only when $t\leq2$ that $x(t)=\left(1-\frac{t}2\right)^2$ holds, and in order for the differential equation to be satisfied everywhere in $\mathbb{R},$ it can only be the case that for $t\gt2,$ $x(t)=0,$ as suspected.


text:
Q: If $Ra$ is free for $a\neq 0,$ is $a$ regular? Let $R$ be a commutative ring with unity, and $0\neq a\in R.$ We will say that an element $x\in R$ is linearly independent if $\{x\}$ is a linearly independent set. A non-zero element of $R$ is called regular if it is not a zero divisor.
$a$ is a regular element iff $\{a\}$ is a linearly independent set. So if $a$ is regular, then the principal ideal $Ra$ is a free $R$-module with basis $\{a\}.$ My question is about the converse.

Suppose $Ra$ is a free $R$-module. Is $a$ regular?

Suppose for a moment that $Ra$ has a one-element basis $\{b\}.$ Then $Ra$ is isomorphic to $R$ as an $R$-module. The $R$-module $R$ has the following property.

$(\mathrm P)$ Every element $x\in R$ generating the whole module $R$ is linearly independent.

This is because the elements generating the whole $R$ are exactly the units of $R$, and the linearly independent elements are exactly the regular elements of $R$ and $0$. Units are always regular.
$Ra$, being isomorphic to $R,$ also satisfies $(\mathrm P).$ Therefore, since $a$ generates the whole $Ra,$ we have that $a$ is linearly independent, and hence regular.
So, returning to my main question, if $Ra$ is a free $R$-module, and we want to show that $a$ is regular, it is enough to show that $Ra$ has a one-element basis, not necessarily $\{a\}.$
It is not difficult to prove that $Ra$ must have a finite basis. Suppose $\{x_i\}_{i\in I}$ is a basis of $Ra$. Then $a$ can be written as $$a=\sum_{j\in J}r_ix_j,$$ where $J$ is a finite subset of $I.$ Clearly, $\{x_j\}_{j\in J}$ is linearly independent and generates the whole $Ra.$
I don't see how to go from a finite basis to a one-element basis. However, I believe commutative rings should be "nice" enough for the answer to be "yes". Could an ideal of a commutative ring have greater dimension than the ring itself?

A: Yes, if $0\neq I\subset R$ is an  ideal (not assumed principal !) which is a free module, then $I$ has dimension $1$.
Proof
A basis of $I$ can have  only one element because any two different elements $0\neq a,b\in I$ are linked by the non-trivial linear relation   (watch carefully !)
$$b\cdot a-a\cdot b=0$$
Remark So a posteriori $I$ turns out to be principal after all, even if you didn't assume it.

A: I don't think it requires that many words: it's pretty elementary.
If $aR\cong R$ via a homomorphism $f$, then there exists $b$ such that $f(ab)=1$.
If $a$ were not regular, say $c\neq0$ and $ca=0$, then $0=f(cab)=cf(ab)=c1$: a contradiction. So, $a$ must be regular.
Another way is to realize $ann(aR)=ann(a)$. So the module $aR$ is faithful iff $a$ is regular.  Clearly all free modules are faithful.

A: Thanks for elaborating the question so much, but I think you are missing something simple. An element is regular if it is neither $0$ nor a zero divisor. Now assume $a$ is not regular. Then if we first consider the possibility $a=0$ we see that $aR=\{0\}$, which is a free $R$ module, so the answer to your question is strictly speaking"no, $aR$ free does not imply $a$ regular". But this module is not of rank $1$, so you probably want to include that in your question: "if $aR$ is a free $R$ module of rank $1$, then does it follow that $a$ is regular?". Now we have excluded $a=0$, so remains the case of a zero divisor: $ab=0$ with $a,b$ nonzero. But this relation immediately shows that $aR$ is not a free $R$ module, since mutliplication by $b$ kills all of $aR$, but it doesn't kill all of $R$. So to the modified question the answer is "yes, if $aR$ is a free $R$ module of rank $1$, then $a$ is regular".


text:
Q: mongoid / mongodb - Geospatial queries on embedded document it is possible to do a geospatial query on the embedded document and have a "flat" results?
Class a
  ....
  embeds_many : bs
end

Class b
   ....
   field :location, :type => Array

   embedded_in :a, :inverse_of => :b
   index [[:location, Mongo::GEO2D]]
end

I was able to push the indexation in the mongo console
db.a.ensureIndex({"bs.location" : "2d"})

And then was able to query from the mongo console
db.a.find( { 'b.location' : { $near : [50,50] } # mongo console

However, the results is a list of "a" Documents, and not a list of "b" objects.
Two question:
1* It is what I am trying to do doable? (I know [and follow the virtual collection Jira] http://jira.mongodb.org/browse/SERVER-142)
2* If yes, how can it be accomplished in Mongoid?
If not, the only option I will have will be to remove the embedded collection and move to a "classic" reference / is_referenced couple of classes.

A: It's not possible in v2.0, but is in v2.1, using the aggregation framework and renaming fields (there may be other ways too).
The basic idea is to $match : { $near : <> }, then $project : { _id : 0, location : "$b.location" }
http://www.mongodb.org/display/DOCS/Aggregation+Framework+-+%24project#AggregationFramework-%24project-RenamingFields

A: It's not doable. You will have to use one query to get a list of "a" documents then filter it down into a list of "b" documents, but there is no way to merge that into one step.


text:
Q: C Beginners' Query: char array program - not getting desired output Newbie Question:
Hi! Intended to study how one array populates another (initialised) array during copying. So I ran the following bit of code.
#include<stdio.h>

char strA[]= "\nThis is array 'a'.\n";
char strB[] = "ABCDEFGABCDEFGABCDEFG";

int main()
{
  /* Copy one string to another using pointers */

  char *pA, *pB;
  puts(strA);
  puts(strB);
  pA=strA;
  pB=strB;
  puts(pA);
  puts(pB);
  while(*pA!='\0') {
    *pB++ = *pA++;
    puts(pB);
  }
  *pB='\0';
  puts(strB);

  return 0;
}

What I expected was to see how strA[] copied itself into strB[] at each step i.e. somewhere in the middle strB[] would have strA[] elements copied and remaining strB[] elements. But I could not find strA[] elements copied into strB[], though strB[] elements kept decreasing. The following is the output:
This is array 'a'.

ABCDEFGABCDEFGABCDEFG

This is array 'a'.

ABCDEFGABCDEFGABCDEFG
BCDEFGABCDEFGABCDEFG
CDEFGABCDEFGABCDEFG
DEFGABCDEFGABCDEFG
EFGABCDEFGABCDEFG
FGABCDEFGABCDEFG
GABCDEFGABCDEFG
ABCDEFGABCDEFG
BCDEFGABCDEFG
CDEFGABCDEFG
DEFGABCDEFG
EFGABCDEFG
FGABCDEFG
GABCDEFG
ABCDEFG
BCDEFG
CDEFG
DEFG
EFG
FG
G

This is array 'a'.

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.

Am I missing something basic here? Any explanations would be of great help.

A: Since you're incrementing pB before you call puts(pB) in the loop, you're only seeing the part of strB starting from the current value of pB.
Change your loop to:
while(*pA!='\0') {
    *pB++ = *pA++;
    puts(strB);
}

and you'll see the entire string with the intermediate changes after each step.

A: You are increment pB pointer before printing pB. Could you modify your while like below?
while(*pA!='\0') {

    *pB = *pA++;

    puts(pB);

    pB++;

}


text:
Q: Navigate to a new page in React? Not SPA Recently started using React and I have an issue that is perhaps very basic.
I simply want to click a button and get taken to a new page. I.e go from login screen to the home screen. It seems that all the answers I find online recommend using react-router but that seems to be for Single Page Applications? I want to use actual new pages when navigating.
I have my login function
 login = () => {
       //I want to go to another page
    }

and on my button
<button type="button" class="btn btn-primary" onClick={() => this.login()}>Sign in</button>

I guess the problem is that I only have one HTML file (see file structure below), and I would need to have an html file each for every page?

Is there any way to do this, or is SPA the way to go with React?


text:
Q: State In Modal Bottom Sheet in Flutter I would like to know why the state of the below radio buttons change post selection whenever the keyboard appears upon clicking on the title textfield. Here's how it goes:
The Radio Button named Self comes pre-selected when the ModalBottomSheet first comes up. I now select Personal. Also, by default, the Work button also comes pre-selected.

The moment the keyboard appears, everything gets back to their original state.

openDialog(BuildContext context) {
//final themeProvider = Provider.of<ThemeProvider>(context);
showModalBottomSheet(
    shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(10.0))),
    isScrollControlled: true,
    // backgroundColor: Colors.grey[800],
    backgroundColor: Theme.of(context).colorScheme.onSurfaceVariant,
    // backgroundColor: Colors.red,
    context: context,
    builder: (context) {
      // bool _show = true;
      int? _radioValue = 0;
      int? _managerValue = 0;
      String? assignedName;

      // void _handleRadioValueChange(value) {
      //   print('RADIO VALUEEEEEEEE: $value');
      // }

      final themeProvider = Provider.of<ThemeProvider>(context);
      return StatefulBuilder(builder: (context, setState) {
        return Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                      .......
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Radio(
                                  fillColor: (themeProvider.darkTheme)
                                      ? MaterialStateProperty.resolveWith<
                                          Color>((states) {
                                          if (states.contains(
                                              MaterialState.disabled)) {
                                            return Colors.black;
                                          }
                                          return Colors.white;
                                        })
                                      : MaterialStateProperty.resolveWith<
                                          Color>((states) {
                                          if (states.contains(
                                              MaterialState.disabled)) {
                                            return Colors.black;
                                          }
                                          return Colors.black;
                                        }),
                                  value: 0,
                                  groupValue: _managerValue,
                                  onChanged: (value) {
                                    setState(() {
                                      _managerValue = 0;
                                    });
                                    print("radiofirst" +
                                        value.toString() +
                                        "radiovalue" +
                                        _managerValue.toString());
                                  },
                                ),
                                Row(
                                  children: [
                                    Icon(
                                      Icons.person,
                                      color: Theme.of(context).accentColor,
                                    ),
                                    SizedBox(
                                      width:
                                          SizeVariables.getWidth(context) *
                                              0.007,
                                    ),
                                    const Text(
                                      'Self',
                                      style: TextStyle(fontSize: 16.0),
                                    ),
                                  ],
                                ),
                                SizedBox(
                                    width: SizeVariables.getWidth(context) *
                                        0.028),
                                Radio(
                                  fillColor: (themeProvider.darkTheme)
                                      ? MaterialStateProperty.resolveWith<
                                          Color>((states) {
                                          if (states.contains(
                                              MaterialState.disabled)) {
                                            return Colors.black;
                                          }
                                          return Colors.white;
                                        })
                                      : MaterialStateProperty.resolveWith<
                                          Color>((states) {
                                          if (states.contains(
                                              MaterialState.disabled)) {
                                            return Colors.black;
                                          }
                                          return Colors.black;
                                        }),
                                  value: 1,
                                  groupValue: _managerValue,
                                  onChanged: (value) {
                                    setState(() {
                                      _managerValue = 1;
                                    });
                                    print("radiosecond " +
                                        value.toString() +
                                        "radiovalue " +
                                        _managerValue.toString());
                                  },
                                ),
                                Row(
                                  children: [
                                    Icon(
                                      Icons.group,
                                      color: Theme.of(context).accentColor,
                                    ),
                                    SizedBox(
                                      width:
                                          SizeVariables.getWidth(context) *
                                              0.007,
                                    ),
                                    const Text(
                                      'Assign To',
                                      style: TextStyle(
                                        fontSize: 16.0,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            _managerValue == 0
                                ? Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.start,
                                    children: [
                                      Radio(
                                        fillColor: (themeProvider.darkTheme)
                                            ? MaterialStateProperty
                                                .resolveWith<Color>(
                                                    (states) {
                                                if (states.contains(
                                                    MaterialState
                                                        .disabled)) {
                                                  return Colors.black;
                                                }
                                                return Colors.white;
                                              })
                                            : MaterialStateProperty
                                                .resolveWith<Color>(
                                                    (states) {
                                                if (states.contains(
                                                    MaterialState
                                                        .disabled)) {
                                                  return Colors.black;
                                                }
                                                return Colors.black;
                                              }),
                                        value: 0,
                                        groupValue: _radioValue,
                                        onChanged: (value) {
                                          setState(() {
                                            _radioValue = 0;                       //Work
                                          });
                                          print("radiofirst" +
                                              value.toString() +
                                              "radiovalue" +
                                              _radioValue.toString());
                                        },
                                      ),
                                      Row(
                                        children: [
                                          Icon(
                                            Icons.work,
                                            color: Theme.of(context)
                                                .accentColor,
                                          ),
                                          SizedBox(
                                            width: SizeVariables.getWidth(
                                                    context) *
                                                0.007,
                                          ),
                                          const Text(
                                            'Work',
                                            style:
                                                TextStyle(fontSize: 16.0),
                                          ),
                                        ],
                                      ),
                                      Radio(
                                        fillColor: (themeProvider.darkTheme)
                                            ? MaterialStateProperty
                                                .resolveWith<Color>(
                                                    (states) {
                                                if (states.contains(
                                                    MaterialState
                                                        .disabled)) {
                                                  return Colors.black;
                                                }
                                                return Colors.white;
                                              })
                                            : MaterialStateProperty
                                                .resolveWith<Color>(
                                                    (states) {
                                                if (states.contains(
                                                    MaterialState
                                                        .disabled)) {
                                                  return Colors.black;
                                                }
                                                return Colors.black;
                                              }),
                                        value: 1,
                                        groupValue: _radioValue,
                                        onChanged: (value) {
                                          setState(() {
                                            _radioValue = 1;              //Personal
                                          });
                                          print("radiosecond " +
                                              value.toString() +
                                              "radiovalue " +
                                              _radioValue.toString());
                                        },
                                      ),
                                      Row(
                                        children: [
                                          Icon(
                                            Icons.person,
                                            color: Theme.of(context)
                                                .accentColor,
                                          ),
                                          SizedBox(
                                            width: SizeVariables.getWidth(
                                                    context) *
                                                0.007,
                                          ),
                                          const Text(
                                            'Personal',
                                            style: TextStyle(
                                              fontSize: 16.0,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  )
                                : Row(),
                          ],
                        ),
                      ),
                    ),
              Form(
                key: _key1,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Container(
                    //   height: SizeVariables.getHeight(context) * 0.1,
                    //   width: double.infinity,
                    //   color: Theme.of(context).colorScheme.onSurfaceVariant,
                    // ),
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 10.0, vertical: 20.0),
                      child: TextFormField(
                        controller: _taskTitle,
                        cursorColor: Colors.white,
                        // controller: taskController,
                        // maxLines: 5,
                        style: Theme.of(context).textTheme.bodyText1,
                        decoration: InputDecoration(
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.amber,
                            ),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          // border: new OutlineInputBorder(
                          //   borderSide: new BorderSide(color: Colors.amber),
                          // ),
                          label: Text(
                            "Task Name",
                            style: Theme.of(context).textTheme.bodyText1!,
                          ),
                          labelStyle: Theme.of(context).textTheme.bodyText1,
                          //border: InputBorder.none,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      });
    }

A: Flutter rebuilds the whole widget when keyboard appears or disappears. So you should use StatefulWidget or other state management like Bloc to have
      int? _radioValue = 0;
      int? _managerValue = 0;
      String? assignedName;

For quick fix, just create new StatefulWidget and move all your implementation here.
Edited
I created new widget here called YourWidget, you can use for further.
openDialog(BuildContext context) {
//final themeProvider = Provider.of<ThemeProvider>(context);
  showModalBottomSheet(
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(10.0))),
      isScrollControlled: true,
      // backgroundColor: Colors.grey[800],
      backgroundColor: Theme
          .of(context)
          .colorScheme
          .onSurfaceVariant,
      // backgroundColor: Colors.red,
      context: context,
      builder: (context) {
        // bool _show = true;

        // void _handleRadioValueChange(value) {
        //   print('RADIO VALUEEEEEEEE: $value');
        // }

        return const YourWidget();
      });
}

class YourWidget extends StatefulWidget {
  const YourWidget({Key? key}) : super(key: key);

  @override
  State<YourWidget> createState() => _YourWidgetState();
}

class _YourWidgetState extends State<YourWidget> {
  int? _radioValue = 0;
  int? _managerValue = 0;
  String? assignedName;

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);
    return Padding(
      padding: EdgeInsets.only(
        bottom: MediaQuery
            .of(context)
            .viewInsets
            .bottom,
      ),
      child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              //.......
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Radio(
                        fillColor: (themeProvider.darkTheme)
                            ? MaterialStateProperty.resolveWith<
                            Color>((states) {
                          if (states.contains(
                              MaterialState.disabled)) {
                            return Colors.black;
                          }
                          return Colors.white;
                        })
                            : MaterialStateProperty.resolveWith<
                            Color>((states) {
                          if (states.contains(
                              MaterialState.disabled)) {
                            return Colors.black;
                          }
                          return Colors.black;
                        }),
                        value: 0,
                        groupValue: _managerValue,
                        onChanged: (value) {
                          setState(() {
                            _managerValue = 0;
                          });
                          print("radiofirst" +
                              value.toString() +
                              "radiovalue" +
                              _managerValue.toString());
                        },
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.person,
                            color: Theme
                                .of(context)
                                .accentColor,
                          ),
                          SizedBox(
                            width:
                            SizeVariables.getWidth(context) *
                                0.007,
                          ),
                          const Text(
                            'Self',
                            style: TextStyle(fontSize: 16.0),
                          ),
                        ],
                      ),
                      SizedBox(
                          width: SizeVariables.getWidth(context) *
                              0.028),
                      Radio(
                        fillColor: (themeProvider.darkTheme)
                            ? MaterialStateProperty.resolveWith<
                            Color>((states) {
                          if (states.contains(
                              MaterialState.disabled)) {
                            return Colors.black;
                          }
                          return Colors.white;
                        })
                            : MaterialStateProperty.resolveWith<
                            Color>((states) {
                          if (states.contains(
                              MaterialState.disabled)) {
                            return Colors.black;
                          }
                          return Colors.black;
                        }),
                        value: 1,
                        groupValue: _managerValue,
                        onChanged: (value) {
                          setState(() {
                            _managerValue = 1;
                          });
                          print("radiosecond " +
                              value.toString() +
                              "radiovalue " +
                              _managerValue.toString());
                        },
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.group,
                            color: Theme
                                .of(context)
                                .accentColor,
                          ),
                          SizedBox(
                            width:
                            SizeVariables.getWidth(context) *
                                0.007,
                          ),
                          const Text(
                            'Assign To',
                            style: TextStyle(
                              fontSize: 16.0,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  _managerValue == 0
                      ? Row(
                    mainAxisAlignment:
                    MainAxisAlignment.start,
                    children: [
                      Radio(
                        fillColor: (themeProvider.darkTheme)
                            ? MaterialStateProperty
                            .resolveWith<Color>(
                                (states) {
                              if (states.contains(
                                  MaterialState
                                      .disabled)) {
                                return Colors.black;
                              }
                              return Colors.white;
                            })
                            : MaterialStateProperty
                            .resolveWith<Color>(
                                (states) {
                              if (states.contains(
                                  MaterialState
                                      .disabled)) {
                                return Colors.black;
                              }
                              return Colors.black;
                            }),
                        value: 0,
                        groupValue: _radioValue,
                        onChanged: (value) {
                          setState(() {
                            _radioValue = 0; //Work
                          });
                          print("radiofirst" +
                              value.toString() +
                              "radiovalue" +
                              _radioValue.toString());
                        },
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.work,
                            color: Theme
                                .of(context)
                                .accentColor,
                          ),
                          SizedBox(
                            width: SizeVariables.getWidth(
                                context) *
                                0.007,
                          ),
                          const Text(
                            'Work',
                            style:
                            TextStyle(fontSize: 16.0),
                          ),
                        ],
                      ),
                      Radio(
                        fillColor: (themeProvider.darkTheme)
                            ? MaterialStateProperty
                            .resolveWith<Color>(
                                (states) {
                              if (states.contains(
                                  MaterialState
                                      .disabled)) {
                                return Colors.black;
                              }
                              return Colors.white;
                            })
                            : MaterialStateProperty
                            .resolveWith<Color>(
                                (states) {
                              if (states.contains(
                                  MaterialState
                                      .disabled)) {
                                return Colors.black;
                              }
                              return Colors.black;
                            }),
                        value: 1,
                        groupValue: _radioValue,
                        onChanged: (value) {
                          setState(() {
                            _radioValue = 1; //Personal
                          });
                          print("radiosecond " +
                              value.toString() +
                              "radiovalue " +
                              _radioValue.toString());
                        },
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.person,
                            color: Theme
                                .of(context)
                                .accentColor,
                          ),
                          SizedBox(
                            width: SizeVariables.getWidth(
                                context) *
                                0.007,
                          ),
                          const Text(
                            'Personal',
                            style: TextStyle(
                              fontSize: 16.0,
                            ),
                          ),
                        ],
                      ),
                    ],
                  )
                      : Row(),
                ],
              ),
            ),

            Form(
              key: _key1,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Container(
                  //   height: SizeVariables.getHeight(context) * 0.1,
                  //   width: double.infinity,
                  //   color: Theme.of(context).colorScheme.onSurfaceVariant,
                  // ),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 10.0, vertical: 20.0),
                    child: TextFormField(
                      controller: _taskTitle,
                      cursorColor: Colors.white,
                      // controller: taskController,
                      // maxLines: 5,
                      style: Theme
                          .of(context)
                          .textTheme
                          .bodyText1,
                      decoration: InputDecoration(
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.amber,
                          ),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        // border: new OutlineInputBorder(
                        //   borderSide: new BorderSide(color: Colors.amber),
                        // ),
                        label: Text(
                          "Task Name",
                          style: Theme
                              .of(context)
                              .textTheme
                              .bodyText1!,
                        ),
                        labelStyle: Theme
                            .of(context)
                            .textTheme
                            .bodyText1,
                        //border: InputBorder.none,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ]),
    );
  }
}