text:
Q: MEF composition using ImportMany and existing instances of composable parts I'm having the following problem:
When using the ImportMany attribute on MEF always at least one instance of an implementation of the IService interface will be created by MEF.
Since I'm having an existing instance already (simulated by creating one in the code below and adding it as a part to the composition batch), I only want to have this instance in my Services property of the ServiceHost instance. (And of course instances from other types having the same interface implementation ..)
But MEF always also creates a new instance and also pushes it to the Services property so that there are two instances - my own created one and one created by MEF.
How do I prevent MEF from creating an own instance?
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace TestConsole
{
    public interface IService
    {
        int InstanceId { get; }
    }

    public class Program
    {
        public static int counter;

        private static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost();

            DirectoryCatalog catalog = new DirectoryCatalog(".", "*.exe");
            CompositionContainer container = new CompositionContainer(catalog);
            CompositionBatch compositionBatch = new CompositionBatch();

            // create an existing instance
            TestService c = new TestService();
            ComposablePart part = AttributedModelServices.CreatePart(c);
            compositionBatch.AddPart(part);
            Console.WriteLine("existing instance: {0}", c.InstanceId);

            compositionBatch.AddPart(AttributedModelServices.CreatePart(host));

            container.Compose(compositionBatch);

            foreach (var service in host.Services)
            {
                Console.WriteLine(service.InstanceId);
            }
        }
    }

    public class ServiceHost
    {
        [ImportMany]
        public IService[] Services { get; set; }
    }

    [Export(typeof(IService))]
    public class TestService : IService
    {
        public TestService()
        {
            this.InstanceId = ++Program.counter;
        }

        public int InstanceId { get; private set; }
    }
}

Thank you ..
Bernie

A: So it's working as expected. It finds 2 instances, because you add two instances (one manually, one from DirectoryCatalog).
You have to make decision: Let MEF to manage your instances, or do it yourself.
If it is possible, remove [Export(typeof(IService))] and use AddExportedValue instead of parts, like this:
// create an existing instance
TestService c = new TestService();
compositionBatch.AddExportedValue<IService>(c);

In this case, you add your instance manually to the compositionBatch, and DirectoryCatalog cannot find this, cause of class has no [Exported] Attribute.


text:
Q: Cannot connect to websocket server using AHC-WS component in Apache Camel I'm using ACH-WS component in Apache Camel to connect to a websocket server using WSS (Slack's websocket server to be more precise). I have a route like this one:
from("ahc-wss://host")
  .log(...)
  .to(...)

