text:
Q: Login component/route showing below activatedRoute after Logging in due to BrowserAnimationsModule I can't quite seem to be able to figure this one out yet. I have logged in as a user. I have narrowed this down a bit, but I am relying on BrowserAnimationsModule as a dependency because of Angular Material. But if I remove the import it doesn't seem to have this problem and loads normally.
Here is my function call I will just navigate to the new route when I receive the response.
login() {
  this.authService.login()
  .then((res) => {
      this.router.navigate(['home'])
    })
  .catch((err) => console.log(err));
}

Like so, but I can't figure out what is causing the login page to still appear below my home Component. app.component.html looks like this and is only holding the router outlet.
<router-outlet></router-outlet>

Here is my app.routing.ts file
import { Routes, RouterModule } from '@angular/router';

import {
  LoginComponent,
  HomeComponent
} from './_components/index';

import { AuthGuard } from './_guards/auth.guard';

let appRoutes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'home',
    canActivate: [AuthGuard],
    component: HomeComponent
  }
];

export const AppRoutes = RouterModule.forRoot(appRoutes);

platform-browser.js:380 Router Event: NavigationStart
platform-browser.js:367 NavigationStart(id: 1, url: '/home')
platform-browser.js:367 NavigationStart {id: 1, url: "/home"}
core.js:3660 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
platform-browser.js:380 Router Event: RoutesRecognized
platform-browser.js:367 RoutesRecognized(id: 1, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:367 RoutesRecognized {id: 1, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
platform-browser.js:380 Router Event: GuardsCheckStart
platform-browser.js:367 GuardsCheckStart(id: 1, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:367 GuardsCheckStart {id: 1, url: "/home", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ChildActivationStart
platform-browser.js:367 ChildActivationStart(path: '')
platform-browser.js:367 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ActivationStart
platform-browser.js:367 ActivationStart(path: 'home')
platform-browser.js:367 ActivationStart {snapshot: ActivatedRouteSnapshot}
auth.service.ts:37 Observable {_isScalar: false, source: Observable, operator: ObserveOnOperator}
auth.service.ts:39 Observable {_isScalar: false, source: Observable, operator: ObserveOnOperator}
auth.service.ts:37 Observable {_isScalar: false, source: Observable, operator: ObserveOnOperator}
auth.service.ts:39 Observable {_isScalar: false, source: Observable, operator: ObserveOnOperator}
auth.guard.ts:16 false
platform-browser.js:380 Router Event: GuardsCheckEnd
platform-browser.js:367 GuardsCheckEnd(id: 1, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } , shouldActivate: false)
platform-browser.js:367 GuardsCheckEnd {id: 1, url: "/home", urlAfterRedirects: UrlTree, state: RouterStateSnapshot, shouldActivate: false}
platform-browser.js:380 Router Event: NavigationCancel
platform-browser.js:367 NavigationCancel(id: 1, url: '/home')
platform-browser.js:367 NavigationCancel {id: 1, url: "/home", reason: ""}
platform-browser.js:380 Router Event: NavigationStart
platform-browser.js:367 NavigationStart(id: 2, url: '/login')
platform-browser.js:367 NavigationStart {id: 2, url: "/login"}
platform-browser.js:380 Router Event: RoutesRecognized
platform-browser.js:367 RoutesRecognized(id: 2, url: '/login', urlAfterRedirects: '/login', state: Route(url:'', path:'') { Route(url:'login', path:'login') } )
platform-browser.js:367 RoutesRecognized {id: 2, url: "/login", urlAfterRedirects: "/login", state: RouterStateSnapshot}
platform-browser.js:380 Router Event: GuardsCheckStart
platform-browser.js:367 GuardsCheckStart(id: 2, url: '/login', urlAfterRedirects: '/login', state: Route(url:'', path:'') { Route(url:'login', path:'login') } )
platform-browser.js:367 GuardsCheckStart {id: 2, url: "/login", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ChildActivationStart
platform-browser.js:367 ChildActivationStart(path: '')
platform-browser.js:367 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ActivationStart
platform-browser.js:367 ActivationStart(path: 'login')
platform-browser.js:367 ActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: GuardsCheckEnd
platform-browser.js:367 GuardsCheckEnd(id: 2, url: '/login', urlAfterRedirects: '/login', state: Route(url:'', path:'') { Route(url:'login', path:'login') } , shouldActivate: true)
platform-browser.js:367 GuardsCheckEnd {id: 2, url: "/login", urlAfterRedirects: UrlTree, state: RouterStateSnapshot, shouldActivate: true}
platform-browser.js:380 Router Event: ResolveStart
platform-browser.js:367 ResolveStart(id: 2, url: '/login', urlAfterRedirects: '/login', state: Route(url:'', path:'') { Route(url:'login', path:'login') } )
platform-browser.js:367 ResolveStart {id: 2, url: "/login", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ResolveEnd
platform-browser.js:367 ResolveEnd(id: 2, url: '/login', urlAfterRedirects: '/login', state: Route(url:'', path:'') { Route(url:'login', path:'login') } )
platform-browser.js:367 ResolveEnd {id: 2, url: "/login", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ActivationEnd
platform-browser.js:367 ActivationEnd(path: 'login')
platform-browser.js:367 ActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ChildActivationEnd
platform-browser.js:367 ChildActivationEnd(path: '')
platform-browser.js:367 ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: NavigationEnd
platform-browser.js:367 NavigationEnd(id: 2, url: '/login', urlAfterRedirects: '/login')
platform-browser.js:367 NavigationEnd {id: 2, url: "/login", urlAfterRedirects: "/login"}
auth.service.ts:20 Bk {A: Array(0), G: "AIzaSyD-_kTu95MSLLNWEUbNYQZ8SXduvxgCH7g", o: "[DEFAULT]", w: "time-clock-mkteagle.firebaseapp.com", c: Ch, …}
platform-browser.js:380 Router Event: NavigationStart
platform-browser.js:367 NavigationStart(id: 3, url: '/home')
platform-browser.js:367 NavigationStart {id: 3, url: "/home"}
platform-browser.js:380 Router Event: RoutesRecognized
platform-browser.js:367 RoutesRecognized(id: 3, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:367 RoutesRecognized {id: 3, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
platform-browser.js:380 Router Event: GuardsCheckStart
platform-browser.js:367 GuardsCheckStart(id: 3, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:367 GuardsCheckStart {id: 3, url: "/home", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ChildActivationStart
platform-browser.js:367 ChildActivationStart(path: '')
platform-browser.js:367 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ActivationStart
platform-browser.js:367 ActivationStart(path: 'home')
platform-browser.js:367 ActivationStart {snapshot: ActivatedRouteSnapshot}
auth.service.ts:37 Observable {_isScalar: false, source: Observable, operator: ObserveOnOperator}
auth.service.ts:42 Observable {_isScalar: false, source: Observable, operator: ObserveOnOperator}
auth.guard.ts:12 logged in
platform-browser.js:380 Router Event: GuardsCheckEnd
platform-browser.js:367 GuardsCheckEnd(id: 3, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } , shouldActivate: true)
platform-browser.js:367 GuardsCheckEnd {id: 3, url: "/home", urlAfterRedirects: UrlTree, state: RouterStateSnapshot, shouldActivate: true}
platform-browser.js:380 Router Event: ResolveStart
platform-browser.js:367 ResolveStart(id: 3, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:367 ResolveStart {id: 3, url: "/home", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ResolveEnd
platform-browser.js:367 ResolveEnd(id: 3, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
platform-browser.js:367 ResolveEnd {id: 3, url: "/home", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ActivationEnd
platform-browser.js:367 ActivationEnd(path: 'home')
platform-browser.js:367 ActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ChildActivationEnd
platform-browser.js:367 ChildActivationEnd(path: '')
platform-browser.js:367 ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: NavigationEnd
platform-browser.js:367 NavigationEnd(id: 3, url: '/home', urlAfterRedirects: '/home')
platform-browser.js:367 NavigationEnd {id: 3, url: "/home", urlAfterRedirects: "/home"}

While I myself can't make sense of this tracing, or find something going on. I thought it might be helpful to help in diagnosing. I still think this has to do with the @angular/animations that Material is depending on, somehow.

A: I got this to work by explicitly telling NgZone to run. It appears Angular has problems catching unhandled exceptions
login() {
    this.auth.login()
    .then((res) => {
      this.zone.run(() => { this.router.navigate(['/home']); });
      })
    .catch((err) => console.log(err));
}


text:
Q: Make a Start page to my game Java I've been working on a version of a Tetris game and I tried to make a start page. I figured working with 2 panels will do fine but once I press the button the game doesn't run. Here is a piece of the code, where I implemented the panels.
Any ideas what I did wrong and how I should have done it?
public class Tetris extends JFrame
    {

        JLabel statusbar;
        private JPanel panel1=new JPanel();
        private JPanel panel2=new JPanel();
        public Tetris()
        {

            setResizable(false);
            setSize(200, 400);
            setTitle("Tetris");
            setDefaultCloseOperation(EXIT_ON_CLOSE);

            //setLayout(new FlowLayout());

            statusbar = new JLabel(" 0");
            JButton startButton = new JButton("START");

            panel1.add(startButton);

            panel2.add(statusbar, BorderLayout.SOUTH);
            Board board = new Board(this);
            board.addKeyListener(new TAdapter(board));
            panel2.add(board);

            startButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent arg0) {

                    add(panel2);
                    panel1.setVisible(false);

                }
            });

            add(panel1);
            //board.start();

       }

A: Try to add 'revalidate' to your event handler. It should help, I guess.
startButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent arg0) {

        add(panel2);
        panel1.setVisible(false);
        revalidate();

 }

});
By the way, if you are not forced to use Swing, I would advice you to use a modern JavaFX. Swing is not being developed by Oracle anymore.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inconvertible types; cannot cast 'androidx.fragment.app.Fragment' to 'com.google.ar.sceneform.ux.ArFragment' I am getting error on this line.
arCam = (ArFragment) getSupportFragmentManager().findFragmentByTag("arCameraArea");

And also getting error as unused fragment and compilation error xml file.
<fragment
    android:id="@+id/arCameraArea"
    android:name="com.google.ar.sceneform.ux.ArFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />`

I am trying to create an app that has a AR feature.


text:
Q: Step through MonoGame source code Is there a way to step through MonoGame source code while debugging (like with the .NET Framework) without having to compile MonoGame myself? I am using Visual Studio 2013.

A: No.  Visual Studio requires a successful compilation to enable stepping through code.


text:
Q: How do you filter by custom attribute in GetCandy? How do you filter by custom attribute in GetCandy?
I'm trying to filter search results on a GetCandy website, currently, I am using the API like so:
/api/v1/search?brand=hasbro&type=product

but it seems to still be giving me back all the results, am I missing something?

A: It looks like the query string is correct, for a custom attribute to be filterable you need to make sure it's got filterable checked in the attributes table.
Also, when you make changes to attributes you may need to re-run
php artisan candy:search:index

Just because there are potential changes to the index mapping and currently with Elasticsearch you can't update this on an existing index.


text:
Q: Append new column to existing table using SAS I have a do loop in which I do calculation on new variable and results are stored as additional column, this column-s (at each iteration) should be attached to the output table defined by macro.
Here on SO something similar has been asked but the answer is not acceptable, the last answer is not compatible with sas command but very close, getting incomplete script with following:
    proc sql;
         update &outlib..&out.
         set var._iqr = b.&var._iqr
         from &outlib..&out. as a
         left join cal_resul as b
         on a.id_client=b.id_client
         and a.reference_date=b.reference_date;
    quit;

Here is my attempt which works but very slow:
    proc sql; create table &outlib..&out. as select * from &inlib..&in.; quit; /* the input is as a basis for output table */
    proc sql; alter table &outlib..&out. add &var._iqr numeric; quit; /* create empty column to be filled at each iteration */

    proc sql;
         update &outlib..&out. as a
         set &var._iqr=(select b.&var._iqr from cal_resul as b
         where a.id_client=b.id_client
         and a.reference_date=b.reference_date
         and a.data_source=b.data_source);
    quit;

Attempt 2:
This is somewhat faster:
    proc sort data=cal_resul; by id_client reference_date data_source; run;

    data &outlib..&out.;
         update &outlib..&out. cal_resul;
         by id_client reference_date data_source;
    run;

Simple left join (adding new column into existing table is way faster) but with left join I did not figure out how I can update (always retain the same dataset) the &outlib..&out. at each iteration. Many thanks for any help;

A: If you want to ADD a variable to a dataset you will have to make a new dataset.  (Your ALTER TABLE statement will create a new dataset and copy over all of the observations.)
Looks like your data has three key variables.  So use those in merging the new data to the old.
For example to make a new variable in HAVE named EXAMPLE_IQR using the variable EXAMPLE in the dataset NEW you could use code like this.  I have used macro variables to show how you might use those macro variables as the parameters to a macro.  It sounds like you don't want the process to add new observations to the existing dataset so I have added a check for that using the IN= dataset option.
%let base=work.have;
%let indata=work.new;
%let var=example;

data &base ;
   merge &base(in=inbase)
         &indata(keep=id_client reference_date data_source &var
                 rename=(&var=&var._iqr)
                )
   ;
   by id_client reference_date data_source;
   if inbase;
run;


text:
Q: How to implement an optional property? I want to set up a property only if requested explicitly. As this property will involve extra computation time, I want it initialized with None and only initializing if a calling function requests to do so.
For example:
class File:
    def __init__(self, filename, content):
         self.filename = filename
         self.content = content
         self.hash = None or self.get_hash()

    def get_hash():
          '''do some hashing there'''

I have seen some property of that kind but don't know how this could work trigger the function by calling:
my_file = File('text.txt', 'Hello there')
my_file.hash

A: By providing .hash with a property getter, you can create exactly the behaviour you want. The actual value of hash will be 'hidden' as ._hash which is a common practice in Python:
class File:
    def __init__(self, filename, content):
         self.filename = filename
         self.content = content
         self._hash = None

    @property
    def hash(self):
          if self._hash is None:
              # do some hashing here
              self._hash = 'some hash'
          return self._hash

f = File('myfile', 'some content')
print(f.hash)

Of course, you could also have other conditions when you need the hash to be recalculated, it doesn't have to be if self._hash is None. And you could also just reset the hash when it needs to be recalculated. For example, perhaps your hash changes when .content changes:
class File:
    def __init__(self, filename, content):
         self.filename = filename
         self._content = content
         self._hash = None

    @property
    def hash(self):
          if self._hash is None:
              # do some hashing here
              self._hash = f'some hash based on {self._content}'
          return self._hash

    @property
    def content(self):
          return self.content

    @content.setter
    def content(self, value):
          self._content = value
          self._hash = None

f = File('myfile', 'some content')
print(f.hash)
f.content = 'changed content'
print(f.hash)

A: Try passing it as a parameter while creating the Object.
Check if the below code is suitable for you:
class File:
    def __init__(self, filename, content, request_hash=False):
         self.filename = filename
         self.content = content
         self.hash = self.get_hash() if request_hash else None

    def get_hash():
          '''do some hashing there'''

my_file = File('text.txt', 'Hello there') #No Hash is generated
my_file = File('text.txt', 'Hello there', True) #Hash will be generated


text:
Q: JSch - command not being sent to shell? I'm working on a project to restart something within a screen on a remote server using JSch... however I'm running into an issue. It will send the first 2 commands 100% of the time, but the 3rd command will only be sent some of the time. Any help would be appreciated.
public static void stopServer(String name, String ip, String passwd)
{
    try {
        Session session = Main.jsch.getSession("user",ip,22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(passwd);
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.connect();
        ChannelShell cs = (ChannelShell) channel;
        cs.setPty(true);
        DataInputStream dataIn = new DataInputStream(channel.getInputStream());
        PrintStream dataOut = new PrintStream(channel.getOutputStream());
        dataOut.println("screen -x "+name);
        dataOut.flush();
        dataOut.println("stop");
        dataOut.flush();
        String line = dataIn.readLine();
        System.out.println(line);
        while(true) {
            line = dataIn.readLine();
            System.out.println(line);
            if(line.contains("\"quit\""))
            {
                break;
            }
        }
        TimeUnit.SECONDS.sleep(1);
        dataOut.println("quit");
        dataOut.flush();
        System.out.println("Shutdown");
        dataIn.close();
        dataOut.close();
        channel.disconnect();
        session.disconnect();

    }catch(Exception e)
    {
        e.printStackTrace();
    }
}

This sends the screen -x 'name' and the stop 100% of the time from what I've seen, but the 'quit' command only actually gets sent/understood by the console a fraction of the time. Any help would be appreciated!!

A: I managed to fix  this in a way that doesn't use the shell channel, but it is reliable enough that it works:
//Start EXEC
            ChannelExec ce = (ChannelExec) session.openChannel("exec");
            ce.setCommand("screen -S " + name + " -X stuff 'quit\n'");
            ce.setInputStream(null);
            ce.setErrStream(System.err);
            InputStream in=ce.getInputStream();

            ce.connect();

            byte[] tmp=new byte[1024];
            while(true){
                while(in.available()>0){
                    int i=in.read(tmp, 0, 1024);
                    if(i<0)break;
                    //System.out.print(new String(tmp, 0, i));
                }
                if(ce.isClosed()){
                    if(in.available()>0) continue;
                    //System.out.println("exit-status: "+ce.getExitStatus());
                    break;
                }
                try{Thread.sleep(1000);}catch(Exception ee){}
            }
            ce.disconnect();
            //STOP EXEC

As much as this doesn't work along the original vein of the problem, it fixed it for me.

A: *

*If an exception gets thrown sometime before the "quit" command gets sent, then the quit command will never get sent.

*If the while loop never breaks, then that will prevent the "quit"
command from being sent too.


text:
Q: Wicket FileUpload for large files effectively by slicing the file and uploading asynchronously Hi I am working on large file upload component. I am looking for efficient way of uploading large files. I googled and found few does by slicing the large files and uploading asynchronously. I am looking for the similar implementation in Wicket. Is there any similar way in Wicket to achieve the same?

A: You could look into integrating Wicket with jQuery FileUpload which supports asynchronous and chunked uploads.
There is a tutorial and a working example on GitHub. I have used this solution for multi-file upload in two projects and it works great.


text:
Q: error XA0000: Could not determine API level for $(TargetFrameworkVersion) of 'v7.1' While building the solution , xamarin throws this error.
error XA0000: Could not determine API level for $(TargetFrameworkVersion) of 'v7.1'.
How to solve this error?

A: Try upgrading your version of Xamarin, or the Android SDK to the latest version. Seems that it can't find what version 7.1 is.


text:
Q: Bootstrap 4 alert box close button not aligned I'm using bootstrap and I currently have an alert box:

  Delete Album! Select the album(s) you want to delete.
  <button type="button" class="close" aria-label="Close" onclick="return handleOptions($('#btnDeleteAlbum'));">
    ×
  </button>

The close button is not aligned vertically. Here is how it shows up.

How can I make the button aligned? I tried using the
 and it kind of worked but I was wondering if there is a better approach.

A: Override the padding-top property of the button like the following:

.close {
    padding-top: .60rem !important;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  Delete Album! Select the album(s) you want to delete.
  <button type="button" class="close" aria-label="Close" onclick="return handleOptions($('#btnDeleteAlbum'));">
    ×
  </button>

A: You can remove the class alert-dismissable because it's not necessary to make the alert dismissable, this class only has styling purposes. You can use flexbox to align the close-button vertically:

    This is a success alert ...
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>

Important is to use data-bs-dismiss="alert" attribute.


text:
Q: JSoup to extract particular block from multiple block I'm new to JSoup and my question here is how do I extract particular text from multiple blocks that share the same class and attributes?
For example here I want to extract the information on 3rd row of the HTML. How do I specified on my JSoup code to extract the information on 3rd row?

                Active Stats

                User's local time
                Oct 22 2013, 07:23 PM

                Total Cumulative Posts
                4

( 0 posts per day / 0.00% of total forum posts )

A: Use the CSS-selector syntax to specify what row to select.
Element e = doc.select("tr:eq(2) td.row2").first();
System.out.println(e.text());

will result in

Total Cumulative Posts

A tip is to at least look through the Jsoup documentation before asking questions.
All this can easily be found in the API.
Jsoup - Use selector syntax


text:
Q: Why does this IAM policy have a syntax error? I'm new to/learning about AWS, currently using LocalStack in lieu of real live AWS.
arn:aws:s3:::my-bucket/path/to/foo.json is a valid S3 key to an object in a newly-created S3 bucket. Because the bucket is newly created and pristine, other than the one file upload, nothing in it is externally accessible. I'm trying to learn about IAM by working through examples to create a policy that grants read-access to parts of a S3 bucket.
I created the following policy file based on this example from the AWS CLI reference:
$ cat ./policy
{
  "Version": "2020-04-27",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
          "s3:Get*",
          "s3:List*"
      ],
      "Resource": [
          "arn:aws:s3:::my-bucket/path/to/foo.json"
      ]
    }
  ]
}

From the same linked example, I tried to create my policy with this command, which failed:
$ aws --endpoint-url=http://localhost:4593 iam create-policy --policy-name my-bucket-policy --policy-document file://policy

An error occurred (MalformedPolicyDocument) when calling the CreatePolicy operation: Syntax errors in policy.

Why did this command fail, or is there a way I can get a more-descriptive error message?
(policy is a file in the cwd where I execute the aws CLI command)
By my reading, the error message implies malformed JSON, but linters like https://jsonlint.com/ indicate that the text is valid JSON. Moreover, the changes from the source example are minimal and would appear reasonable: "Version" is changed to today's date, and the "Resource" ARN is changed to what's relevant to me.

A: There is incorrect version given. It should be: "2012-10-17"
Edit: Mistake with Principle. See comments. Principle is required for resource-based policies:

Principal (Required in only some circumstances) – If you create a resource-based policy, you must indicate the account, user, role, or federated user to which you would like to allow or deny access. If you are creating an IAM permissions policy to attach to a user or role, you cannot include this element. The principal is implied as that user or role.


text:
Q: How to position an image in a div for different dimensions? I am trying to stick a picture to right of the screen with a fixed height. But this way the dimensions do not fit right in different browsers. I cannot upload pictures, so it's quite hard to describe...
#profile_pic {
    float: right;
    z-index: 99;
    position: absolute;
    right: 0;
    top: 12;
}

#profile_pic img {
    width: 12.73em;
}

I tried it with %, but it also didn't work this way...

A: Try
#profile_pic {
    float: right;
    z-index: 99;
    position: absolute;
    right: 0;
    top: 12;
    height: 100%
}

#profile_pic img {
    width: 12.73em;
    height: 100%;
}

DEMO

A: remove float:right... it will not work on absolute position, set the height and width, can you also post your HTML


text:
Q: What exactly the three inverted commas (''') stands for in Python In this question, I would like to know whether there is a convention for the ''' triple inverted commas in Python.
In one, online course I came across the idea that, don't use triple inverted commas because it uses to denote documentation of the program.
In another, online course I came across the idea that, use it when necessary. Then you can use single or double inverted commas as you like.
print('''This is exactly what he said, "I'm your lover."''')

What are your thoughts on this? Is there any specific convention?
Thank you very much in advance for the help.

A: Triple quotes are usually used for multi-line comments (or documentation as you mentioned!) by convention.
The interpreter will not ignore them as comments though.

Triple quotes, according to official Python documentation are docstrings, or multi-line docstrings and are not considered comments. Anything inside triple quotes is read by the interpreter. When the interpreter encounters the hash symbol, it ignores everything after that. That is what a comment is defined to be.

Read more!

A: Whatever this """ """ or this ''' ''' in Python you use it for multiline strings
For example:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""

As you can see if I want to assign a long line of text. Then I'll use them.


text:
Q: Forecast Multiple output for N days using LSTM I am trying to create a LSTM model that can take multiple input features and Forecast those multiple features for N days
Eg I want to give 4 Features as input for 103 days not I want to forecast those 4 features for next 5 days
input features = [A1,B1,C1,D1],[A2,B2,C2,D2],....,  [A103,B103,C103,D103]
output = [A104,B104,C104,D105],...,[A109,B109,C109,D109]
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(data)

train = scaled_data[:13813,:]
test = scaled_data[13813:,:]

def create_dataset(dataset,size):
    X = []
    y = []
    for i in range(len(dataset)-size-1):
        a = dataset[i:(i+size),:]
        a = dataset[i:(i+size),:]
        X.append(a)
        y.append(dataset[i+size])
    return np.array(X),np.array(y)
##535 is number of data i want to use to forecast the feature

X_test, y_test = create_dataset(test,535)
X_train,y_train = create_dataset(train,535)

##X_train and y_train shape  ((13277, 535, 17), (13277, 17))
##X_test and y_test shape  ((2917, 535, 17), (2917, 17))

model_2 = Sequential()
model_2.add(tf.keras.layers.LSTM(units=128,return_sequences=True,input_shape = (X_train.shape[1],17)))
model_2.add(tf.keras.layers.LSTM(units=64,return_sequences=True))
model_2.add(tf.keras.layers.LSTM(units=50,return_sequences=True))
model_2.add(tf.keras.layers.LSTM(units=32))
model_2.add(tf.keras.layers.Dense(units=17,activation='linear'))
model_2.summary()

model_2.compile(loss='MSE',optimizer='adam')
model_history_2 = model_2.fit(X_train,y_train,validation_data=(X_test,y_test),callbacks=[early_stopping],epochs = 5,batch_size=150)

##But after this I am unable understand how to create a sliding window to predict the next 103 records.


text:
Q: Don't print customizer styles when no setting has been used I'm adding some options to a theme through my plugin, I want to change this theme styles and I'm almost there... Now I need to know how I can hide the <style> tag when no settings are changed (all default not used),
function myplugin_customize_css(){
?>
 <style>
     h2 {color:<?php echo get_theme_mod('myplugin_h2_color'); ?>;}
     h3 {color:<?php echo get_theme_mod('myplugin_h3_color'); ?>;}
     p {
        color:<?php echo get_theme_mod('myplugin_p_color'); ?>;
        font-size:<?php echo get_theme_mod('myplugin_p_size'); ?>;
     }
     // more & more of these!
 </style>
<?php
}
add_action( 'wp_head', 'myplugin_customize_css');

I can do if() statements here but it feels too much, what other ways I can do this... not like this:
function myplugin_customize_css(){
    if (get_theme_mod('myplugin_h2_color') != ''
        || get_theme_mod('myplugin_h3_color') !=''
        || get_theme_mod('myplugin_p_color') !=''
        || get_theme_mod('myplugin_p_size') !='' ) {
        ?>
        <style>
            // if get_theme_mod('myplugin_h2_color') != ''
             h2 {color:<?php echo get_theme_mod('myplugin_h2_color'); ?>;}

             // if get_theme_mod('myplugin_h3_color') != ''
             h3 {color:<?php echo get_theme_mod('myplugin_h3_color'); ?>;}

             // if get_theme_mod('myplugin_p_color') !=''
             //    && get_theme_mod('myplugin_p_size') !=''
             p {
                // if get_theme_mod('myplugin_p_color') !=''
                color:<?php echo get_theme_mod('myplugin_p_color'); ?>;
                // if get_theme_mod('myplugin_p_size') !=''
                font-size:<?php echo get_theme_mod('myplugin_p_size'); ?>;
             }
             // more & more of these!
         </style>
         <?php
    }
}
add_action( 'wp_head', 'myplugin_customize_css');

A: There's not really any trick, you need to check all the values. You can save a little space though, by omitting the != '', which is redundant:
if (
    get_theme_mod( 'myplugin_h2_color' ) ||
    get_theme_mod( 'myplugin_h3_color' ) ||
    get_theme_mod( 'myplugin_p_color' ) ||
    get_theme_mod( 'myplugin_p_size' )
) {

However, it's possible to save Customiser settings into a single array. So if you register your settings with names like:
$wp_customize->add_setting( 'myplugin[h2_color]' );
$wp_customize->add_setting( 'myplugin[h3_color]' );
$wp_customize->add_setting( 'myplugin[p_color]' );
$wp_customize->add_setting( 'myplugin[p_size]' );

Then you can retrieve the values in an array like:
get_theme_mod( 'myplugin' );

If you do this, then you could use array_filter() to remove any empty values, and check if the resulting array is empty. If it isn't, then at least one of the the settings has a value:
$styles = get_theme_mod( 'myplugin' );

if ( ! empty( array_filter( $styles ) ) ) {
    echo '<style>';

    if ( ! empty( $styles['h2_color'] ) {
        printf( 'h2 { color: %s; }', $styles['h2_color'] );
    }

    // etc.

    echo '</style>';
}


text:
Q: Strange behavior of child windows in MDI I have MDI form and few child forms. When I maximize one of the forms all others are also maximized. For example from child form i want to activate another child form. Previously first child form is maximized. New opened form is also maximized even is set to be normal size. How to stop that? Is it some kind of bug?

A: This is standard documented behavior.
There can be a possible workaround. When the maximized form is closed, you can tie to the FormClosing event and set the child form's WindowState to "FormWindowState.Normal"
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
 this.WindowState = FormWindowState.Normal;
}

Try this and see if it works for you.


text:
Q: How to create semi-auto open collapsible in CSS/JavaScript I have collapsibles inside collapsibles, and I'd like for all the levels beneath the first one to open up whenever the first level is click on.
So for example, if I click on Act 1, I'd like everything under Scene 1 and 2, including all the Snippets, to open up whenever Act 1 is clicked.
Here is my attempt at the basic coding, which functions in itself. I just need to figure out how to incorporate the added level of difficulty.

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}
.collapsible {
  background-color: #0486C1;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active,
.collapsible:hover {
  background-color: #254062;
}

.collapsible::after {
  content: '\002B';
  margin-left: 5px;
}

.collapsible.active::after {
  content: "\2212";
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #E2E2E2;
  transition: max-height 0.2s ease-out;
}

p {
  color: #000000;
}
<button type="button" class="collapsible">Act 1</button>

  <button type="button" class="collapsible">Scene 1</button>

    <button type="button" class="collapsible">Snippet 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <button type="button" class="collapsible">Scene 2</button>

    <button type="button" class="collapsible">Snippet 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

A: You can do the following:

const collapsibles = document.querySelectorAll(".collapsible");
collapsibles.forEach(collapsible => {
  collapsible.addEventListener("click", function() {
    open(this);
    const children = this.nextElementSibling.querySelectorAll('.collapsible');
    children.forEach(open);
  });
});

function open(element) {
  element.classList.toggle("active");
  var content = element.nextElementSibling;
  if (content.style.display === "block") {
    content.style.display = "none";
  } else {
    content.style.display = "block";
  }
}
.collapsible {
  background-color: #0486C1;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active,
.collapsible:hover {
  background-color: #254062;
}

.collapsible::after {
  content: '\002B';
  margin-left: 5px;
}

.collapsible.active::after {
  content: "\2212";
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #E2E2E2;
  transition: max-height 0.2s ease-out;
}

p {
  color: #000000;
}
<button type="button" class="collapsible">Act 1</button>

  <button type="button" class="collapsible">Scene 1</button>

    <button type="button" class="collapsible">Snippet 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <button type="button" class="collapsible">Scene 2</button>

    <button type="button" class="collapsible">Snippet 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

A: My suggested approach would be the following:

// I've chosen to use 'let' to declare variables, since they're more easily
// scoped than variables declared with 'var';
// here we retrieve the elements with the class-name of 'collapsible'
// using the CSS selector passed to the document.querySelectorAll() method:
let collapsibles = document.querySelectorAll('.collapsible'),

  // declaring the toggleContent function using Arrow syntax, since we
  // don't need to use the 'this' argument within the function body;
  // we pass in the Event Object (supplied automatically by the
  // EventTarget.addEventListener() call later):
  toggleContent = (evt) => {
    // here we retrieve the element that was clicked, and which triggered
    // the event-listener:
    let clicked = evt.target,

        // we retrieve the next-element sibling:
        content = clicked.nextElementSibling,

        // and find the appropriate display-type for
        // for that neighbouring element; here we use
        // a conditional ('ternary') operator to determine
        // what the approapriate display-type should be
        // based on its current display:
        displayType = content.style.display === 'block' ? 'none' : 'block';

    // updating the display of the content:
    content.style.display = displayType;

    // finding all '.content' elements within the content
    // element-node using Element.querySelectorAll(), and then
    // iterating over those elements using NodeList.prototype.forEach():
    content.querySelectorAll('.content').forEach(
      // here the first argument of the anonymous Arrow function
      // refers to the current '.content' element-node of
      // the NodeList over which we're iterating; this is passed
      // to the function-body, in which we update its display
      // to be the same as the 'outer' content:
      (currentContent) => currentContent.style.display = displayType
    );
  };

// here we iterate over the NodeList of '.collapsible' elements using
// NodeList.prototype.forEach() along with an anonymous Arrow function:
collapsibles.forEach(
  // 'collapseButton' refers to the current element of the NodeList
  // of element-nodes; within the function body this is used to
  // bind the toggleContent() function (note the deliberate lack of
  // parentheses) to the 'click' event of the '.collapsible' element:
  (collapseButton) => collapseButton.addEventListener('click', toggleContent)
);
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font-size: 1rem;
  line-height: 1.5;
  margin: 0;
  padding: 0;
}

.collapsible {
  background-color: #0486C1;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active,
.collapsible:hover {
  background-color: #254062;
}

.collapsible::after {
  content: '\002B';
  margin-left: 5px;
}

.collapsible.active::after {
  content: "\2212";
}

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #E2E2E2;
  transition: max-height 0.2s ease-out;
}

p {
  color: #000000;
}
<button type="button" class="collapsible">Act 1</button>

  <button type="button" class="collapsible">Scene 1</button>

    <button type="button" class="collapsible">Snippet 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <button type="button" class="collapsible">Scene 2</button>

    <button type="button" class="collapsible">Snippet 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button type="button" class="collapsible">Snippet 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

JS Fiddle demo.
References:

*

*Arrow function syntax.

*Conditional ("ternary") operator.

*document.querySelectorAll().

*Element.nextElementSibling.

*ElementCSSInlineStyle.style.

*Element.querySelectorAll().

*Event.target.

*let statement.

*NodeList.prototype.forEach().


text:
Q: How to swap characters in a string You are going to tell me this is easy, I know, but how do I simultaneously change all A into B, and all B into A, in a string, s.
s= s.Replace( 'A', 'B').Replace( 'B', 'A');

clearly doesn't quite work, so what is the right way?

A: Use Regex.Replace and a MatchEvaluator to do the job.  This will cope with strings longer than single characters, if A and B ever get more complex:
s = Regex.Replace(s, "A|B", (m) => m.Value == "A" ? "B" : "A");

A: You can use linq to replace the characters:
string s = "ABZBA";
var result= s.Select(x=> x == 'A' ? 'B' : (x=='B' ? 'A' : x)).ToArray();
s = new String(result);

Output:

BAZAB

A: Copying the string into StringBuilder and doing replacements character-by-character is one way of achieving this:
var s = new StringBuilder(originalString);
for (int i = 0 ; i != s.Length ; i++) {
    var ch = s.Characters[i];
    if (ch == 'A') { s.Characters[i] = 'B'; }
    else if (ch == 'B') { s.Characters[i] = 'A'; }
}
originalString = s.ToString();

If you wish to use Replace, and there is a character that is guaranteed to be absent from your string, you could do it in the same way that you do swaps with a temporary variable:
s= s.Replace( 'A', '~').Replace( 'B', 'A').Replace( '~', 'B');

The above assumes that ~ is not present in the original string.

A: Iterate through the characters of s and if you find A put B (and vice-versa).
StringBuilder newString = new StringBuilder(s.Length);
foreach(var ch in s)
{
    if (ch == 'A') newString.Append('B');
    else if (ch == 'B') newString.Append('A');
    else newString.Append(ch);
}

s = newString.ToString();

A: You can try this:
string s = "ABABAB";
char placeholder = '~';

//After this s is BABABA
s = s.Replace('A', placeholder).Replace('B', 'A').Replace(placeholder, 'B');

A: A solution to your problem could be this:
 string s = "AABB";
 var dict = new Dictionary<char, char> {{'A', 'B'}, {'B', 'A'}};

 s = new string(s.Select(c => dict.ContainsKey(c) ? dict[c] : c).ToArray());

This way you can replace all the characters that you want, just add the key/value pair to the dictionary

A: I ended up with this extension method:
string Swap( this string s, char a, char b, char unused)
{
    return s.Replace( a, unused).Replace( b, a).Replace( unused, b);
}

Then I changed it to:
string Swap( this string s, char a, char b)
{
    return new string( s.Select( ch => (ch == a) ? b :(ch == b) ? a : ch).ToArray());
}


text:
Q: Is it possible to control a PC through Python/Powershell using RDP or VNC? I'm writing a script to perform some actions (e.g: execute scripts, copy/paste/rename etc) on a remote machine. The remote machine only has RDP, VNC and FTP activated. I can perform all the above mentioned actions manually using a RDP/VNC viewer but I want to automate them. Initially I wrote my script in Python but I can change to Powershell if necessary. SSH would solve all the problems but unfortunately its not available on the remote machine.
I tried to connect through psexec but its been disabled.
Is it possible to control the remote machine through Python/Powershell using RDP/VNC?

A: Neither RDP or VNC supports this.
The best you can do is to RDP/VNC to the remote machine.
Copy your script over (if file-transer is disabled you can always open Notepad  on the remote and copy/paste the script content from your local PC to Notepad on the remote and save it there).
Then run your script remotely.


text:
Q: Copy file from windows remote server to GCS bucket using Airflow file_path = "\\wfs8-XXXXX\XXXX"
The files is on remote server path, I am using cloud composer to automate my data pipeline,
so How I will be able to copy the files from remote windows server to GCS bucket using composer ?
I tried to use LocalFilesystemToGCSOperator, but I am not able to provide any connection option to connect windows remote server, please advise
upload_file = LocalFilesystemToGCSOperator(
        task_id="upload_file",
        src=PATH_TO_UPLOAD_FILE,
        dst=DESTINATION_FILE_LOCATION,
        bucket=BUCKET_NAME,
    )

A: In this case you can use SFTPToGCSOperator operator, example :
copy_file_from_sftp_to_gcs = SFTPToGCSOperator(
    task_id="file-copy-sftp-to-gcs",
    sftp_conn_id="<your-connection>",
    source_path=f"{FILE_LOCAL_PATH}/{OBJECT_SRC_1}",
    destination_bucket=BUCKET_NAME,
)

You have to configure the sftp connection in Airflow, you can check this topic to have an example.


text:
Q: Maven и Eclipse - установка и настройка Скачала мавен (zip) с сайта, попыталась запустить jar - ничего не произошло. Как установить мавен и что делать с загадочным "прописать PATH"? Где найти пошаговое руководство по установке мавена, желательно со скринами и стрелочками, куда тыкать? (для чайников, которые это делают впервые и никогда раньше о таких финтах даже не слышали)
И как его впоследствии привязать к эклипсу?

A: Поддержка maven в Eclipse плагинами делается. И нет необходимости её отдельно ставить самому.

*

*Открываем Eclipse IDE.

*Жмём Help -> Install New Software...

*Жмём Add button.

*Вводим "M2Eclipse" и путь.
"http://download.eclipse.org/technology/m2e/releases".

*OK.

Или

*

*Открыть Eclipse.

*Help -> Eclipse Marketplace.

*Ищем по слову Maven.

*Жмём "Install" напротив "Maven Integration for Eclipse".

*Дальше по инструкции.

Если же вы, всё же, хотите установить Maven ручками, а потом использовать, то :

*

*m2e плагин поставить по инструкции выше.

*Устанавливаем Maven.

*Не забываем в PATH системы добавить путь до установки, чтоб можно было выполнять mvn -version и другие команды.

*В Eclipse выбрать Window->Preference->Maven->Installations и там Add нажать и указать путь до места, куда вы установили Maven.


text:
Q: CheckBox issues in JavaFX I am working on an assignment and I am using check boxes to convert my text from normal to bold, italics or both. However when I run my code, I get some errors saying my checkbox has no constructor that accepts strings when I checked on Oracle and there is a constructor that accepts strings, and check boxes cannot be converted to a nodes when I try to add them into my gridpanes when I think check boxes inherits the node properties naively. Here is my code. Thanks for any possible help.
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.geometry.*;
import javafx.scene.layout.*;
import javafx.scene.shape.*;
import javafx.scene.paint.*;
import java.util.*;
import javafx.scene.text.*;
import javafx.scene.control.*;
import java.lang.*;
import javafx.beans.binding.*;
import javafx.event.*;
//import javafx.scene.control.CheckBox;
//import javafx.scene.control.Button;

public class test extends Application{
  protected Text name = new Text(50, 50, "Hello World");

  protected BorderPane getPane() {
    BorderPane masterPane = new BorderPane();

    Pane textPane = new Pane();
    textPane.getChildren().add(name);
    //masterPane.setCenter(textPane);

    GridPane gridPane = new GridPane();
    gridPane.setPadding(new Insets(10));
    gridPane.setHgap(5);
    gridPane.setVgap(5);
    gridPane.add(textPane,0,0);
    GridPane.setHalignment(textPane, HPos.CENTER);
    GridPane.setValignment(textPane, VPos.CENTER);
    masterPane.setCenter(gridPane);

    // HBox buttonPane = new HBox(1000);
    Button upBtn = new Button("Up");
    Button downBtn = new Button("Down");
    GridPane buttonGridPane = new GridPane();
    buttonGridPane.add(upBtn,0,0);
    buttonGridPane.add(downBtn,1,0);
    buttonGridPane.setPadding(new Insets(10));
    buttonGridPane.setHgap(5);
    buttonGridPane.setVgap(5);
    buttonGridPane.setHalignment(upBtn, HPos.CENTER);
    buttonGridPane.setValignment(upBtn, VPos.CENTER);
    buttonGridPane.setHalignment(downBtn, HPos.CENTER);
    buttonGridPane.setValignment(downBtn, VPos.CENTER);
    // buttonPane.getChildren().addAll(upBtn, downBtn);
    // buttonPane.setAlignment(Pos.CENTER);
    buttonGridPane.setStyle("-fx-border-color: cyan");
    masterPane.setBottom(buttonGridPane);

    upBtn.setOnAction(e -> name.setY(name.getY() - 10));
    downBtn.setOnAction(e -> name.setY(name.getY() + 10));

    return masterPane;
  }

  protected StackPane setPane(){

    BorderPane newMasterPane = new BorderPane(getPane());
    GridPane gridPane = new GridPane();
    gridPane.setMinSize(1250, 500);
    gridPane.setMaxSize(1250, 500);
    StackPane root = new StackPane(gridPane);
    NumberBinding maxScale = Bindings.min(root.widthProperty().divide(1250), root.heightProperty().divide(500));
    gridPane.scaleXProperty().bind(maxScale);
    gridPane.scaleYProperty().bind(maxScale);
    gridPane.add(newMasterPane,0,0);

    return root;
  }

  @Override
   public void start(Stage primoStage) {

     Scene scene = new Scene(setPane(), 1250, 500);
     primoStage.setTitle("Assignment #7");
     primoStage.setScene(scene);
     primoStage.show();

   }

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

class CheckBox extends test {
  @Override
  protected BorderPane getPane() {
    BorderPane pane = super.getPane();

    Font fontBoldItalic = Font.font("Comic Sans MS",
      FontWeight.BOLD, FontPosture.ITALIC, 20);
    Font fontBold = Font.font("Comic Sans MS",
      FontWeight.BOLD, FontPosture.REGULAR, 20);
    Font fontItalic = Font.font("Comic Sans MS",
      FontWeight.NORMAL, FontPosture.ITALIC, 20);
    Font fontNormal = Font.font("Comic Sans MS",
      FontWeight.NORMAL, FontPosture.REGULAR, 20);

      name.setFont(fontNormal);

      GridPane fontGridPane = new GridPane();
      fontGridPane.setPadding(new Insets(10));
      fontGridPane.setHgap(5);
      fontGridPane.setVgap(5);
      fontGridPane.setStyle("-fx-border-color: cyan");

      // VBox checkPane = new VBox(20);
      // checkPane.setPadding(new Insets(5, 5, 5, 5));
      // checkPane.setStyle("-fx-border-color: cyan");
      CheckBox chkBold = new CheckBox("Bold");
      CheckBox chkItalic = new CheckBox("Italic");
      // checkPane.getChildren().addAll(chkBold, chkItalic);
      // pane.setLeft(checkPane);
      fontGridPane.add(chkBold,0,0);
      fontGridPane.add(chkItalic,0,1);
      fontGridPane.setHalignment(chkBold, HPos.CENTER);
      fontGridPane.setValignment(chkBold, VPos.CENTER);
      fontGridPane.setHalignment(chkItalic, HPos.CENTER);
      fontGridPane.setValignment(chkItalic, VPos.CENTER);

      EventHandler<ActionEvent> handler = e -> {
        if (chkBold.isSelected() && chkItalic.isSelected()) {
          text.setFont(fontBoldItalic); // Both check boxes checked
        }
        else if (chkBold.isSelected()) {
          text.setFont(fontBold); // The Bold check box checked
        }
        else if (chkItalic.isSelected()) {
          text.setFont(fontItalic); // The Italic check box checked
        }
        else {
          text.setFont(fontNormal); // Both check boxes unchecked
        }
      };

      chkBold.setOnAction(handler);
      chkItalic.setOnAction(handler);

      return pane;
  }
}

A: Your own CheckBox class is used, not javafx.scene.control.CheckBox.
You can still refer to javafx.scene.control.CheckBox using the fully quualified name, e.g.
javafx.scene.control.CheckBox chkBold = new javafx.scene.control.CheckBox("Bold");

but maybe you should reconsider naming your class CheckBox, since this name is misleading anyways (It's a application using CheckBoxes, not a CheckBox).


text:
Q: Share config in cluster How I can share config file in cluster with is on failover mode?
I don't want to edit artemis-user.properties, artemis-role.properties, and broker.xml files on every server in the cluster.
Cluster settings:

*

*security-enabled: true

*persistence-enabled : true

*paging-directory, bindings-directory, journal-directory, large-messages-directory used from master server

Security settings like this:
<security-setting match="clusterQueue">
    <permission type="createNonDurableQueue" roles="amq"/>
    <permission type="deleteNonDurableQueue" roles="amq"/>
    <permission type="createDurableQueue" roles="amq"/>
    <permission type="deleteDurableQueue" roles="amq"/>
    <permission type="createAddress" roles="amq"/>
    <permission type="deleteAddress" roles="amq"/>
    <permission type="consume" roles="amq"/>
    <permission type="browse" roles="amq"/>
    <permission type="send" roles="amq"/>
    <!-- we need this otherwise ./artemis data imp wouldn't work -->
    <permission type="manage" roles="amq"/>
</security-setting>

It is possible?

A: ActiveMQ Artemis doesn't provide any automated way to share configuration between cluster members. However, since all the configuration you referenced is text-based it should be fairly simple to replicate it to your brokers with standard tools and/or infrastructure. For example, you could use SCP to copy the files, create a shared NFS mount with them, etc.
Even in a homogeneous cluster it's common to have small differences in the configuration files (e.g. for the cluster-connection, an acceptor, etc.). In that case you can use system property substitution (which is referenced in the documentation) to pull out the bits from each broker which need to be customized and then set those in artemis.profile, e.g.:
JAVA_ARGS="$JAVA_ARGS -DmyAcceptor=tcp://192.168.1.10:61616"

Then reference that system property in your broker.xml, e.g.:
<acceptor name="netty-acceptor">${myAcceptor}</acceptor>

In this way you can have the same broker.xml shared among all the brokers but each can have their own artemis.profile with the unique values that each broker needs.


text:
Q: How to update all records in DynamoDB? I am new to nosql / DynamoDB.
I have a list of ~10 000 container-items records, which is updated every 6 hours:
[
   { containerId: '1a3z5', items: ['B2a3, Z324, D339, M413'] },
   { containerId: '42as1', items: ['YY23, K132'] },
   ...
]

(primary key = containerId)

*

*Is it viable to just delete the table, and recreate with new values?

*Or should I loop through every item of the new list, and conditionally update/write/delete the current DynamoDB records (using batchwrite)?

A: For this scenario batch update is better approach. You have 2 cases:

*

*If you need to update only certain records than batch update is more efficient. You can scan the whole table and iterate thought the records and only update certain records.

*If you need to update all the records every 6 hours batch update will be more efficient, because if you drop the table and recreate table, that also means you have to recreate indexes and this is not a very fast process. And after you recreate table you still have to do the inserts and in the meantime you have to keep all the records in another database or in-memory.

One scenario where deleting the whole table is a good approach if you need to delete all the data from the table with thousands or more records, than its much faster to recreate table, than delete all the records though API.
And one more suggestion have you considered alternatives, because your problem does not look like a good use-case for DynamoDB. For example MongoDB and Cassandra support update by query out of the box.

A: If the update touches some but not all existing items and if partial update of 'items' is possible then you have no choice but to do a per record operation.  And this would be true even with a more capable database.
You can perhaps speed it up by retrieving only the existing containerIds first so based on that set you know which to do update versus insert on.  Alternately you can do a batch retrieve by ids using the ids from the set of updates and which every ones do not return a result are the ones you have to insert and the ones where you do are the ones to update.


text:
Q: virt-manager kvm modules are not available Fedora 16 latest updates running on a HP Mini 210 with an Intel(R) Atom(TM) CPU N550 @ 1.50GHz.
sudo yum groupinstall Virtualization

Only installed virt-viewer
sudo yum groupinstall Virtualization Platform
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Warning: Group virtualization does not have any packages.
Warning: Group Platform does not exist.
No packages in any requested group available to install or update

After trying the above I am still getting the same message.
I have installed the virt-manager. When I try and create a new virtual machine I get the following warning:

KVM is not available. This may mean the KVM package is not installed, or the KVM kernel modules are not loaded. Your virtual machines may perform poorly.

I have installed the following package:
qemu-kvm-0.15.1-4.fc16.x86_66

And loaded the kvm module:
lsmod | grep kvm
kvm                   406993  0

Not sure what package I am expected to install, or what kvm kernel module is not loaded?
Normally I use virtualbox without any problem. But I wanted to try and see if this virt-manager performs better.

A: Also in my case (Fedora 16 32 bits) I've installed everything ...also I've activated bios visualization vt-x... cpu is compatible .. but the same error (KVM is not available. This may mean the KVM package is not installed,or the KVM kernel modules are not loaded. Your virtual machines may perform poorly.)
Finaly I've executed manualy modprobe kvm_intel and all done.
[root@monsterm ~]# grep vmx /proc/cpuinfo
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm ida dts tpr_shadow vnmi flexpriority
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm ida dts tpr_shadow vnmi flexpriority

lshw | grep vmx
[root@monsterm ~]# lshw | grep vmx
          capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe x86-64 constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm ida tpr_shadow vnmi flexpriority cpufreq

# check kvm kernel modules
modprobe kvm_intel
lsmod | grep kvm

[root@monsterm ~]# lsmod | grep kvm*
kvm_intel             126289  0
kvm                   356309  1 kvm_intel

A: try following:
sudo yum groupinstall Virtualization
sudo yum groupinstall Virtualization Platform
sudo yum groupinstall Virtualization Client
sudo yum groupinstall Virtualization Tools

make sure to reboot after that installation is complete
you can check service is started by issuing following command (it should return service is started)
service libvirtd status

A: There are more packages required than just qemu-kvm.
This will get you what you need.
yum groupinstall Virtualization
Edit:
To answer your question about your CPU and virtualization, run
$ egrep '^flags.*(vmx|svm)' /proc/cpuinfo

If NOTHING is printed, your system does not support the relevant extensions. You can still use the QEMU/KVM, but the emulator will fall back to software virtualization, which is FAR FAR slower.
You should not have to manually load the kvm kernel module. Just start the libvirt service.
service libvirtd start
Now when you run lsmod | grep kvm, you should see
kvm
kvm_intel

If you don't see both modules, kvm is not installed correctly.

A: I had the same problem on VMware guest machine, so I checked at VMware Hardware Setting in Processor there's called Virtualization engine. It already sets Automatically but turns out that Automatically actually blocking my virtualization profile on VMware guest so I changed preferred mode to Intel VT-x/EPT or AMD-V/RVI and Voila problem solved !!

A: I experienced same problem and after read a lot of guides of how to configure KVM, almost 24h later I realized that is necessary to Enable the Virtualization on BIOS... Uffff!!!


text:
Q: Given a free module with a well-defined finite rank, are all of its linearly independent sets finite? Given a free left $R$-module $M$ over a ring $R$ with Invariant Basis Number, does every linearly independent subset $L \subseteq M$ have cardinality at most $n$?
Over integral domains like $R=\mathbb Z$, the answer is yes, by an adaptation of Gaussian elimination. But I don't know if it's true in general.


text:
Q: C# How to Move A Circle Along a Rectangle Path I need to move a point along a rectangle path at the command of a button. I want it to start at the upper right corner of the rectangle path, but I am not sure how to get it to go all the way around the path and stop at the original point. The screen refreshes at the speed provided by the user in an input box. Thank you in advance!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
namespace Assignment_2
{

    public partial class Form1 : Form
    {
        private const int formwidth = 1280;
        private const int formheight = 720;
        private const int ball_a_radius = 10;
        private const int horizontaladjustment = 8;
        private const double ball_a_distance_moved_per_refresh = 1.6;
        private double ball_a_real_coord_x = 515;
        private double ball_a_real_coord_y = 40;
        private int ball_a_int_coord_x;
        private int ball_a_int_coord_y;

        private const double graphicrefreshrate = 30.0;

        private static System.Timers.Timer graphic_area_refresh_clock = new System.Timers.Timer();

        private static System.Timers.Timer ball_a_control_clock = new System.Timers.Timer();
        private bool ball_a_clock_active = false;

        public double speed = 0;

        public Form1()
        {

            InitializeComponent();
            ball_a_int_coord_x = (int)(ball_a_real_coord_x);
            ball_a_int_coord_y = (int)(ball_a_real_coord_y);
            System.Console.WriteLine("Initial coordinates: ball_a_int_coord_x = {0}. ball_a_int_coord_y = {1}.",
                               ball_a_int_coord_x, ball_a_int_coord_y);

            graphic_area_refresh_clock.Enabled = false;
            graphic_area_refresh_clock.Elapsed += new ElapsedEventHandler(Updatedisplay);

            ball_a_control_clock.Enabled = false;
            ball_a_control_clock.Elapsed += new ElapsedEventHandler(Updateballa);

            Startgraphicclock(graphicrefreshrate);
            Startballaclock(speed);
        }
        public class NumericTextBox : TextBox
        {
        }

            private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel2_Paint_1(object sender, PaintEventArgs e)
        {
            //Create pen
            Pen blackPen = new Pen(Color.Black, 1);

            //Create rectangle
            Rectangle rect = new Rectangle(125, 50, 400, 400);

            //Draw rectangle to screen
            e.Graphics.DrawRectangle(blackPen, rect);

            Graphics graph = e.Graphics;
            graph.FillEllipse(Brushes.Green, ball_a_int_coord_x, ball_a_int_coord_y, 2 * ball_a_radius, 2 * ball_a_radius);
            base.OnPaint(e);
        }

        public void button7_Click(object sender, EventArgs e)
        {
           speed = Convert.ToInt32(textBox3.Text);

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Startgraphicclock(double refreshrate)
        {
            double elapsedtimebetweentics;
            if (refreshrate < 1.0) refreshrate = 1.0;
            elapsedtimebetweentics = 1000.0 / refreshrate;
            graphic_area_refresh_clock.Interval = (int)System.Math.Round(elapsedtimebetweentics);
            graphic_area_refresh_clock.Enabled = true;
        }

        protected void Startballaclock(double updaterate)
        {
            double elapsedtimebetweenballmoves;
            if (updaterate < 1.0) updaterate = 1.0;
            elapsedtimebetweenballmoves = 1000.0 / updaterate;
            ball_a_control_clock.Interval = (int)System.Math.Round(elapsedtimebetweenballmoves);
            ball_a_control_clock.Enabled = true;
            ball_a_clock_active = true;
        }

        protected void Updatedisplay(System.Object sender, ElapsedEventArgs evt)
        {
            Invalidate();
            if (!(ball_a_clock_active))
            {
                graphic_area_refresh_clock.Enabled = false;
                System.Console.WriteLine("The graphical area is no longer refreshing.  You may close the window.");
            }
        }

        protected void Updateballa(System.Object sender, ElapsedEventArgs evt)
        {
            ball_a_real_coord_x = ball_a_real_coord_x - 5;

            ball_a_real_coord_y = ball_a_real_coord_y - 5;
            ball_a_int_coord_x = (int)System.Math.Round(ball_a_real_coord_x);
            ball_a_int_coord_y = (int)System.Math.Round(ball_a_real_coord_y);

            if (ball_a_int_coord_x >= formwidth || ball_a_int_coord_y + 2 * ball_a_radius <= 0 || ball_a_int_coord_y >= formheight)
            {
                ball_a_clock_active = false;
                ball_a_control_clock.Enabled = false;
                System.Console.WriteLine("The clock controlling ball a has stopped.");
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            ball_a_control_clock.Enabled = true;

        }
    }

}

A: I have a more straightforward way to move a circle. Your code is too long for me to read. See if you like this!
If I were you, I would use a PictureBox. I first create an image of a circle, and then put that image in the PictureBox. Then you can just use a timer to change the position of the PictureBox.
You should set the Interval of the timer to 33 ms, which is roughly 30 fps. This is how you would programme the timer:
Keep a counter to indicate how many pixels the circle has moved. Let's say you want it to move in a 100px x 50px rectangular path.
For every 33ms,
    If the counter is less than 100,
        increase the X position and the counter by 1,
    if the counter is between 101 and 150,
        increase the Y position and the counter by 1,
    if the counter is between 151 and 250,
        decrease the X position by 1 and increment the counter
    if the counter is between 251 and 300,
        decrease the Y position by 1 and increment the counter
    if the counter is greater than 300,
        stop the timer

I really don't like drawing stuff on the screen with the OnPaint event. I mean, you are moving a ball! People think of this as changing the x and y positions of a ball, not as deleting the ball at the previous position and drawing it in the new position. Changing the position of the picture box just makes LOTS more sense, don't you think so?


text:
Q: can't get the same result after changing from activity to fragment I started using a navigation drawer, for that i started using fragments.. after I've changed this activity and moved the code with slight changes to a new fragment .. I get an error on onOptionsItemSelected method inside the fragment.. where should I put the url if it is not the right place to put it?? !!
this is FoodView.java Activity
public class FoodView extends AppCompatActivity {

private ListView lvFood;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_food_view);

    lvFood = (ListView) findViewById(R.id.lvFood);
}

    public class JSONTask extends AsyncTask<String, String, List<FoodModel>> {

        @Override
        protected List<FoodModel> doInBackground(String... params) {

            HttpURLConnection httpURLConnection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();

                InputStream inputStream = httpURLConnection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                String finalJson = buffer.toString();

                JSONArray parentArray = new JSONArray(finalJson);

                List<FoodModel> foodModelList = new ArrayList<>();

                for (int i = 0; i < parentArray.length(); i++) {
                    JSONObject finalObject = parentArray.getJSONObject(i);
                    FoodModel foodModel = new FoodModel();
                    foodModel.setFood(finalObject.optString("name"));
                    foodModel.setStatus(finalObject.optString("status"));
                    foodModel.setAmount(finalObject.optInt("amount"));
                    foodModel.setDescription(finalObject.optString("description"));
                    foodModel.setDate(finalObject.optInt("exDate"));

                    foodModelList.add(foodModel);
                }

                return foodModelList;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();

            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return new ArrayList<>();
        }

        @Override
        protected void onPostExecute(List<FoodModel> result) {
            super.onPostExecute(result);

            FoodAdapter adapter = new FoodAdapter(getApplicationContext(), R.layout.row, result);
            lvFood.setAdapter(adapter);

        }}

        public class FoodAdapter extends ArrayAdapter {

            private List<FoodModel> foodModelList;
            private int resource;
            private LayoutInflater inflater;

            public FoodAdapter(Context context, int resource, List<FoodModel> objects) {
                super(context, resource, objects);
                foodModelList = objects;
                this.resource = resource;
                inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = inflater.inflate(resource, null);
                }

                ImageView ivIcon;
                TextView foodName, txt_amount, txt_desc, txt_date, txt_status;

                ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
                foodName = (TextView) convertView.findViewById(R.id.foodName);
                txt_amount = (TextView) convertView.findViewById(R.id.txt_amount);
                txt_desc = (TextView) convertView.findViewById(R.id.txt_desc);
               txt_status = (TextView) convertView.findViewById(R.id.txt_status);
                txt_date = (TextView) convertView.findViewById(R.id.txt_date);

                foodName.setText(foodModelList.get(position).getFood());
                txt_amount.setText("Amount: " + foodModelList.get(position).getAmount());
                txt_desc.setText(foodModelList.get(position).getDescription());
                txt_status.setText(foodModelList.get(position).getStatus());
                txt_date.setText("EX Date: " + foodModelList.get(position).getDate());

                return convertView;
            }
        }

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_refresh) {
        new JSONTask().execute("http://10.0.3.2/MySqlDemo/food.php");
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

this is FoodViewFragment.java Fragment
public class FoodViewFragment extends Fragment {
private ListView lvFood;
Context context = getActivity();

public FoodViewFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

     View v = inflater.inflate(R.layout.fragment_food_view, container, false);
    lvFood = (ListView)v. findViewById(R.id.lvFood);

    return v;
}

public class JSONTask extends AsyncTask<String, String, List<FoodModel>> {

    @Override
    protected List<FoodModel> doInBackground(String... params) {

        HttpURLConnection httpURLConnection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();

            InputStream inputStream = httpURLConnection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String finalJson = buffer.toString();

            JSONArray parentArray = new JSONArray(finalJson);

            List<FoodModel> foodModelList = new ArrayList<>();

            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);
                FoodModel foodModel = new FoodModel();
                foodModel.setFood(finalObject.optString("name"));
                foodModel.setStatus(finalObject.optString("status"));
                foodModel.setAmount(finalObject.optInt("amount"));
                foodModel.setDescription(finalObject.optString("description"));
                foodModel.setDate(finalObject.optInt("exDate"));

                foodModelList.add(foodModel);
            }

            return foodModelList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ArrayList<>();
    }

    @Override
    protected void onPostExecute(List<FoodModel> result) {
        super.onPostExecute(result);

        FoodViewFragment.FoodAdapter adapter = new FoodViewFragment.FoodAdapter(context, R.layout.row, result);
        lvFood.setAdapter(adapter);

    }}
public class FoodAdapter extends ArrayAdapter {

    private List<FoodModel> foodModelList;
    private int resource;
    private LayoutInflater inflater;

    public FoodAdapter(Context context, int resource, List<FoodModel> objects) {
        super(context, resource, objects);
        foodModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater)getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(resource, null);
        }

        ImageView ivIcon;
        TextView foodName, txt_amount, txt_desc, txt_date, txt_status;

        ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
        foodName = (TextView) convertView.findViewById(R.id.foodName);
        txt_amount = (TextView) convertView.findViewById(R.id.txt_amount);
        txt_desc = (TextView) convertView.findViewById(R.id.txt_desc);
        txt_status = (TextView) convertView.findViewById(R.id.txt_status);
        txt_date = (TextView) convertView.findViewById(R.id.txt_date);

        foodName.setText(foodModelList.get(position).getFood());
        txt_amount.setText("Amount: " + foodModelList.get(position).getAmount());
        txt_desc.setText(foodModelList.get(position).getDescription());
        txt_status.setText(foodModelList.get(position).getStatus());
        txt_date.setText("EX Date: " + foodModelList.get(position).getDate());

        return convertView;
    }
}

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_refresh) {
        new JSONTask().execute("http://10.0.3.2/MySqlDemo/food.php");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

this is a part of the code inside navigationDrawer.java class, I'm trying to runf nav_home item and show FoodViewFragmentActivity
 public boolean onNavigationItemSelected(MenuItem item) {

    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        setTitle("Food View");

       FoodViewFragment fragment = new FoodViewFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.content_frame,fragment, "fragment1");
        fragmentTransaction.commit();

    } else if (id == R.id.nav_food) {

    } else if (id == R.id.nav_money) {

    } else if (id == R.id.nav_settings) {

    } else if (id == R.id.nav_about) {

    } else if (id == R.id.nav_notifications) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

A: Keep these methods in your activity, remove them from your fragment
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.navigation_drawer, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

         if (id == R.id.action_refresh) {
        // add this line in your activity

      ((FoodViewFragment)selectedFragment).yourServerCallMethodInFragment();
            return true;
        }

return super.onOptionsItemSelected(item);
}

Maintain current Fragment at Activity level
private Fragment selectedFragment;

And get reference of selected fragment in
 public boolean onNavigationItemSelected(MenuItem item) {

// Handle navigation view item clicks here.
int id = item.getItemId();

if (id == R.id.nav_home) {
    setTitle("Food View");

   selectedFragment = new FoodViewFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content_frame,selectedFragment, "fragment1");
    fragmentTransaction.commit();

} else if (id == R.id.nav_food) {

} else if (id == R.id.nav_money) {

} else if (id == R.id.nav_settings) {

} else if (id == R.id.nav_about) {

} else if (id == R.id.nav_notifications) {

}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

Now your fragment would have this method
public void yourServerCallMethodInFragment(){
 new JSONTask().execute("http://10.0.3.2/MySqlDemo/food.php");
}


text:
Q: ETL From Sql Server bak file to Postgres or other open source solution Is there anyway to get table definitions and data from a Sql Server bak file to an open source solution?

A: This functionality is not supported out of the box.  Why not restore the database backup to another server and script out the tables that you need?
If you really need to work with the backups as a database, there is only one product left on the market from Apex Software.
Red Gate used to have a product called virtual restore but it was discontinued a year ago.


text:
Q: Threading in selenium webdriver in Python I am trying to get used to Selenium WebDriver. By that, I am trying to login and do something on my targeted website. In the code, I tried to log in for 10 users. However, as expected, it isn't the best approach. My first concern is how to do it in better way and secondly, how to create threads at once for each user and start simultaneously.
# User threads
t1 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr1", "123456", True))
t2 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr2", "123456", True))
t3 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr3", "123456", True))
t4 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr4", "123456", True))
t5 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr5", "123456", True))
t6 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr6", "123456", True))
t7 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr7", "123456", True))
t8 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr8", "123456", True))
t9 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr9", "123456", True))
t10 = threading.Thread(target=user_qsinav_normal, args=("student@foo.com.tr10", "123456", True))

# Starting threads
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
t7.start()
t8.start()
t9.start()
t10.start()

I changed the code as follows:
# creating make up users in the function and return it as dict(email,pass)
users = number_of_users(6)

# logging in with users created before.
for user_email, user_passwoard in users.items():
    threading.Thread(target=user_qsinav_normal, args=(user_email, user_passwoard, True)).start()

A: I think to test the API, it is better to use requests or some other tools. You then can create multiple threads to test the login API easily.
Selenium side, not so nice with threading. If you surely need to test it using Selenium, I advise you do not use Thread. Instead, we should use Remote Testing using Selenium Grid.
You can install the Selenium Grid Docker from here: https://github.com/SeleniumHQ/docker-selenium
Create a grid (below example is 3 standalone browsers), you can create more ports if you want.
$ docker network create grid
$ docker run -d -p 4442-4444:4442-4444 --net grid --name selenium-hub selenium/hub:4.0.0-alpha-7-prerelease-20200921
$ docker run -d --net grid -e SE_EVENT_BUS_HOST=selenium-hub -e SE_EVENT_BUS_PUBLISH_PORT=4442 -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 -v /dev/shm:/dev/shm selenium/node-chrome:4.0.0-alpha-7-prerelease-20200921
$ docker run -d --net grid -e SE_EVENT_BUS_HOST=selenium-hub -e SE_EVENT_BUS_PUBLISH_PORT=4442 -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 -v /dev/shm:/dev/shm selenium/node-firefox:4.0.0-alpha-7-prerelease-20200921
$ docker run -d --net grid -e SE_EVENT_BUS_HOST=selenium-hub -e SE_EVENT_BUS_PUBLISH_PORT=4442 -e SE_EVENT_BUS_SUBSCRIBE_PORT=4443 -v /dev/shm:/dev/shm selenium/node-opera:4.0.0-alpha-7-prerelease-20200921

Then point your test to the ports:
from selenium import webdriver

firefox_options = webdriver.FirefoxOptions()
driver = webdriver.Remote(
    command_executor='http://localhost:4444/wd/hub',
    options=firefox_options
)
driver.get("http://www.google.com")
driver.quit()

You can build a small custom engine with "Thread" to run Selenium test on the hub. The hub will handle the testing for you, and it will respond back to your thread.


text:
Q: Load HTML Page In Textarea I've been trying to load a html document into a textarea when the page loads.
I know you can use the ajax load api in JQuery...
$("#siteloader").load('startup.html');

but if I try to load this into the textarea...
var mirror = $("#pageloader"),
    input = $("#pagecode");

input.val(mirror.load('startup.html'));

I get [object Object] which I figured wouldn't work, but thought I'd try it anyway as I just didn't know if it would work or not.
Any help on how to do this would be greatly appreciated.

A: try this
$(function () {
    function download_to_textbox(url, el) {
        $.get(url, null, function (data) {
            el.val(data);
        }, "text");
    }
    download_to_textbox("startup.html", $("#textareaID"));
});

A: I would suggest you to try this one:
input.val(mirror.load('startup.html').html());


text:
Q: Cannot see the current html file
*

*sync; echo 3 > /proc/sys/vm/drop_caches

*Cloudflare cache

*Digitalocean cdn cache

*lscache folder inside remove

although I have done all of the operations I mentioned above, I cannot see the current html file.
I also deleted the history of my computer.


text:
Q: Media query sass split by resolution Is there a way to strip down sass styles based on the media query resolution? Here is my sass file.I want to split it by blue300.css and blue480.css?
.red {

color: red;
}
@media only screen and (max-width: 300px) {
  .blue {
    color: red;
  }
}

.blue {
  color: blue;
}

@media only screen and (max-width: 480px) {
  .blue {
    margin: 10px;
  }
}

A: I think you are looking to implement something similar to Jake Archibald's approach to creating a seperate sass file for IE.
IE Friendly CSS with Sass
In your comment you mention creating stylesheets for different resolutions that don't support media queries.  I would advise against that and just create one default stylesheet for browsers with no media query support.

A: I recently wrote an npm module and a grunt plugin, wich separates a css file into media query files automatically. In this case it would create a separate css file for every found media query. This is the cli and this is the grunt plugin


text:
Q: How to configure web.config to support file handler I created a file browser control which open files on client machine itself, so I don't need to bother about file path
from my application I am not able to redirect page to
file:///C:/Program%20Files/Application/readme.txt

it works for
http://

how can I configure my application to support file handler.
Thanx

A: If you are trying to redirect to a local file. This is not possible without knowing quite a lot of information on the client machine - for example how do you know the directory structure of the client computer?
Response.Redirect tells the client (browser) where to redirect to. A file URL will be one that is on the client machine - you would need to know in advance that the file is there, that the user has permissions to view it etc...

Are you asking how to send a file from the server?
You can do this via Response.WriteFile.


text:
Q: Regex for no email and number (upto 5 digits allowed) and string can be added I want to apply validation that user can write string but cannot enter email id and number in continuous pattern upto 5 digits only.
I am trying following not working:
^[a-zA-Z][0-9]{0,5}$

Like if user write :

*

*hello 12345 is good --- > True,

*hello 134566 is bad ---- > false,

*hello  +32444 is bad  --- > false,

*hello 13233 is good , I have 12333 ---> true

thanks in advance

A: This should work for you:
^[A-z ,]*(([0-9]\s?){1,5})([A-z ,]*)(([A-z ,]+)(([0-9]\s?){1,5}))*$

Explanation:

*

*^ matches the beginning of the string

*[A-z ,]* matches the text before the number

*(([0-9]\s?){1,5}) matches the number with spaces in it

*([A-z ,]*) matches the text after the first number

*([A-z ,]+)(([0-9]\s?){1,5}) matches all other numbers with spaces in it and that ony, if ther ist text between the numbers

*$ matches the end of the string

https://regex101.com/r/EbKsZG/2/tests

A: I have used following regex as solution for this:
^([a-zA-Z,\s]+[0-9\s]{0,5})+$

And sometimes people enter number with space specially phone number for restrict them, I use function on Keyup event:
valid(){
    this.commmentValid=false; //condition to show or not on html page
    var count=0;
    // Remove space from starting and end of string
    var a = (this.commentData.comment).trim();
    // Split each string value and form an array
    var m = a.split("");
    var preVal;
    // console.log(m)
    m.forEach(el => {
      console.log(el);
      var d= el.match(/\d+/);
      //Check if value is digit
      if(d){
        //Store previous value
        preVal=el;
        count++;
        if(count>=6){
          // Run when find phone number with and without space
          this.commmentValid=true;
        }
      }
      //If find space
      else if(el == " "){
        if(preVal){
          count++;
        }
      }
      //Check if string is ok
      else{
        count =0;
        preVal=0;
      }
    });
  }