When I init my app I see the following log:
Route: wss-inbound-event started and consuming from: Endpoint[ahc-wss://ms109.slack-msgs.com/websocket/....]

However it sounds like the connection to the server never happens. If I copy the URL string and use another websocket client it connects and immediately get some welcome messages. This is the proof that AHC-WS component never connected because the URL can only be used once according to Slack's documentation.
I wonder if I need to provide additional options to the component in order to work.

A: Looking at the code of the component it seems like it expects that you send a message first as the connection is established at that time. If you just create the consumer it won't connect to the URL.
To solve my issue what I did was to add a ping message to the Slack API one the app is started. That makes the endpoint connect to the server and starts receiving events.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a block for all non-root paths in nginx config? In a single page app behind nginx, I'd like all non-root paths to be handled by an upstream server:
upstream socket_nodes {
    server 127.0.0.1:5000;
}
server {

listen 80;

index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
 location whaeverelse {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://socket_nodes;
    }
}

What I've tried was to list all the whateverelse paths to a line like this:
location /(api|user|profile|about|login|logout|register) {...

Apart from being hackish, that did not work.
I have also tried some wildcard regexps like this:
location  ~ ^/[0-9a-z] {

or even more excessive ones:
location  ~ ^/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W) {

with no success.
So I'm wondering what is the idiomatic way to do so?


text:
Q: How Do I Fetch Name and Email using Facebook SDK I am using a TextView to show Name and Email of logged in facebook user, but i really don't know How do I fetch Name and Email ?
private void onSessionStateChange(Session session, SessionState state,
                                  Exception exception) {
    if (session != currentSession) {
        return;
    }

    if (state.isOpened()) {
        // Log in just happened.
        Toast.makeText(getApplicationContext(), "session opened",
                Toast.LENGTH_SHORT).show();
    } else if (state.isClosed()) {
        // Log out just happened. Update the UI.
        Toast.makeText(getApplicationContext(), "session closed",
                Toast.LENGTH_SHORT).show();
    }
}

A: You can get the name and email as below:
// use their Facebook info
    JSONObject json = Util.parseJson(facebook.request("me"));
    String facebookID = json.getString("id");
    String firstName = json.getString("first_name");
    String lastName = json.getString("last_name");
    Toast.makeText(uiActivity,"Thank you for Logging In, "
                 + firstName + " "
                 + lastName + "!"
                 , Toast.LENGTH_SHORT).show();


text:
Q: how to define a class variable referring to an object of same class in python Below is java code. I need to know the equivalent code in python:
class A {
    public static A obj = new A();
}

A: You can't do this inside a python class definition, since the class has not yet been defined until the end of the class: block. You will have to set it after:
class A(object):
    pass
A.obj = A()

A: You could do this with a metaclass:
class SelfReferencingObjectMetaclass(type):

    def __new__(cls, name, bases, attrs):

        attrs['obj'] = property(lambda self: self.__class__.obj)
        return super(SelfReferencingObjectMetaclass, cls).__new__(cls, name, bases, attrs)

    @property
    def obj(cls):

        try:
            return cls._obj
        except AttributeError:
            cls._obj = cls()
            return cls._obj

class A(object):

    __metaclass__ = SelfReferencingObjectMetaclass

As @Daniel Roseman notes in the comments to @jamylak's answer though, there's probably an easier, more Pythonic way to solve the problem you have than this.  Following that comment, how you would accomplish this functionally, if not identically in terms of the object structure, would be by having a module like this:
a.py
class A(object):

    @property
    def obj(self):

        return a_inst

a_inst = A()

This does create the somewhat ugly construct from a import A in code that utilizes it, but it's a less complicated way to implement it.

A: Do you need this class member before any instance of the class is created? In not, you can try assigning it when the first instance is created:
class A (object):
    obj = None

    def __init__(self):
        if A.obj is None:
            a.obj = A()
            # or:
            a.obj = self

A: I think you'd like to do that because you're trying to implement a pattern like singleton or something like that.
You may read the following recipe from activestate: http://code.activestate.com/recipes/52558/
It explains the way it works and also shows some code.


text:
Q: How do I get the desktop to show directly after wakeup from sleep? I'd like to immediately return to my desktop after waking from sleep. I've managed to remove the password, but still need to wait and click on Sign in after waking from sleep.
Is there a setting or registry change I can do to disable to sign-in screen completely?
Make sure to test your answer, because the obvious solution of removing a password doesn't get rid of the sign in screen (that used to work in older Windows versions though)

A: If you are

*

*using Windows 10 Anniversary Update (version 10.0.14393) or later and using a Microsoft account to log in then the location of the option is somewhere else entirely

or

*

*using a later version (the exact version number is not known) with a local login which has a password (you can unset the password afterwards)*

Then go to (Control Panel) or, depending on Windows version, (Action Centre -> All settings) -> "Accounts" -> "Sign-in options" (on the left) -> "Require sign-in" - > Change it to "Never".

* You need to have the password set when you are choosing "Never". It doesn't matter if it was previously set, but the password must currently be set or else the "Never" option will not appear. But after choosing "Never" you can unset the password, and the "Never" option sill works.

A: Open Run and type "netplwiz". In the dialog box which appears, uncheck the "Users must enter a user name and password to use this computer." option. Click on Apply. An additional popup will appear asking you to enter a username and password which would be used to signing into the desktop. Enter your credentials and click on OK.
Then go to Power Options and select "Don't require a password on wakeup". Restart the system and now you won't have to enter a password or click the sign-in button.
Note: I've tested this on Windows 10 and it works for me.

A: *

*Right-click Battery icon in the Taskbar, and click Power Options.

*Click Change plan settings next to the active power plan.

*Click Change advanced power settings.

*Click Change settings that are currently unavailable.

*Expand Require a password on wakeup and change settings to No.

*Click OK to save the settings.

I use it myself. When I open laptop lid, I see the desktop. After restarting, I have to enter my PIN or password.

A: In elevated command prompt:
powercfg /SETDCVALUEINDEX SCHEME_CURRENT SUB_NONE CONSOLELOCK 0
powercfg /SETACVALUEINDEX SCHEME_CURRENT SUB_NONE CONSOLELOCK 0
Reboot.
Source: https://www.tenforums.com/tutorials/11129-turn-off-require-sign-wakeup-windows-10-a.html#option3

A: Run > Control Panel\All Control Panel Items\Power Options\System Settings > don't require a password on wakeup.
If greyed out click "Change settings that are currently unavailable"

A: It seems that for some people (including myself) neither disabling require a password on wakeup nor netplwiz fully disable the login screen after wakeup on Windows 10.
Disabling a password on wakeup removes the need from entering your password after sleep, but Windows 10 may still resume to the login screen that you have to dismiss (even though you no longer have to enter a password).
The netplwiz solution makes the computer automatically log in when starting up the PC, but may not prevent the login screen from showing up when resuming from sleep.
This is the ultimate solution I have found to disabling the login screen when resuming from sleep (assuming you have already disabled password on wakeup, which is described in another answer).
Open regedit
Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows
Right click on Windows and select New>Key
Name the new key Personalization
Right click on Personalization and select New>DWORD
Name it NoLockScreen
Double click NoLockScreen and edit the value to be 1 and click OK.
Restart the computer, and the lock screen should be disabled when it resumes from sleep.
Credit: http://windows.wonderhowto.com/how-to/disable-lock-screen-windows-10-0162965/

A: If noting works, like in my case, go to right click Start->Power Options->Choose What the Power Buttons Do. Set both buttons to "Sleep" and then click the link above them "Change Settings that are currently unavailable". Uncheck Lock, Save it and try Sleep/Wake again.

A: For me it still didnt work even after Pudergeeks and others suggestion.
My case is a Windows 10 Home edition, with no microsoft account, AND no password.
What I had to do, (in addition to other things from this thread), is go to the following setting:
Lock Screen > click: settings for screen security (near the bottom, in the tutorial I followed it was actually called "Screen saver settings", not sure if they changed the name or if the menu's name was updated)
From there, set the screensaver to "blank". This is what finally did the trick for me. Obviously, "On resume, display logon screen" also has to be disabled. (This was already disabled for me but that didn't initially stop it from actually showing)
Source: https://answers.microsoft.com/en-us/windows/forum/windows_10-power/disable-password-after-sleep-in-windows-10/cf7a7d2b-6927-4ebf-9469-7d06b20d5fc1
Edit: I could change it back to "(none)" afterwards because it's pretty annoying. But for some reason, nothing worked until I touched this menu.


text:
Q: Most efficient way of having separate delivery and billing addresses on an Order I have an Address model and an Order model in my Rails app. An order has a billing address and a delivery address. I'm trying to figure out the most efficient way of implementing this with a polymorphic association (other models will also have addresses in future) and this is the code I've come up with:
address.rb:
class Address < ActiveRecord::Base
  attr_accessible :line_1, :line_2, :city, :county, :postcode
  # Also has an 'address_type' attribute

  belongs_to :addressable, polymorphic: true
end

order.rb:
class Order < ActiveRecord::Base
  has_many :addresses, as: :addressable

  def delivery_address
    addresses.where(address_type: 'delivery').first
  end

  def delivery_address=(address)
    address.address_type = 'delivery'
    addresses << address
  end

  def billing_address
    addresses.where(address_type: 'billing').first
  end

  def billing_address=(address)
    address.address_type = 'billing'
    addresses << address
  end
end

Adding an address:
Order.first.address = Address.new(line_1: 'My House', city: 'Cityville, county: 'Hazzard')

This almost works except that trying to change an address by calling order.delivery_address= again just adds another address of type 'delivery'. I'm also pretty sure that there must be a more elegant way of doing it and I'd really appreciate any advice.

A: has_one :delivery_address, as: :addressable,
         conditions: "addresses.address_type = 'delivery'", class_name: "Address"
has_one :billing_address,  as: :addressable,
         conditions: "addresses.address_type = 'billing'", class_name: "Address"

A: The code looks great.  I think the difference between adding and changing an address should be handled in your controller, not the model, e.g. in a RESTful case, there are method for create and update, in which case you can know whether to replace the value or add it.
Also look at Rails' support for Dirty attributes, which let you know if something has been changed.


text:
Q: Reverse a string with ruby with recursion. What's wrong with this? As said, I'd like to reverse a string in Ruby using recursion (I know how to do it with loops, but I can't wrap my mind around the recursion stuff yet). Here's what I got:
def reverseRecursive(s)

   if s.length==1 then
      return s
   else
      return ((s[s.length-1,1] = s[(s.length-(s.length+1)),1]) + reverseRecursive(s.length-1))
  end
end

puts(reverseRecursive("hello"))

What's wrong with this? I replace the first letter with the last, then add the function with one letter less, the first letter is replaced with the last one again until there's only one letter left which ruby is supposed to put out.
Instead I get the following cryptic message:
undefined method 'length'for 4: Fixnum(NoMethodError)
So it recognized that I want the length of the string -1. How is this undefined? Length works always...
Thanks for your help. :)

A: Now that your question has been answered, let's have some fun by thinking up other ways to reverse a string using recursion.  Here's one:
def esrever(s)
  s.size < 2 ? s : s[-1] + esrever(s[1..-2]) + s[0]
end

esrever("") # => ""
esrever("a") # => "a"
esrever("at") # => "ta"
esrever("this seems to be working") # => "gnikrow eb ot smees siht"

*

*esrever(s[1..-2]) passes all but the first and last characters of the string to itself.

*s[-1] + esrever(s[1..-2]) + s[0] reverses the first and last characters and sandwiches the reversed midsection between them.

*If the method receives a string of length zero or 1, there is nothing to do but return the string.

*You might want to look at "Ruby Names" for a description of Ruby's naming conventions.

A: On this line:
return ((s[s.length-1,1] = s[(s.length-(s.length+1)),1]) + reverseRecursive(s.length-1))

You are calling the reverseRecursive method with an integer:
 reverseRecursive(s.length-1)

and inside the method, you are trying to access the length of an integer which will give you an error:
I don't know about Ruby but the logic should be this:
return s[s.length-1] + reverseRecursive(s[0, s.length-1])

A: This isn't an attempt to fix the recursion logic, instead it's to help you write better Ruby code:
def reverse_recursive(s)

  if s.length > 1 then
    ((s[s.length - 1, 1] = s[(s.length - (s.length + 1)), 1]) + reverse_recursive(s.length - 1))
  else
    s
  end

end

puts(reverse_recursive("hello"))

*

*Methods in Ruby are written in snake_case, not camelCase, so use reverse_recursive.

*Use whitespace around operators like +, = and =. It's a readability thing for those other people who have no clue what you're doing, like your future self that can't remember why you wrote something a certain way, or a future employer who expects you to write in an idiomatic Ruby style.

*if s.length==1 then shouldn't have a trailing then. Use then for single line if tests:
if s.length == 1 then return s

But that isn't used in Ruby very often. Instead we'd use a trailing if:
return s if s.length == 1

*Ruby allows, and it's idiomatic to use, implied return values. In other words, you don't have to use return at the end of a block or method to return the value. The last value seen will be what's returned by the method.

*The logic for your conditional test:
if s.length==1 then
  return s
else
  return ((s[s.length-1,1] = s[(s.length-(s.length+1)),1]) + reverseRecursive(s.length-1))
end

has a problem if s == '', because then you have a string length of 0, which isn't caught correctly:
s = ''
if s.length == 1
  s
else
  ((s[s.length - 1, 1] = s[(s.length - (s.length + 1)), 1]) + reverseRecursive(s.length - 1))
end

# ~> TypeError
# ~> no implicit conversion of nil into String

Use a better test and look for a string length > 1 like in the example above.

A: Your return statement needs to be altered a bit:
return s[s.length-1].chr + reverseRecursive(s[0, s.length-1])

You notice the chr? That is so you get the character at the position, and not the fixnum.

A: As mentioned by others the error is coming because you are passing an integer 's.length-1' into the recursive function, so when it checks it's length at line 3 it has an error because integers do not have a .length function.
Furthermore the logic and the syntax in the recursion is faulty.
The logic should be s[last letter] + recursion(s[second..second last]) + s[first letter]. You need to switch the first with the last letter not replace the first with last, & then call the recursive function on the middle letters to keep swapping the first and last.
Syntactically, I'm not sure exactly how you were trying to achieve your goals because that is not written in ruby, here is more like how it should look:
def reverse_recursive(str)
    return str if str.length < 2 # not ==1 in case empty string passed in
    str[-1] + reverse_recursive("#{str[1..-2]}") + str[0]
end

A: I feel like this would be the simplest way to use recursion.  It helps to identify the base case first.  In this case, the base case would be a single letter.  Assuming that works, then build from there.
def reverseRecursive(s)
    #returns the string if it is only a single letter
    return s if s.length <= 1

    #takes the last letter and assigns it to last
    last = s[-1]

    #assigns the rest of the string to rest
    rest = s[0...-1]

    #runs the rest of the string through the same method
    rest = reverseRecursive(rest)

    #adds them together
    return last + rest
end


text:
Q: Align picture to the right Consider this MWE
\documentclass[12pt,a4paper]{article}
\usepackage[showframe]{geometry}
\usepackage[demo]{graphicx}
\usepackage{lipsum}
\usepackage{floatrow}
\usepackage{caption}
\captionsetup{labelsep=newline,
    justification=raggedleft,
    singlelinecheck=false,
    labelfont=bf,
    font=small}

\begin{document}
\lipsum[2]

\begin{figure}[H]
    \raggedleft
    \begin{minipage}{20cm}
        \floatbox[{\capbeside\thisfloatsetup{capbesideposition={left,center},capbesidewidth=4cm}}]{figure}[\FBwidth]
        {\caption{Some caption that spans more than a line and some additional text}}
        {\includegraphics[width=5cm]{name}}
    \end{minipage}
\end{figure}
\end{document}

This is what I get

As you can see from the command \raggedleft in the code, I was expecting a result which is more like this

How do I achieve this? Also, although this code works perfectly with article class, but if I switch to scrartcl the compilation process encounters some trouble unless I remove labelsep=newline option for caption package. How do I fix this?

A: In order to align the image to the right margin, you might want to use foatrow's \floatsetup[figure]{margins=raggedleft}  command. You can either use it globally by putting it into the preamble or locally as shown in teh following MWE:

\documentclass[12pt,a4paper]{article}
\usepackage[showframe]{geometry}
\usepackage[demo]{graphicx}
\usepackage{lipsum}
\usepackage{floatrow}
\usepackage{caption}
\captionsetup{labelsep=newline,
    justification=raggedleft,
    singlelinecheck=false,
    labelfont=bf,
    font=small}

\begin{document}
\lipsum[2]
{\floatsetup[figure]{margins=raggedleft}
\begin{figure}[H]
        \floatbox[{\capbeside\thisfloatsetup{capbesideposition={left,center},capbesidewidth=4cm}}]{figure}[\FBwidth]
        {\caption{Some caption that spans more than a line and some additional text}}
        {\includegraphics[width=5cm]{name}}
\end{figure}}

\begin{figure}[H]
        \floatbox[{\capbeside\thisfloatsetup{capbesideposition={left,center},capbesidewidth=4cm}}]{figure}[\FBwidth]
        {\caption{Some caption that spans more than a line and some additional text}}
        {\includegraphics[width=5cm]{name}}
\end{figure}

\end{document}

Regarding switching from article to scrartcl you will recieve the following error message:

Package caption Error: The option labelsep=newline does not work
  with \setcaphanging (which is set by default).

Looking through the caption manual, we can find that the default format of article and scrartcl differ:

By adding format=plain to the \captionsetup command, we can make the code compilable for scrartcl as well. Nevertheless, I'd suggest to take a look at the KOMA-script documentation as these document classes already offer ways to customize the look of captions.

A: Only as a supplement to the answer of @leandris for the KOMA-Script part: The KOMA-Script class provides environments captionbeside and captionofbeside.
\documentclass[12pt,a4paper]{scrartcl}
\usepackage{showframe}
\usepackage{graphicx}
\usepackage{lipsum}
\usepackage{float}% if position H is really needed

\KOMAoption{captions}{nooneline,centeredbeside,leftbeside}
\setcapindent*{0pt}
\setcaptionalignment{r}
\renewcommand\captionformat{}
\addtokomafont{caption}{\small}
\addtokomafont{captionlabel}{\bfseries}

\begin{document}
\lipsum[1]

\begin{figure}[H]
  \begin{captionbeside}
      {Some caption that spans more than a line and some additional text}%
    \includegraphics[width=5cm]{example-image}
  \end{captionbeside}
\end{figure}

\lipsum[2]

\begin{figure}[H]
  \begin{captionbeside}
      {Some caption that spans more than a line and some additional text}%
      [l]% caption position
      [\dimexpr9cm+10pt\relax]% width of caption and figure
      [\dimexpr\linewidth-9cm-10pt\relax]% offset
    \includegraphics[width=5cm]{example-image}
  \end{captionbeside}
\end{figure}

\end{document}

Result:

Warning: Package floatrow breaks environment captionbeside.


text:
Q: Oracle Stored Procedures without Ref Cursors Does anyone know of a way to call an Oracle 19 stored procedure in C# without the command object requiring an implicit Ref Cursor be created?
I have no need for any output from this procedure.
It just deletes records that are more than 2 hours old from a table - maybe there's some there - maybe not. There never is any output that I need back from this procedure.
When I try to execute it:
OraCommand.CommandText = sql;
OraCommand.CommandType = CommandType.StoredProcedure;

for (var i = 0; i < args.Length; i += 2)
{
    OraCommand.Parameters.Add(args[i], OracleDbType.Varchar2).Value = args[i+1];
}

try
{
    OraConn.Open();
}
catch (Exception ex)
{
    return ex.Message;
}

int RowsAffected = OraCommand.ExecuteNonQuery();

I get this error:

Operation is not valid due to the current state of the object.

The command object contains this error:

OraCommand.ImplicitRefCursors' threw an exception of type 'System.NullReferenceException'

Does anybody know why?
Thanks


text:
Q: RangeError (index): Invalid value: Not in range 0..1, inclusive: 2. How can this be fixed? I am building a static ListView. How can I solve this error? Also how can I add a UI to the ListView?
Following is my class MatchData code:
class MatchData {
  String date, team1, team2, time;

  MatchData({@required this.date, @required this.team1, @required this.team2, @required this.time});
}

Following is the Data I want to show in the ListView:
final List<MatchData> dayMatch = [
    MatchData(
        date: '12/02/2020',
        team1: 'Mumbai Indians',
        team2: 'Bangalore',
        time: '16:00'),
    MatchData(
        date: '12/02/2020',
        team1: 'Mumbai Indians',
        team2: 'Bangalore',
        time: '16:00')
  ];

  match() {
    return dayMatch;
  }

Following is the body of my Widget:
body: Center(child: ListView.builder(itemBuilder: (context, index) {
          return Card(
            child: Row(
              children: <Widget>[
                  Text(dayMatch[index].date),
                  Text(dayMatch[index].team1),
                  Text(dayMatch[index].time),
                  Text(dayMatch[index].team2),
                ],
            ),
          );
        }

A: If you don't specify itemCount and the screen is big enough to display ten items, ListView.builder() builds a little more than ten children, and even more on demand if you scroll down.
In your case, ListView.builder() tries to build more than two children, while your list (dayMatch) only has two elements, which is why the error occurs.
To fix it, just pass the number of items to the itemCount argument, or it'll be somewhat better to use the default constructor of ListView instead if the number is fixed and small. ListView.builder() does more computing under the hood to be flexible, which is a little too much for a small list.

A: You can use "itemCount".
child: ListView.builder(
  itemCount: dayMatch.length,
  itemBuilder: (context, index) {
    return Card(
      child: Row(
        children: <Widget>[
          Text(dayMatch[index].date),
          Text(dayMatch[index].team1),
          Text(dayMatch[index].time),
          Text(dayMatch[index].team2),
        ],
      ),
    );
  },
),


text:
Q: pass data from html form to python How to pass data from html form to python?
My Html Code:
<form id="form" name="passlink" method="post">
      <input
        id="videolink"
        placeholder="Search or Paste Video Link here"
        type="url"
        name="videolink"
      />
      <input id="download_button" type="submit" value="Submit" />
    </form>

A: from flask import *

app = Flask(__name__)

@app.route("/", methods=['GET','POST'])
def form():
    if request.method == "GET":
        return "You html code"
    data = dict(request.form)

if __name__ == "__main__":
    app.run()

Here data will give dict with the formatting like,
{
    "name1":"value1",
    "name2":"value2"
}


text:
Q: How to use limitRender like in rich:autocomplete Below is my code for autocomplete :
<rich:autocomplete mode="ajax" minChars="2" var="message" fetchValue="#{message.displayName}"
                   layout="div" autocompleteMethod="#{suggestionControlAction.suggestionAction}">
   <h:column>
<h:outputText value="#{message.displayName}"/>
   </h:column>
</rich:autocomplete>

But the problem is,all the a4j:outputPanel which are used in this file are also getting rendered whcih i don't want.There is no limitRender attribute in this tag.
So,how to achive this functionality ?

A: There is indeed no limitRender attribute, have you tried to nest an a4j:ajax inside:
 <a4j:ajax execute="@this" event="..." render="@this">

I have not tried it but this may work.
Maybe you have this issue:
https://issues.jboss.org/browse/RF-12158


text:
Q: No module named 'cogs.music.__pycache__.music' I'm making a discord bot for me and my friends and whenever I run the code, I get this missing pycache module error, I have no idea why and I can't find anything googling python no module named __pycache__ or anything similar
this is the folder layout down to the music pycache, running the code with python bot from the directory above bot

Full traceback:
Traceback (most recent call last):
  File "C:\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "D:\zemo\bot\__main__.py", line 29, in <module>
    load_extensions(bot, './bot/cogs')
  File "D:\zemo\bot\__main__.py", line 16, in load_extensions
    load_extensions(client, entry_path)
  File "D:\zemo\bot\__main__.py", line 16, in load_extensions
    load_extensions(client, entry_path)
  File "D:\zemo\bot\__main__.py", line 21, in load_extensions
    client.load_extension(ext)
  File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
    spec = importlib.util.find_spec(name)
  File "C:\Python39\lib\importlib\util.py", line 94, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'cogs.music.__pycache__.music'

A: You're trying to import from the __pycache__ folder when the music.py file isn't in it.
Try import cogs.music.music instead.

A: Turns out I needed a __init__.py file in the cogs directory


text:
Q: How do I reset GNOME to the defaults? I was playing around with some settings, and now I need to reset GNOME to it's defaults - how do I do that?

A: Logout, switch to command line (Alt + Ctrl + F4), login, do:
rm -rf .gnome .gnome2 .gconf .gconfd .metacity

Switch to X (Alt + Ctrl + F2, F7 on older versions).
Just like they described it here.

A: Resetting Gnome Extensions
If you need to remove your Gnome Extensions (I ran into this problem when trying out Ubuntu 17.10 on an upgraded system) run:
rm -rf ~/.local/share/gnome-shell/extensions

Keep in mind that this will wipe all of your extensions.
To remove an individual extension, you can navigate to ~/.local/share/gnome-shell/extensions and look for the extension's folder, then delete it.
If you'd like to backup
To backup, run:
cp ~/.local/share/gnome-shell/extensions ~/.local/share/gnome-shell/extensions-bkup

A: You can use the mv command.
The syntax is:
mv source1 source2 source3 ... sourceN destination

In your case:
cd ~
mkdir .old-gnome-config
mv .gnome .gnome2 .gconf .gconfd .metacity .cache \
.dbus .dmrc .mission-control .thumbnails .config/dconf/user \
.compiz* .old-gnome-config/

The last one is a directory and it's the destination.

A: For 17.10+
There isn't a great solution but this may do the job or most of it.
dconf reset -f /org/gnome/

Then log out/in
That command's path could be shortened if needing a more extensive reset, i.e. to just /org/ or even / but I'd go with above first.
Worst case one could also just go this in a terminal, I think it's a bit overkill as it will set all dconf (gsettings) back to defaults
mv .config/dconf/user .config/dconf/user.bak && sudo reboot

A: Fore me those directories were not sufficient - I had to delete ~/.config/dconf/user as well.
This helped for me in those two cases:

*

*gnome-panel config broken
(tried to specify location "left" for one gnome panel, it immediately crashed and could not be started afterwards)

*GTK Theme and GTK Icons broken
(nevertheless the selection via e. g. gnome-tweak-tool, it remained in ugly Windows-style grey look and icons were standard gnome - I have no clue how this was provoked, it appeared suddenly after login)

This corresponds to the Gnome 3 Fallback Mode I use on Linux Mint 12 Lisa (Oneiric based). But the GTK problem persisted in all other login modes as well (MATE, Gnome 3 Standard)!
I am unsure now to which mechanism the ~/.config/dconf/user file corresponds, as I found out that in Linux Mint only _mateconf-editor_ is installed by default but outfitted with the title and icon of gconf-editor from Natty!
After installing gconf-editor additionally, this one is titled identically but has a different (new) icon. But don't rely on this icon stories, because this will rely on the icon theme which is Mint-X-Dark for me.
Theory says that dconf is the successor for gconf, but I found no information regarding the GUIs.

A: For Unity-related configuration resetting, take a look here.
For Ubuntu 17.10 and higher, you can reset all the settings using dconf.
This command will delete your configuration files. Once it's run there is no going back!
Still with me?
GNOME 2
Run the following on a terminal or with Alt+F2:
rm -rf .gnome .gnome2 .gconf .gconfd .metacity

That will remove all the GNOME 2 configuration settings. Log out, and log back in. You'll be back to a stock desktop.
You can backup before playing around with your settings in the future:
mkdir ./.old-gnome-config && mv ./.gnome* ./.old-gnome-config && mv .gconf* ./.old-gnome-config && mv ./.metacity ./.old-gnome-config

GNOME 3
If your config isn't worth saving run the following:
rm -rf .gnome .gnome2 .gconf .gconfd .metacity .cache .dbus .dmrc .mission-control .thumbnails ~/.config/dconf/user ~.compiz*

To back up and reset GNOME3:
mkdir ./.old-gnome-config/ && mv ./.gnome* ./.old-gnome-config/ && mv .gconf* ./.old-gnome-config/ && mv ./.metacity ./.old-gnome-config/ && mv ./.cache ./.old-gnome-config/ && mv ./.dbus ./.old-gnome-config/ && mv ./.dmrc ./.old-gnome-config/ && mv ./.mission-control ./.old-gnome-config/ && mv ./.thumbnails ./.old-gnome-config/   && mv ~/.config/dconf/* ./.old-gnome-config/

A: If you want to reset your GNOME specific settings to default as if you had never logged in try
rm -rf .gnome .gnome2 .gconf .gconfd .metacity

A: Reinstalling gnome-tweak-tool resolved this issue and after reboot the GNOME 3 come up again. Actually gnome-tweak-tool was installed but the system detects it as a uninstalled one.

A: I did :
cd $HOME
cd .config
rm -R *
sudo reboot

And I've found my desktop like the first day I create my user account, but all my software params are the same (firefox, thunderbird, filezilla...)


text:
Q: How to fetch last one year's data in SQl with out date, timestamp columns? I have  a table containing years of data but no date or timestamp columns. Now I have to fetch last one year's data. How can achieve that when the table does not have any timestamp or date columns ?

A:
How can achieve that when the table does not have any timestamp or date columns?

In general, you cannot; if you do not have any data inside the table to tell you a date associated with the row then there is not any meta-data that will tell you.

If you have enabled flashback (with a large enough history) on the table then you could compare the state of the table now to the state of the table a year ago using something like:
SELECT * FROM table_name
MINUS
SELECT * FROM table_name AS OF ADD_MONTHS(SYSDATE, -12);


text:
Q: How to make the position of a LINQ Query SELECT variable Is it possible to make the LINQ SELECT more flexible by not working with properties but with the column name?
Maybe an example will help..I'm trying to do the following (pseudocode):
From x In Entities
Where ...
Select("ID", "Value" , "Date")

but depending on certain choices, I would like to have the result in different order
From x In Entities
Where ...
Select("Value", "Date", "ID" )

Or another amount of SELECT results
From x In Entities
Where ...
Select("Value")

Any help to make this as dynamic as possible would be AWESOME! tnx

A: Maybe this will help you
from x In Entities
where ... select new {
  Value = x["Value"],
  Date = x["Date"],
  ID = x["ID"]
}

A: Like I said in my comment (handles subproperties, like Type.Name, but not multiple fields)
I let the fun to make the multi field version ;)
public static class DynamicLinkExtensions
{
    public static IEnumerable<dynamic> Select<T>(this IQueryable<T> source, string memberAccess)
    {
        var propNames = memberAccess.Split('.');
        var type = typeof(T);
        var props = new List<PropertyInfo>();

        foreach (var propName in propNames)
        {
            var prop = type.GetProperty(propName);
            props.Add(prop);
            type = prop.PropertyType;
        }
        return source.Select(props.ToArray());
    }

    public static IEnumerable<dynamic> Select<T>(this IQueryable<T> source, PropertyInfo[] props)
    {
        var parameter = Expression.Parameter(typeof(T));
        var member = Expression.MakeMemberAccess(parameter, (MemberInfo)props.First());

        for (var i = 1; i < props.Length; i++)
        {
            member = Expression.MakeMemberAccess(member, (MemberInfo)props[i]);
        }

        Expression<Func<T, object>> expression = Expression.Lambda<Func<T, object>>(member, new[] { parameter });
        return source.Select(expression);
    }
}

Usage:
var names = DataContext.Customers.Select("Name").Cast<string>().ToList();


text:
Q: Split a dataframe into multiple dataframes I have a dataframe; I split it  using groupby. I understand this splits the dataframes into multiple dataframes. How can I get back those individual dataframes , based on the groups and name them accordingly? So if said df.groupby(['A','B'])
and A has values A1, and B has values B1-B4, I want to get back those 4 dataframes callefdf_A1B1..df_A1B1, df_A1B2...df_A1B4?

A: This can be done by locals but not recommend
variables = locals()
for i,j in df.groupby(['A','B']):
    variables["df_{0[0]}{0[1]}".format(i)] = j
df_01
Out[332]:
   A  B              C
0  0  1  a-1524112-124

Using dict is the right way
{"df_{0[0]}{0[1]}".format(i) : j for i,j in df.groupby(['A','B'])}

A: Offering an alternate solution, using pandas.DataFrame.xs and some exec magic -
df = pd.DataFrame({'A': ['a1', 'a2']*4,
    'B': ['b1', 'b2', 'b3', 'b4']*2,
    'val': [i for i in range(8)]
})

df
#    A   B  val
# 0  a1  b1    0
# 1  a2  b2    1
# 2  a1  b3    2
# 3  a2  b4    3
# 4  a1  b1    4
# 5  a2  b2    5
# 6  a1  b3    6
# 7  a2  b4    7

for i in df.set_index(['A', 'B']).index.unique().tolist():
     exec("df_{}{}".format(i[0], i[1]) + " = df.set_index(['A','B']).xs(i)")

df_a1b1
#        val
# A  B
# a1 b1    0
#    b1    4


text:
Q: Do I need php-mysql? If I already have nginx, php-fpm and mariadb-server? Do I need to install it if I already have nginx, php-fpm and mariadb-server?
What is php-mysql for?

A: Do you want your PHP code to be able to access a MySQL (or MariaDB) database? If yes, then you need this package. It provides the necessary PHP functions.


text:
Q: Javascript: How to get NEXT occurring X day of week I am building a feature into my app that allows an event to scheduled into the future.  IE: The event takes place every Wednesday at 6:30pm.  I need to show the user, based on today's current date, when the NEXT Wednesday is.
If today is Thu Dec 6th 2018, it needs to show the user the next event is on "Wed Dec 12th, 2018 at 6:30pm"
If today is "Tuesday Jan 8th, 2019", it needs to show the user the next event is on "Wed Jan 9th, 2019 at 6:30pm"
The original start date is of the event is captured in my DB as the first day of the ongoing series.  IE: Wed Sept 10, 2018.  I am using that start date to try and calculate every next Wednesday.
  function nextEvent(cEvent) {
      var startDate = cEvent.ceDate+ ", " +cEvent.ceTime ;
      var ceDate = new Date(startDate) ;
      var curDate = new Date() ;
      var timeDiff = Math.abs(curDate.getTime() - ceDate.getTime()) ;
      var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)) ;
      var addDays = Math.ceil(diffDays / 7) * 7 ;
      var futureDate = ceDate.setDate(ceDate.getDate() + addDays) ;
      var futureEvent = ceDate.format('D, M d, Y @ g:i a') ;
      return futureEvent ;
    }
  }

  // this date object START event is Wed Sept 10, 2018
  var dObject = {"ceDate":"2018-09-10","ceTime":"18:30:00"}
  var nextDate = nextEvent(dObject) ;

I am looping through several events, all using different start dates (ie: ceDate), and NEXT event is displaying the wrong next day.  The example above (hard coded in dObject) is displaying Mon Dec 10, 2018, when it should be displaying Wed Dec 12, 2018.
As well, if today is Wednesday at 6pm, the next event still needs to show as TODAY at 6:30pm.  The event lasts minimum 2 hours...so ideally I would also like to figure out how to show something like: Next Event: happening now til 8:30pm

A: Use moment, don't try an write your own date functions for anything more than simple calculations.
https://momentjs.com/
Find next instance of a given weekday (ie. Monday) with moment.js

A: There are a number of issues with your code. Given:
 var dObject = {"ceDate":"2018-09-10","ceTime":"18:30:00"}

then
var startDate = cEvent.ceDate+ ", " +cEvent.ceTime ;

will build a string like "2018-09-10, 18:30:00" which is not a format supported by ECMAScript, so when you do:
var ceDate = new Date(startDate);

the result is implementation dependent and may well result in an invalid Date.
Next:
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)) ;

appears to be trying to get the difference in days between two dates, however it doesn't accommodate the time component so 3 Nov 09:00 to 3 Nov 09:01 will be 1 day, even though it's on the same day and only 1 minute later.
Anyhow, taking your requirement of determining the next occurrence of a weekly event, you can get the event for the current week and if it's passed, add 7 days, e.g.

var dObject = {
  "ceDate": "2018-09-10", // Mon, 9 Sep 2018
  "ceTime": "18:30:00",
  "recurrenceUnit": "day",
  "recurrenceLength": 7
}

// Helper to parse ISO date as local
function parseISOLocal(s) {
  var b = s.split(/\D/);
  return new Date(b[0],b[1]-1,b[2]);
}

function nextEvent(obj) {
  // Get today's details
  var now = new Date();
  var day = now.getDay();

  // Get event details
  var evtDate = parseISOLocal(obj.ceDate);
  var evtDay = evtDate.getDay();

  // Set nextEvt to event for this week
  var nextEvt = new Date(+now);
  nextEvt.setHours(0,0,0,0);
  nextEvt.setDate(nextEvt.getDate() - day + evtDay);
  nextEvt.setHours(...obj.ceTime.split(/\D/));

  // If the nextEvent has passed, add 7 days
  // Should use the recurrenceUnit and recurrenceLength
  if (nextEvt < now) {
    nextEvt.setDate(nextEvt.getDate() + 7)
  }

  return nextEvt;
}

console.log(nextEvent(dObject).toString());

The source object needs to have the repeating period unit and multiple. I've added those but not used them, you should be able to see where it goes. You also need to have functions for add and subtracting hours, days, months, etc. to leverage them. There are plenty of questions and answers here already on those topics.
If I was designing a recurring event object, it would have a lot more information than above with methods to handle the various scenarios.

A: You could try the following:
const getNextOccurringDay = (date, dayOfWeek) => {
 date.setDate(date.getDate() + ((7 + dayOfWeek - date.getDay()) % 7));

 return date;
};

Where date is the date in which you want to locate the next occurring day from (i.e. today) and dayOfWeek is the next occurring day you're trying to find (i.e. if it's a Friday, then it would be 5, Wednesday would be 3, Saturday 6 etc.)
Please note this solution will return the current day if the day you're looking for is the same day as today (i.e. today is a Friday and you're looking for the next occurring Friday then today will be returned).


text:
Q: What's the difference between "here we are " & " here we go " I need to know the difference between "here we go "and " here we are " ?

A: Okay... Well, here we go. "Here we go" refers to going (active) somewhere. That somewhere may be a physical place, e.g., if two people are, hesitantly, about to jump into a cold lake, one might say to the other, "Well. He we go." And then they'd jump in together. That somewhere may be a mental place, e.g., if one person is about to explain something to another person, the explainer might begin by saying, "Well, here we go."
"Here we are" refers to being (passive) somewhere. That somewhere may be a physical place, e.g., if two people are looking at a map, one person might point to a place on the map and say, "Here we are." It probably is more commonly used when arriving somewhere, e.g., if one person is driving another person to a location, especially a location with which the passenger is unfamiliar, the driver, upon arriving, might say to the passenger, "Here we are," meaning that they have arrived at the passenger's destination. Similarly, it may be used metaphorically in a mental context, e.g., if two people are discussing something, one person might say, "Here we are" before stating the facts upon which the two people have agreed. That is, "Here we are," in that context, refers to agreeing about something.
Each of these is sometimes used when presenting someone with something. For example, when someone serves food, the person might say either "Here we go" or "Here we are" meaning the the food has arrived. Or, if you ask to borrow someone's pen, the person might say either "Here we go" or "Here we are" when handing you the pen. Although, that's more commonly "Here you go" or "Here you are."

A: Let's say my friend and I are talking to you, and i get a phone call telling me to reach somewhere.
I then say to you "see you. Here we go" i.e, i am leaving you and going somewhere.
ok so now you call me, and i come to you. Now I will say "Hi, Here we are".
I hope it helps


text:
Q: PHP JSON parsing formatting I am parsing JSOn using PHP. Right now my json is working fine i just want to format my output. I have created a rootobj array where i am inserting few properties then inside that rootobj there is another array but i want inner array properties to be in the root element , This is my code
  $rootObj = array(
     MainEvent' => $event_value['MainEvent'],
    'OutcomeDateTime' => $formatteddate->format('Y-m-d H:i:s'),
    'OutcomeDateTimeUTC' => gmdate('Y-m-d H:i:s', strtotime($event_value['OutcomeDateTime']))
     );
    //inner array
    foreach($event_value['Competitors']['Competitors'] as $compKey => $compVal) {
    $teamName = array_key_exists('Team',$compVal) ? $compVal['Team'] :  $compVal['Name'];
    $win = $compVal['Win'];
    //Creating Competitor Array
     $CompetitorArray[] = array(
     "Team" => $teamName,
     "Win" => $win,
     );
     }
     $rootObj ['Competitors'] = $CompetitorArray;

This is a sample of my output
    ...
     "MainEvent": "West Perth v Swan Districts",
      "OutcomeDateTime": "2014-07-05 16:05:00",
       "OutcomeDateTimeUTC": "2014-07-05 06:05:00",
      "Competitors": [
        {
          "Team": "West Perth",
          "Win": "1.57"
        },
        {
          "Team": "Swan Districts",
          "Win": "2.35"
        }
      ]
    },
    {
      "MainEvent": "East Fremantle v Perth",
      "OutcomeDateTime": "2014-07-05 16:05:00",
       "OutcomeDateTimeUTC": "2014-07-05 06:05:00",
      "Competitors": [
        {
          "Team": "East Fremantle",
          "Win": "1.22"
        },
        {
          "Team": "Perth",
          "Win": "4.15"
        }
      ]
    },
    {
      "MainEvent": "East Perth v Peel Thunder",
      "OutcomeDateTime": "2014-07-05 16:05:00",
       "OutcomeDateTimeUTC": "2014-07-05 06:05:00",
      "Competitors": [
        {
          "Team": "East Perth",
          "Win": "1.12"
        },
        {
          "Team": "Peel Thunder",
          "Win": "6.00"
        }
      ]
    }
  ],
  .....

Bur i want my output to be like this
 ...
 "MainEvent": "West Perth v Swan Districts",
  "OutcomeDateTime": "2014-07-05 16:05:00",
   "OutcomeDateTimeUTC": "2014-07-05 06:05:00",

      "Team1": "West Perth",
      "Win1": "1.57",

      "Team2": "Swan Districts",
      "Win2": "2.35"

},
{
  "MainEvent": "East Fremantle v Perth",
  "OutcomeDateTime": "2014-07-05 16:05:00",
   "OutcomeDateTimeUTC": "2014-07-05 06:05:00",

      "Team3": "East Fremantle",
      "Win3": "1.22",

      "Team4": "Perth",
      "Win4": "4.15"
},
{
  "MainEvent": "East Perth v Peel Thunder",
  "OutcomeDateTime": "2014-07-05 16:05:00",
   "OutcomeDateTimeUTC": "2014-07-05 06:05:00",

      "Team5": "East Perth",
      "Win5": "1.12",

      "Team6": "Peel Thunder",
      "Win6": "6.00"
}

],
  .....

A:  // outside of scope
 $countTeam=0;

 ...

 foreach($event_value['Competitors']['Competitors'] as $compKey => $compVal) {
   $countTeam++;
   $teamName = array_key_exists('Team',$compVal) ? $compVal['Team'] :  $compVal['Name'];
   $win = $compVal['Win'];
  //Insert to root object
   $rootObj["Team".$countTeam] = $teamName;
   $rootObj["Win".$countTeam] = $win;

}


text:
Q: R returns list instead of filling in dataframe column I am trying to use apply() to fill in an additional column in a dataframe and by calling a function I created with each row of the data frame.
The dataframe is called Hit.Data has 2 columns Zip.Code and Hits. Here are a few rows
Zip.Code , Hits
97222    , 20
10100    , 35
87700    , 23

The apply code is the following:
Hit.Data$Zone = apply(Hit.Data, 1, function(x) lookupZone("89000", x["Zip.Code"]))

The lookupZone() function is the following:
lookupZone <- function(sourceZip, destZip){
  sourceKey = substr(sourceZip, 1, 3)
  destKey = substr(destZips, 1, 3)
  return(zipToZipZoneMap[[sourceKey]][[destKey]])
}

All the lookupZone() function does is take the 2 strings, truncates to the required characters and looks up the values. What happens when I run this code though is that R assigns a list to Hit.Data$Zone instead of filling in data row by row.
> typeof(Hit.Data$Zone)
[1] "list

What baffles me is that when I use apply and just tell it to put a number in it works correctly:
> Hit.Data$Zone = apply(Hit.Data, 1, function(x) 2)
> typeof(Hit.Data$Zone)
[1] "double"

I know R has a lot of strange behavior around dropping dimensions of matrices and doing odd things with lists but this looks like it should be pretty straightforward. What am I missing? I feel like there is something fundamental about R I am fighting, and so far it is winning.

A: Your problem is that you are occasionally looking up non-existing entries in your hashmap, which causes hash to silently return NULL.  Consider:
> hash("890", hash("972"=3, "101"=3, "877"=3))[["890"]][["101"]]
[1] 3
> hash("890", hash("972"=3, "101"=3, "877"=3))[["890"]][["100"]]
NULL

If apply encounters any NULL values, then it can't coerce the result to a vector, so it will return a list.  Same will happen with sapply.
You have to ensure that all possible combinations of the first three zip code digits in your data are present in your hash, or you need logic in your code to return NA instead of NULL for missing entries.

A: As others have said, it's hard to diagnose without knowing what ZiptoZipZoneMap(...) is doing, but you could try this:
Hit.Data$Zone <- sapply(Hit.Data$Zip.Code, function(x) lookupZone("89000", x))


text:
Q: Ext 4.1.1: Add new record to Store I would like to add records after the initialization of a store.
I tried loadData(), loadRawData(), add() but nothing seams to work.
Here is my jsfiddle: http://jsfiddle.net/charlesbourasseau/zVvLc
Any ideas ?

A: You need to set queryMode: 'local' in the combo box. Minimal example:
Ext.onReady(function() {
    var store = Ext.create('Ext.data.Store', {
        alias: 'store.ModeStore',
        autoLoad: false,
        fields: [{
            name: 'mode',
            type: 'string'
        }, {
            name: 'id',
            type: 'string'
        }],
        data: [{
            mode: 'mode1',
            id: 1
        }]
    });

    var container = Ext.create('Ext.form.field.ComboBox', {
        renderTo: Ext.getBody(),
        displayField: 'mode',
        valueField: 'mode',
        store: store,
        queryMode: 'local'
    });

    store.add({
        mode: 'mode2',
        id: 2
    });
});

A: For a panel you can add or remove items by remove() and add()
var store = Ext.create('MyApp.store.Roles', {autoLoad: false});
store.load(function(records, action, success) {
    if (success) {
        store.remove(store.findRecord('id', 50, 0, false, true, true));//exact match
        store.add({'id':110,'name':'Agent' });
    }
});


text:
Q: Python: Higher Order Functions with Methods In Python, is there anyway to pass a method to a higher order function, as you would if passing a regular function?
For example, let's say I have a string, "str", and depending on some condition, "cond", I want to apply some arbitrary method, "meth", to the string and return it. In code:
def func(str, meth, cond):
    ...
    if cond:
        str.meth()
    ...

Now, I know the above doesn't work. I also know that I could write something like:
def func(str, meth, cond):
    ...
    if cond:
        str = meth
    ...

and pass the object and method I want to execute to func like this: func(str, str.capitalize(), cond). The problem with the above is that:

*

*The above code doesn't make the intention of the function clear.

*If I, for example, want to modify "str" in anyway before the application of the method, then I end up with an incorrect result. Consider:
def func(str, meth, cond):
    ...
    str += "a"
    ...
    if cond:
        str = meth
    ...

will not work as intended.
So, returning to the beginning: is there anyway to accomplish what I want? Or am I approaching this from the wrong direction altogether?

A: You can pass a method to a higher order function just like you would any function, you just have to pass it as object.method:
class Foo(object):
    def upper(self, s):
        return s.upper()

def func(s, method, cond):
    if cond:
        return method(s)
    else:
        return s

obj = Foo()
s = 'hello world'

print(func(s, obj.upper, 'hello' in s))
print(func(s, obj.upper, 'goodbye' in s))

result:
HELLO WORLD
hello world

Or alternatively if you might try:
def func(s, method, cond):
    if cond:
        return method()
    else:
        return s

s = 'hello world'

print(func(s, s.upper, 'hello' in s))
print(func(s, s.upper, 'goodbye' in s))

However, as pointed out in the comments, this second approach won't work if you have a statement as s = s + 'a' inside the function, since you are just binding the local variable s to a new string, while method is still bound to the upper method of the string initially passed to the function.

A: I think what you what is to pass meth as an unbounded method, so it can be bounded to another object dynamicly.
>>> class C(object):
...     def foo(self):
...             print self
...
>>> C.foo
<unbound method C.foo>
>>> C().foo
<bound method C.foo of <__main__.C object at 0xb708216c>>
>>> def func(obj, meth):
...     meth(obj)
...
>>> c = C()
>>> func(c, C.foo)
<__main__.C object at 0xb70822ac>
>>> c
<__main__.C object at 0xb70822ac>

you can think an unbounded method as an regular who must take an object as its first argument

A: This does not allow you to call the function exactly as you wanted but it gets really close so perhaps it solves your problem.
def func(str, meth, cond):
    if cond:
        str = getattr(str, meth)()
    return str

print func("a", "capitalize", True)
print func("a", "capitalize", False)

A: Don't quite sure what you're asking, but you could pass a function like the following.
def func(str, meth, cond):
    ...
    ...
    if cond:
        return meth(str)
    ...

And run it like this: (for example lowercase)
func("ABC", str.lower, True)

should return "abc"


text:
Q: Android google map drag drop marker on single click on marker I am using Google Map API v2.
In this I place a draggable marker on map.
To drag marker I need to long press on marker for some seconds and then after drag event triggers and dragging is possible.
I want that drag event be called single tap to marker.
How to do that ?
Thanks

A: You can use onTouchListener instead onLongClickListener. Start dragging as soon as touch is detected and stop when touch is completed.
Hope this thread can help you in some way. You can get the idea from this.
Make marker draggable after single click in Android
There is another workaround for this. You can move map under the marker. Marker will remain in the center and the map will move


text:
Q: Distinct numbers in java i need a code that inputs 10 numbers from the user, displays only the distinct numbers and the quantity of distinct numbers ("xxxx distinct #s were entered.")
I am having a hard time displaying the quantity of distinct numbers.
import java.util.Scanner;

class hwFINAL {
    public static void distinctElements(int[] array){
        int count=0;
        int i=0;

        for(i=0;i<array.length;i++){
            boolean isDistinct = false;
            for(int j=0;j<i;j++){
                if(array[i] == array[j]){
                    isDistinct = true;
                    break;
                }
            }
            if(!isDistinct)
                System.out.print(array[i]+",");
        }
    }

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int arr[] = new int[10];

        for (int i = 0; i < arr.length; i++) {
            System.out.print("Enter numbers " + (i+1) + " : ");
            arr[i] = scan.nextInt();
        }

        for (int i = 0; i < arr.length; i++);

        hwFINAL.distinctElements(arr);
    }
}

A: Using Java 8
IntStream.of(intArray).distinct().boxed().forEach(System.out::println);

OR
int[] array={1,2,3,4,4,2,2};

String result =IntStream.of(array).distinct().mapToObj(Integer::toString).collect(Collectors.joining(","));
System.out.println(result);

Output:
1,2,3,4

A: Try this code. It's simpler IMO.
Scanner scan = new Scanner(System.in);
int arr[] = new int[10];
for (int i = 0; i < arr.length; i++) {
    System.out.print("Enter numbers " + (i+1) + " : ");
    arr[i] = scan.nextInt();
}

Arrays.sort(arr);
int totalUnique = 1;
for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] != arr[i+1]) {
        totalUnique += 1;
    }
}
System.out.print(totalUnique + " distinct numbers were entered");

A: Use a HashSet (import java.util.HashSet). By definition, a HashSet cannot store duplicates; therefore your code for the distinctElements() method would be much simpler:
int count;
public static void distinctElements(int[] array){
    HashSet<Integer> set = new HashSet<Integer>();
    for (int i=0; i<array.length; i++){
        set.add(array[i]);
    }
    count = set.size();

    System.out.println(count + " distinct numbers were entered");
}

Then you could also print each distinct number individually using a for-each loop:
for (Integer number : set){
    System.out.println(number);
}


text:
Q: RestTemplate getForObject is not able to map Custom Class Custom class structure DocumentListVO mapping one to one with JSON response however while using  DocumentListVO dv1 = restTemplate.getForObject(uri,DocumentListVO.class), it is throwing error with following stack trace:
GET request for
"http://aaa.ddd.com:8081/bpi1/service/aa/documen1t/list23"
resulted in 200 ()
    [2018-05-28 12:49:46,397]-DEBUG org.springframework.web.client.RestTemplate  - Reading [class
com.fascorp.isis.ejb.documentVO.DocumentListVO1] as
"application/json;charset=UTF-8" using
[org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@58206f8]
    [2018-05-28 12:49:46,399]-DEBUG org.apache.http.wire  - http-outgoing-0 << "0[\r][\n]"
    [2018-05-28 12:49:46,400]-DEBUG org.apache.http.wire  - http-outgoing-0 << "[\r][\n]"
    [2018-05-28 12:49:46,402]-DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager  -
Connection [id: 0][route: {}->http://aaa.ddd.com:8081] can be kept
alive indefinitely
    [2018-05-28 12:49:46,404]-DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager  -
Connection released: [id: 0][route:
{}->http://aaa.ddd.com:8081][total kept alive: 1; route allocated:
1 of 2; total allocated: 1 of 10]
    org.springframework.http.converter.HttpMessageNotReadableException:
Could not read JSON: Unrecognized field "Results" (class
com.fascorp.isis.ejb.documentVO.DocumentListVO1), not marked as
ignorable (3 known properties: , "success", "results", "count"])
     at [Source: org.apache.http.conn.EofSensorInputStream@209152d; line: 1, column: 13] (through reference chain:
com.fascorp.isis.ejb.documentVO.DocumentListVO1["Results"]); nested
exception is
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "Results" (class
com.fascorp.isis.ejb.documentVO.DocumentListVO1), not marked as
ignorable (3 known properties: , "success", "results", "count"])
     at [Source: org.apache.http.conn.EofSensorInputStream@209152d; line: 1, column: 13] (through reference chain:
com.fascorp.isis.ejb.documentVO.DocumentListVO1["Results"])
            at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:228)
            at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:220)
            at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)
            at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:559)
            at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:527)
            at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:259)

public class DocumentListVO
{
  String Count;
  boolean Success;
  Results[] Results;

  public DocumentListVO()
  {
    super();
  }

  public DocumentListVO(String Count, boolean success, Results[] results)
  {
    super();
    this.Count = Count;
    this.Success = success;
    this.Results = results;
  }

  public Results[] getResults()
  {
    return Results;
  }
  public void setResults( Results[] results)
  {
    this.Results = results;
  }
  public String getCount()
  {
    return Count;
  }
  public void setCount( String count)
  {
    this.Count = count;
  }
  public boolean isSuccess()
  {
    return Success;
  }
  public void setSuccess( boolean success)
  {
    this.Success = success;
  }

  @Override
  public String toString()
  {
    return "DocumentListVO [count=" + Count + ", success=" + Success
           + ", results=" + Arrays.toString(Results) + "]";
  }
}

JSON response:
{
    "Results": [
        {
            "Category": "abcde",
            "DateCreated": "12-13-2016 14:43:31",
            "Token": "ad",
            "ClassDescription": "Wisd",
            "DocumentTitle": "Rela",
            "ContentSize": "58",
            "MimeType": "application/pdf"
        },
        {
            "Category": "tyreytr",
            "DateCreated": "11-07-2017 13:37:11",
            "Token": "hgdf",
            "ClassDescription": "With",
            "DocumentTitle": "Related Doc - 1234646315",
            "ContentSize": "58",
            "MimeType": "application/pdf"
        }
    ]
    "Count": 89,
    "Success": true
}

A: Add @JsonProperty annotation on your fields.
public class DocumentListVO
{

    @JsonProperty("Count")
    String Count;

    @JsonProperty("Success")
    boolean Success;

    @JsonProperty("Results")
    Results[] Results;

    ..... setters / getters
    // add annotation on setter / getter too (not necessary)

}

The reason is jackson doesn't reads the private variable names, but setter / getter method names.
So a setter for Results will be setResults but jackson interpret the field name as results as per naming convention of setters / getters.
After adding @JsonProperty you can rename your fields as per java naming convention as well, count, success, results etc.


text:
Q: Update native query is too slow I am using Hibernate with native query to update a field in a table with 17000 rows in Oracle.
When I execute the query on Toad, it takes 0.5s to be executed and with the below code no finish ever.
Query query = em.createNativeQuery("UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )");
query.setParameter(1, value);
query.executeUpdate();

This is the trace:
10-08 14:15:59 DEBUG JpaTransactionManager - Creating new transaction with name [es.package.app.repository.jpa.JPAValorMaximo.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
10-08 14:15:59 DEBUG JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@405264e8] for JPA transaction
10-08 14:15:59 DEBUG AbstractTransactionImpl - begin
10-08 14:15:59 DEBUG LogicalConnectionImpl - Obtaining JDBC connection
10-08 14:15:59 DEBUG LogicalConnectionImpl - Obtained JDBC connection
10-08 14:15:59 DEBUG JdbcTransaction - initial autocommit status: true
10-08 14:15:59 DEBUG JdbcTransaction - disabling autocommit
10-08 14:15:59 DEBUG JpaTransactionManager - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@1bbb3b9e]
10-08 14:15:59 DEBUG SQL - UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )
Hibernate: UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )

thanks


text:
Q: how to insert a variable inside HTML I am trying to code in HTML + JavaScript the following kind of form/decision tree:
Question 1: from which country are you?
Answer 1: Italy
Answer 2: Japan
...
Q2: what do you like?
if Q1 = Italy, A1 = i like cats, A2 = i like music
if Q1 = Japan, A1 = i like dogs, A2 = i like sport
Q3: what age are you?
A1 = 13
A2 = 57
Result: depends on selected answers
I did succeed to code the form as well as to include the different results. Now my challenge is to display the different options for Q2 depending on Q1 answer.
My question looks like this, written in HTML:

 what do you like?
  <select id="question_2">
          <option value="hello">i like cats</option>
          <option value="goodbye">i like music</option>
          <option disabled selected="selected"></option>
  </select>

I use a function written in JS for the decision tree logic.
I would like to add these options if Q1 = Japan, A1 = i like dogs, A2 = i like sport ; preferably within the HTML. I thought of using variables, and have something like:

 what do you like?
  <select id="question_2">
          <option value="hello">i like ${x}</option>
          <option value="goodbye">i like ${y}</option>
          <option disabled selected="selected"></option>
  </select>

with this logic, ideally written in JS:
if Q1 = A1, then x = cat and y = music
if Q1 = A2, then x = dogs and y = sport

Would this be possible? Any hint on what to look at?
I am a beginner. Thanks a lot.

A: You can write two questions for both options Japan and Italy respectively. Then use a Javascript function which will make the question corresponding to Italy visible if the user selects Italy. Otherwise, another question will be visible if the user selects Japan. If the user selects neither Japan nor Italy, then both the questions will not be visible.
In the Javascript function, you can set the style.display attribute to none to make any question (div) invisible or set it to block to make the question (div) visible.
HTML

  from which country are you?
  <select id="question_1" onchange="showDiv(this)">
          <option value="italy">italy</option>
          <option value="japan">Japan</option>
          <option disabled selected="selected"></option>
  </select>

 what do you like?
  <select id="question_2_italy">
          <option value="hello">i like cats</option>
          <option value="goodbye">i like Music</option>
          <option disabled selected="selected"></option>
  </select>

 what do you like?
  <select id="question_3_japan">
          <option value="hello">i like dogs</option>
          <option value="goodbye"> i like sport</option>
          <option disabled selected="selected"></option>
  </select>

CSS
.hidden_div{
    display: none;
}

JS
function showDiv(element)
{

       for ( var i = 0, len = element.options.length; i < len; i++ ) {
            opt = element.options[i];

            if ( opt.selected === true ) {
                document.getElementsByClassName("hidden_div")[i].style.display = 'block';
            }
            else {
                    document.getElementsByClassName("hidden_div")[i].style.display = 'none';
            }

     }
}


text:
Q: Trouble with converting phonegap plugin to work with plugman I'm working on an iPhone app via AppGyver Steroids and it requires that phonegap plugins be installed via plugman. I found a plugin that I desperately need but it isn't compatible with plugman. I've been trying to convert it, but I'm stuck. The javascript layer is working fine, but I can't seem to get it to talk to the native layer. Any help would be much appreciated.
Here's what I've got so far:
https://github.com/stevethorson/phonegap-backgroundjs
I've edited the plugin.xml file and restructured the files, but I'm not sure if it's right.

A: Nevermind. This branch already did what I was looking for.
https://github.com/colibri-software/phonegap-backgroundjs/tree/phonegap3


text:
Q: How to avoid redundancy of assets splitting Android app into modules? I am planning to split my app, feature-wise into a set of independent modules. Many of the features (modules in my new design) share the image assets and string constants.
If I add the reusable assets in the main/app module then they would be compiled into the APK even if I don't include the modules using them. If I add the reusable assets to all the modules, then I face all the problems that come with redundancy.
What is the correct approach of splitting app into modules ? End-goal of my design is to enable/disable any feature during the build phase (through build.gradle).

A: Let's assume that we have App A, and Libraries L1, L2, and L3. L1 and L2 share some common resources and/or assets. From a production standpoint, only one copy of those common resources and/or assets would be included anyway, but redundancy is bad from the standpoint of development (e.g., ensuring you change both copies).
So, I'd create a Resource Module Mfoo that contains those common resources and/or assets. Have L1 and L2 depend upon Mfoo. Have different product flavors(?) of A depend upon various mixes of L1, L2, and L3. Only one copy of Mfoo will be used, as Gradle will net out the transitive dependencies. This is no different than, say, L1 and L2 both depending on support-v13.
Of course, depending upon how many libraries you have and the mix of shared stuff, you could get into Michael Bay-level combinatorial 'splosions here.


text:
Q: appending values in a dynamic array #!/bin/bash

range=$(seq -f "cen%04g" 1052 1099)
range1=$(seq -f "rh%04g" 1052 1099)

check () {
for node1 in ${range};do
   ping -q -c 1 -w 3 -s 10 $node1 >/dev/null
   if [ $? -eq 0 ];then
       $i_up+=(${node1}",")
   else
       $i_down+=(${node1}",")
   fi
done
}

for i in "site1" "site2" "site3"
do
   declare -a $i_down
   declare -a $i_up
   check &
done

*

*I'm not sure how can I name the array based on for loop input so that it can run sites(site1,site2,site3) in parallel and get the array input in separate for each site. Else running each will take longer time.

*I have range on series cen(1052 to 1099) and if its not found there, I need to check with different series(rh) with same numbers. eg: cen1052 isn't there it needs to check rh1052. how can do that.

A: I think you are looking for parset:
checkhost() {
    piing() {
        ping -q -c 1 -w 3 -s 10 "$1" >/dev/null
    }
    if piing "cen$1"; then
      echo "+cen$1"
    else
      if piing "rh$1"; then
         echo "+rh$1"
      else
        if piing "deb$1"; then
           echo "+deb$1"
        else
           echo "-cen$1"
        fi
      fi
    fi
}
export -f checkhost
parset updown -j0 checkhost ::: {1052..1099}
echo "${updown[@]}"

It is unclear to me how the you need the sites to work. If, say, it was simply a domain name to append, you can do:
parset updown -j0 checkhost {1}.{2} ::: {1052..1099} ::: site1.com site2.com site3.com

parset is part of GNU Parallel. After installing GNU Parallel you need to activate parset by:

*

*(permanently) env_parallel --install followed by starting a new shell

*(this session only) . $(which env_parallel.bash)
If this is not what you are looking for, I suggest you make a full example that works, but does so in serial.


text:
Q: What is the size of a composite index in MySQL/MariaDB Suppose I have three columns, A, B, C. They each have a range of x, y and z possible values respectively.
Does an index on all three columns have a size proportional to x * y * z?

A: No.  The size of an INDEX is (roughly)
  N * L + overhead

N = Number of rows in the entire table.
L = Length (in bytes) of the values in all the columns of the index, plus columns in the PRIMARY KEY.
overhead = various pointer, lengths, padding, etc
Example:  CREATE TABLE ... id INT PRIMARY KEY, A INT, INDEX(A) ...
INT is a 4-byte datatype.  It can hold more than 4 billion distinct values.  If there are 100 rows in the table, let's look at the BTree holding the secondary INDEX(A).
N = 100
L = 4 + 4  -- that bytes, not billions of bytes

N * L = 800, but once the overhead is added, and use the blocking, it will take 16KB.  (Note:  InnoDB allocates data and indexes in "blocks" of 16KB.)
Now add to that table
city VARCHAR(100),  -- average length 10 characters
INDEX(city, A)

N = 100  -- still assuming 100 rows
L = (2+10) + 4 + 4 = 16
total = again, only 1-2 blocks.

The (2+10):  2 for the "length" of the string; 10, on average, for the actual string.  (In some cases, the "2" is really "1" and if you are using utf8, each character could be multiple bytes.)
If that table grows to 1 million rows, the index may take 50MB, a lot of it being unavoidable "overhead".
A major exception:
For InnoDB, the size of the PRIMARY KEY is virtually zero since it is "clustered" with the data.  Actually, there is about 1% extra for the non-leaf nodes in that BTree and some 'overhead'.


text:
Q: action is not a function react-redux login undefined
I am getting login as undefined, whenever I click the login button it was working fine before I created AppRoutes.js and moved some of the routes into that file.

TypeError: login is not a function

here is the code structure.
this is the main file where app is started and login route is put here inside the AppRoutes component.

*

*app.js

import React, { Fragment, useEffect } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import Navbar from './components/layout/Navbar'
import Landing from './components/layout/Landing'
import Alert from './components/layout/Alert'
import { loadUser } from './actions/auth'
import { Provider } from 'react-redux'
import setAuthToken from './utils/setAuthToken'
import store from './store'
import './App.css'
import AppRoutes from './components/routing/AppRoutes'
if (localStorage.token) {
  setAuthToken(localStorage.token)
}
const App = () => {
  useEffect(() => {
    store.dispatch(loadUser())
  }, [])
  return (
    <Provider store={store}>
      <Router >
        <Fragment>
          <Navbar />
          <Alert />
          <Switch>
            <Route exact path='/' component={Landing} />
            <Route component={AppRoutes} />
          </Switch>

        </Fragment>
      </Router>
    </Provider>
  )
}

export default App

2.AppRoutes.js

import React, { Fragment } from 'react'
import { Register } from '../auth/Register'
import { Login } from '../auth/Login'
import Dashboard from '../dashboard/Dashboard'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import PrivateRoute from './PrivateRoute'
import { NotFound } from '../layout/NotFound'
import store from '../../store'
import { Provider } from 'react-redux'
const AppRoutes = () => {
    return (<Fragment>
        <Switch>
            <Route exact path='/register' component={Register} />
            <Route exact path='/login' component={Login} />
            <PrivateRoute path='/dashboard' component={Dashboard} >
            </PrivateRoute>
            <Route component={NotFound} />
        </Switch>
    </Fragment>
    )
}

export default AppRoutes

*auth.js

export const login = (email, password) => async dispatch => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    }

    const body = JSON.stringify({ email, password })
    try {
        const res = await axios.post('/api/auth', body, config)
        if (res?.data?.token) {
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data
            })
            dispatch(loadUser())
        }
        else {
            dispatch(setAlert(res.data.msg, 'success'))
        }
    } catch (error) {
        const errors = error.response.data.errors
        if (errors) {
            errors.forEach(error => dispatch(setAlert(error.msg, 'danger')))
        }
        dispatch({
            type: LOGIN_FAIL
        })
    }
}

4.Login.js

import React, { Fragment, useState } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { login } from '../../actions/auth'
import { Link, Redirect } from 'react-router-dom'
import store from '../../store'

export const Login = ({ isAuthenticated, login }) => {
    const [formData, setFormData] = useState({

        email: '',
        password: ''

    })

    const { email, password } = formData

    const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value })

    const onSubmit = e => {
        e.preventDefault()
        console.log(typeof login)
        login(email, password)
    }

    //redirect if logged in

    if (isAuthenticated) {
        return <Redirect to='/dashboard' />
    }

    return (
        <Fragment>

Welcome Back!

                                        <form className="user" onSubmit={e => onSubmit(e)}>

                                                <input className="form-control form-control-user" type="email" placeholder="Email Address" name="email" value={email} onChange={e => onChange(e)} required />

                                                <input className="form-control form-control-user" type="password"
                                                    placeholder="Password"
                                                    name="password"
                                                    minLength="6"
                                                    value={password} onChange={e => onChange(e)}
                                                />

                                                        <input className="form-check-input custom-control-input" type="checkbox" id="formCheck-1" />
                                                        Remember Me

<button className="btn btn-dark btn-block text-white btn-user" type="submit">Login</button>

                                        </form>

<Link to="/register" className="small" href="register.html">Create an Account!</Link>

        </Fragment >
    )
}
Login.propTypes = {
    login: PropTypes.func.isRequired,
    isAuthenticated: PropTypes.bool
}

const mapStateToProps = state => ({
    isAuthenticated: state.auth.isAuthenticated

})

export default connect(mapStateToProps, { login })(Login)

I am not able to figure out whether it is related to the route structure that i changed or is there a bigger problem that I am missing out on.

A: You have imported Login a named import in AppRoutes, whereas the connected component with Login was a default export which is why you see the issue
Change
import { Login } from '../auth/Login'

to
import Login from '../auth/Login'


text:
Q: Automation Testing approach - Which is best? Which is the best suited automation approach? is it Data driven testing or Keyword driven testing? Now even we have Business process testing, what according to you is best approach?

A: It all depends on your needs.
As a long-term investment I recommend keyword-driven or hybrid keyword/data driven framework.
See my short overview below (taken from my blog page http://automation-beyond.com/category/automation/automation-methodology/practices/).
Front-End Test Automation Practices – Record/Playback

*

*Description
• Hard-coded data
• Hard-coded flow
• No error handling
• No or limited reporting
• No structure
• No verification
• No validation

*Advantages
• Easy to create
• Quick to create
• No programming required

*Disadvantages
• Very low usability
• Extremely high maintenance cost
• No-proof test results
• Break on any fail
• Poor test flow coverage
• A lot of manual work is still required

*Applicability
• Demo and sale presentations
• Same day testing (re-record from scratch, short test flow)
• Exploratory testing (investigating how the Testing Tool handles the Application)
• Automated data entry (restrictions apply)
Front-End Test Automation Practices – Record/Playback Enhanced

*

*Description
• Parameterized data
• Dataset is a part of the script but not in the code
• Verification via GUI checkpoints (hard-coded)
• Hard-coded flow
• No error handling
• No or limited reporting
• No structure

*Advantages
• Easy to create
• Quick to create
• No programming required, but expertise on the Testing Tool is a must

*Disadvantages
• Vulnerable scripts
• No multi-environment support
• Very high maintenance cost for checkpoints
• Not reproducible test results
• Break on any fail
• Limited test flow coverage
• All analysis and validation done manually

*Applicability
• Single/stable environment
• Short flow Test Cases
• Limited set of checkpoints, as any Database / Data Input change breaks verification and requires recapture
• Short-term simplified automation goals
Front-End Test Automation Practices – Data-Driven Framework

*

*Description
• Programmatically created
• Parameterized, capable to import spreadsheets
• GUI/Database checkpoints, hard-coded and/or parameterized
• Library-based structure
• Possibly error handling
• Hard-coded yet data-driven flow (input and logic)
• Standard reporting
• Verification is limited to Testing Tool's capabilities
• No validation

*Advantages
• Good usability and re-usability
• Good test flow coverage
• Multi-environment support
• Data and code are separate
• Reproducible test results

*Disadvantages
• Quality and coverage strongly depends on the automation skills of implementing person
• Continuous maintenance issues due to a big amount of the code
• Exit on fail
• Manual validation is required

*Applicability
• Good fit for a single application testing, featuring multi-environment, big datasets, and rarely changing Test Cases
• Batch-run capable with additional development efforts
• Limited set of checkpoints, as any Database / Data Input change breaks verification and requires recapture
• Shared across the team workspace (environment, data, etc.) required (possible issues with offshore support)
• Mid-term automation goals
Front-End Test Automation Practices – Keyword-Driven Framework

*

*Description
• Pure programmatically
• Parameterized, capable to import spreadsheets
• GUI/Database checkpoints, hard-coded and/or parameterized
• Framework-based structure
• Limited error handling
• Keyword-based flow (logic and data in a spreadsheet)
• Possibly extended reporting
• Verification is limited to Testing Tool's capabilities
• No validation

*Advantages
• Good usability and re-usability
• Compact code
• Test development doesn't require programming skills
• Good test flow coverage
• Multi-environment support
• Data and code are separate
• Reproducible test results

*Disadvantages
• Requires initial investment for design and implementation of the Framework
• Due to keywords limit doesn't allow covering very complicated Test Cases
• Meta-language specific training is required for staff
• Version control issues
• Exit on fail
• Manual validation is required

*Applicability
• Good fit for a multi-application testing (same platform), featuring multi-environment, big datasets, and a big number of short and straight Test Cases
• Test Plan / Test Scenario execution (Batch run)
• Limited set of checkpoints, as any Database / Data Input change breaks verification and requires recapture
• Better support of distributed teams, especially with extended reporting implemented
• Multi-tool support for the meta-language
• Mid- and long-term automation goals
Front-End Test Automation Practices – Hybrid Keyword/Data Driven Framework

*

*Description
• Pure programmatically
• Internal Data Model, capable to import/export data from various sources
• GUI/Database checkpoints, parameterized/transitioned
• Business Verification Rules
• Framework-based structure; capable to integrate external objects (i.e. MSXML DOM)
• Exception handling and recovery capabilities
• Test Case oriented execution (business logic outside of the code)
• Data-driven input & verification
• Extended business reporting
• AI-based validation methods

*Advantages
• High usability and re-usability
• Compact and scalable architecture
• Test Plan / Test Scenario creation doesn't require programming or training on the Testing Tool
• Extensive test flow coverage
• Multi-application support
• Data and code are separate
• Reproducible and proven test results, convenient and transferable Test Reports
• Built-in Consistency and Severity Validation

*Disadvantages
• Requires initial investment for design and implementation of the Framework

*Applicability
• Comprehensive Functional Testing for multi-application, multi-platform products, featuring huge number of complicated Test Cases
• Smoke-Regression-Sanity Testing Cycle with extensive coverage and validation
• Test Plan / Test Scenario execution (Batch run)
• Big and changeable data set and data transitioning cases
• Excellent support of distributed teams
• Integration with other testing tools
• Mid- and long-term automation goals

A: It sounds like your question is specific to HP's QTP/BPT. Here are the differences. QTP is really the 'engine' that is used by both BPT and QTP. QTP provides two main views for working with scripts.
QTP:
The first is the 'Keyword' view which presents a tree of actions and functions. This mode is suited for beginners and allows them to select objects from either the application or from the object repository as well as selecting the methods to be performed on the objects. The script is then generated automatically.
The second is the 'Expert' view which allows the display and editing of the scripts source code. The expert veiw provides an IDE for developing the scripts. This view is suited for advanced users.
BPT is based on the concept of creating test cases from re-usable business components which in turn are created from keywords. This keyword-driven approach simplifies the process of test case creation by providing a gui that allows the user to 'drag and drop' components to build the test. the script is generated automatically.

A: It depends what you are trying to accomplish in your particular situation.  One thing that is universal, however, is that test automation is software development, and needs to be treated as such.  Use sound design and coding practices.  It sounds like you are new to automation.  Often a good place to start is building a smoke test that will quickly run for each new build.


text:
Q: Keras + IndexError I am very new to keras. Trying to build a binary classifier for an NLP task. (My code is motivated from imdb example - https://github.com/fchollet/keras/blob/master/examples/imdb_cnn.py)
Below is my code snippet:
max_features = 30
maxlen = 30
batch_size = 32
embedding_dims = 30
nb_filter = 250
filter_length = 3
hidden_dims = 250
nb_epoch = 3

(Train_X, Train_Y, Test_X, Test_Y) = load_and_split_data()
model = Sequential()
model.add(Embedding(max_features, embedding_dims, input_length=maxlen))
model.add(Convolution1D(nb_filter=nb_filter,filter_length=filter_length,border_mode="valid",activation="relu",subsample_length=1))
model.add(MaxPooling1D(pool_length=2))
model.add(Flatten())
model.add(Dense(hidden_dims))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode="binary")
fitlog = model.fit(Train_X, Train_Y, batch_size=batch_size, nb_epoch=nb_epoch, show_accuracy=True, verbose=2)

When I run model.fit(), I get the following error:
/.virtualenvs/nnet/lib/python2.7/site-packages/theano/compile/function_module.pyc in __call__(self, *args, **kwargs)
    857         t0_fn = time.time()
    858         try:
--> 859             outputs = self.fn()
    860         except Exception:
    861             if hasattr(self.fn, 'position_of_error'):

IndexError: One of the index value is out of bound. Error code: 65535.\n
Apply node that caused the error: GpuAdvancedSubtensor1(<CudaNdarrayType(float32, matrix)>, Elemwise{Cast{int64}}.0)
Toposort index: 47
Inputs types: [CudaNdarrayType(float32, matrix), TensorType(int64, vector)]
Inputs shapes: [(30, 30), (3840,)]
Inputs strides: [(30, 1), (8,)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[GpuReshape{3}(GpuAdvancedSubtensor1.0, MakeVector{dtype='int64'}.0)]]

HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.
HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

Can you please help me resolve this ?

A: You need to Pad the imdb sequences you are using, add those lines:
from keras.preprocessing import sequence
Train_X = sequence.pad_sequences(Train_X, maxlen=maxlen)
Test_X = sequence.pad_sequences(Test_X, maxlen=maxlen)

Before building the actual model.


text:
Q: Intellij do not load project right when I create a new project everything is fine and work well. If I close IntelliJ and open it again, it shows me the recent projects, but if I will load one nothing happened. It only show's me the background of IntelliJ and nothing else. If I open the .IML source IntelliJ load the correct project structure but all "class"-files have the .java ending and IntelliJ find no SDK and so on.
Thanks for helping and if you find any mistakes correct me, please. It's also important to write correct English :)


text:
Q: Ignite near cache - Can the same distributed cache be configured to be a near cache in one ignite client & a regular cache in another ignite client? Folks,
Does anyone know the behavior for the below two items on Ignite Near Cache,

*

*Can the same distributed cache on the ignite grid be configured to be a near cache in one ignite client & a regular cache in another ignite client at the same time?. Hopefully this can be done.

*Does near caches work when using SQL queries (we use Spring Data abstraction) or does it work only with JCache based key-value access.
Thanks
lmk

A: *

*I think you should be able to only start Near Cache on a subset of clients. Have you tried that.

*No, SQL map phase will not happen on clients, it will happen on primary server node(s).


text:
Q: Adding a horizontal and vertical scroll bar for d3-2way-tree for multilevel tree I was referring to d3 widget, http://bl.ocks.org/kanesee/5d6c48bffd4ea31201fb . I want the tree to be grown further more both at the top and bottom, As the page canvas is fixed I want to add scroll bars so that when the graph grows i should be able to see the chart completely.
{
    "name": "Heirachy",
    "parents": [
        {
            "name": "Parent1",
            "isparent": true
        },
        {
            "name": "Parent2",
            "isparent": true
        },
        {
            "name": "Parent3",
            "isparent": true,
            "parents": [
                {
                    "name" : "inner-parent3",
                    "isparent" : true,
                    "parents":[
                        {
                            "name" : "inner-most-parent3",
                            "isparent" : true
                        }
                    ]
                },
                {
                    "name" : "outer-parent3",
                    "isparent" : true
                }
            ]
        }
    ],
    "children": [
        {
            "name": "Childern1",
            "isparent": false
        },
        {
            "name": "Childern2",
            "isparent": false
        },
        {
            "name": "Childern3",
            "isparent": false,
            "children": [
                {
                    "name" : "inner-1-children3",
                    "isparent" : false
                },
                {
                    "name" : "inner-2-children3",
                    "isparent" : false
                }
            ]
        },
        {
            "name": "Childern4",
            "isparent": false
        }
    ]
}

This my json data, it makes tree to grow vertically.

A: Wrap it in a div and add this to the CSS:
overflow: scroll;

A: just include overflow:auto; in css to perticular div
overflow:auto;

new
Add parent div for #categoryHierarchy div
HTML

CSS:
#parentDiv {
   margin:0 auto;
   overflow:auto;
   max-width:960px; // set width according to your requirement
   max-height:448px; // set height according to your requirement
}


text:
Q: MPAndroidChart click listener on chart I am using MPAndroidChart and would like to know how to perform click event on following graphs and get the related callback:
Pie chart: click on particular reason open its detail.
Bar chart: click on any bar open its detail.
Stacked Bar chart: click on any bar open its detail.
I need to get notified when the chart is clicked.

A: for LineChart if you are using displayed non float value in Kotlin use below code
lineChart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener
       {
        override fun onValueSelected(e: Entry, h: Highlight?) {
            val x = e.x.toString()
            val y = e.y
            val selectedXAxisCount = x.substringBefore(".") //this value is float so use substringbefore method
            // another method shown below
            val nonFloat=lineChart.getXAxis().getValueFormatter().getFormattedValue(e.x)
            //if you are display any string in x axis you will get this
        }

        override fun onNothingSelected() {}
    })

Happy coding...

A: For PieChart :-
mPieChart.setOnChartValueSelectedListener(object :
OnChartValueSelectedListener {
            override fun onNothingSelected() {
            }

            override fun onValueSelected(e: Entry?, h: Highlight?) {

                val pieEntry = e as PieEntry
                val label: String = pieEntry.label
            }
})

A: *

*Implement OnChartValueSelectedListener

*Register listener in activity/fragment

*override methods

*This is in Kotlin
chart.setOnChartValueSelectedListener(this)

override fun onNothingSelected() {
    Log.i("Entry selected", "Nothing selected.")
}

override fun onValueSelected(e: Entry?, h: Highlight?) {
    Log.i("Entry selected", e.toString())
    val x:Float =e!!.x
    val y:Float =e!!.y
    chart.highlightValue(h)

}

A: Use the OnChartValueSelectedListener. You can find the documentation on how to implement it here.
This listener allows you to react on click gestures performed on the charts.

A: for LineChart
   chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener()
    {
        @Override
        public void onValueSelected(Entry e, Highlight h)
        {
            float x=e.getX();
            float y=e.getY();
        }

        @Override
        public void onNothingSelected()
        {

        }
    });

A: *

*Implement interface OnChartValueSelectedListener

*Implemented methods

@Override
public void onValueSelected(Entry e, Highlight h) {
   // enter your code here
}

@Override
public void onNothingSelected() {
    // do nothing
}

*Add this code to your chart display method

chart.setOnChartValueSelectedListener(this);