text:
Q: how to show data from table in drop down list using MVC3? I'm creating a search application  in mvc3 where i have 2 tables :
1.State :Id(pk) and state_name
2.District:Id(pk),s_id(f.k.), District_name
I am using code first and EF and have database created for it called Search
I want my index to show all states in drop down list
following is my State.cs code
public partial class State
{
    public State()
    {
        this.Districts = new HashSet<District>();
        this.Search_master = new HashSet<Search_master>();
    }

    public int Id { get; set; }
    public string State_name { get; set; }

    public virtual ICollection<District> Districts { get; set; }}

this is my District class:
 public partial class District
{
    public District()
    {
        this.Search_master = new HashSet<Search_master>();
    }

    public int Id { get; set; }
    public string District_name { get; set; }
    public int StateId { get; set; }

    public virtual State State { get; set; } }

I also created one viewmodel for state and district....
  public class State_district
{
    public string selectedstate { get; set; }
    public IEnumerable<State> states { get; set; }
    public string selecteddistrict { get; set; }
    public IEnumerable<District> districts { get; set; }
}

inside controller i have written:
 public ActionResult Index()
    {
        var model = new State_district { states = db.States, districts = db.Districts };
        return View(model);}

in the view:
 <div class="editor-field"  id="districtID">*Select State:-
         @Html.DropDownListFor(x => x.states, new SelectList(Model.states, "Id", "State_Name"))
        </div>

With this i am able to see my 1st ddl but how can i bind it with my second list.....
I need code that help me to show me district from selected state only.....can anybody help me with the jQuery code...
thank you in advance!!

A: You are trying to implement a dynamic/cascading dropdown and there are a lot of resources on the internet which can help you with this:

*

*Such as this

*Or this

*And much more on google

A simple non-AJAX implementation would work like this:
You have your first dropdown, created normally:
@Html.DropDownListFor(x => x.states, new SelectList(Model.states, "Id", "State_Name"), new {id = "states"})

Your second dropdown, or dependent dropdown, will need to store some information about which parent item each item is associated with. e.g.:
<select name="selecteddistrict" id="districts">
@foreach (var district in Model.districts)
{
    <option value="@district.Id" data-state-id="@district.StateId">@district.District_name</option>
}
</select>

Notice how each entry in the dropdown has an additional attribute data-state-id. We need this information in order to know which values to show given the current active State.
And then you would add an event handler which handles the change event on your primary dropdown, and update the dependent dropdown accordingly:
<script type="text/javascript">

$(function () {
    $("#states").change(onStateChange).change(); // fire for initial setup
});

function onStateChange() {
    var districtDropdown = $('#districts');
    districtDropdown.find('option').hide();
    var districtsForState = $(districtDropdown.find('option[data-state-id=' + $(this).val() + ']'));
    districtsForState.show();
    districtDropdown.val(districtsForState.val());
}

</script>

Please note the code provided are to demonstrate the concept only.


text:
Q: How to specify options to Custom Formatter in Accumulo I am planning to use same formatter for different accumulo tables with one configurable option.
Is it possible to provide options to Custom Formatter in accumulo? I tried using OptionDescriber but it seems that OptionDescriber gets invoked only during setiterator command.
Or at least is there any way to get current table properties (on which table the custom fomatter is set). I mean if the formatter was set on TABLE_A, then formatter code should be able to load all the table properties during initialization. So that I can set the required properties to table using "config" and the custom formatter can access them.

A: There is currently no way to set options directly on the formatter in the shell. If your custom formatter needs to accept options, you'll have to write your formatter so that it accepts options outside of Accumulo, for example by reading java system properties you set in the environment, or by reading a configuration file stored locally on your system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Cloud SDK installer fails to complete component installation on Windows I downloaded it from here.

gives me error:

Error Log:

Output folder: C:\Users\Info 7\AppData\Local\Google\Cloud SDK
  Downloading Google Cloud SDK core. Extracting Google Cloud SDK core.
  Create Google Cloud SDK bat file: C:\Users\Info
  7\AppData\Local\Google\Cloud SDK\cloud_env.bat Installing components.
  Welcome to the Google Cloud SDK! ERROR: (gcloud.components.update)
  Failed to fetch component listing from server. Check your network
  settings and try again. This will install all the core command line
  tools necessary for working with the Google Cloud Platform. Failed to
  install.

A: I had this issue tonight, and I was able to get by the error message by performing the following:

*

*Install Python 2.7

*Add Python install directory to PATH (my case: c:\Python27)

*Add System Variable CLOUDSDK_PYTHON to be python.exe in the Python install directory (my case: c:\Python27\python.exe)

*Install Google Cloud SDK

A: I had set the environment variable HTTPS_PROXY and forgotten about it. I just had to remove it to get this to work.
I guess you may have the opposite issue if you're behind a proxy so make sure you set it (or maybe HTTP_PROXY) to configure it.


text:
Q: visual-studio-code: fatal error C1090: PDB API call failed, error code '3': vc143.pdb? I am building vtk using vs code with CMake.
The configuring is OK:

Then, I build CommonCore projection, and the bug is reported:
[build] C:\Users\qiang_zhang\Desktop\VTK-9.2.2\Common\Core\SMP\STDThread\vtkSMPToolsImpl.cxx : fatal error C1090: PDB API call failed,error code "3": C:\Users\qiang_zhang\Desktop\VTK-9.2.2\build\Common\Core\CommonCore.dir\Debug\vc143.pdb [C:\Users\qiang_zhang\Desktop\VTK-9.2.2\build\Common\Core\CommonCore.vcxproj]
[proc] The command: "D:\Program Files\CMake\bin\cmake.EXE" --build c:/Users/qiang_zhang/Desktop/VTK-9.2.2/build --config Debug --target CommonCore -j 10 -- exited with code: 1 and signal: null
[build] Build finished with exit code 1

My environment is:
win10, 64 operation system
CMake:
    variant: Debug
    kit: Visual Studio Community 2022 Release-amd64

The availabel kits are:

How can I fix the fatal error C1090 bug? Any suggestion is appreciated~~~


text: Q: How do I see what docker-compose build is doing? docker-compose build is failing.   I want to see what docker-compose build is doing so I can reproduce it step by step and drill down into the problem.  What I'm interested in is a process for finding out what's wrong, not a solution to my current problem.   Setting --log-level DEBUG doesn't seem to help at all.


text:
Q: How to do this calculation in java/groovy? I want a function that can do the below calculation and return the result. I am not sure what does e means in this statistical formula. I am not sure how to convert that formula to java code...that is the issue...specifically e power points....points is a variable which i will pass in as the function arg

This is not homework.

A: As Corbin said, you can find your constant in Java as java.lang.Math.E.
But you probably want to use the Math.exp(Double d) method.
Your calculation is:
 ePoints = Math.exp(Points);
 finalScore = 1000 * (ePoints/(1 + ePoints)) - 10;

You can achieve better precision, but higher risk of overflow, by using:
 ePoints = Math.exp(Points);
 finalScore = (1000 * ePoints)/(1 + ePoints) - 10;

A: e is a constant. Its value is 2.71828....
See e math constant

A: I don't know if that is a know formula or not (maybe a scientific package has it), but this seems to work:
import static Math.pow

def finalScore(points) {
    def e = Math.E
    1000 * pow(e, points) / (1 + pow(e, points)) - 10
}

// lim when points -> 0 of finalScore(points) == 490
assert finalScore(0) == 490

// lim when points -> ∞ of finalScore(points) == 990
assert Math.abs(finalScore(50) - 990) < 0.001


text:
Q: Getting rid of black stripes in 3d pictures generated with asymptote Below is a script cribbed from the asymptote examples from the softwares homepage. I tried to generate a .png image with the script but got the output as shown below.
How can I get rid of the black stripes?! I can't seem to find anything about this in the asymptote manual. Are there any extra commandline flags I must pass while calling the asy executable?
import three;

size(400);

path3 g=(1,0,0)..(0,1,0)..(-1,0,0)..(0,-1,0)..cycle;
draw(g);
draw(O--Z,red+dashed,Arrow3);
draw(((-1,-1,0)--(1,-1,0)--(1,1,0)--(-1,1,0)--cycle));
dot(g,red);


text:
Q: Can I make a QR code to site its favicon.ico? Specifically I want to make a QR code to http://example.com be the favicon for all pages under http://example.com
Is the available resolution good enough?  How do I scale it down? Can I chop off the single pixel white border before scaling down?
Can I pack multiple resolutions -- if so what browsers would show the higher resolutions?

A: Favicons that are displayed by the browser in the URL bar are 16x16 which is not enough for a normal QR code (25x25). You can include a better resolution favicon and some browsers will display it in places but unless the end size on screen is large enough to scan it won't help you. You can see the minimum size you would need on screen for a scan-able code here.

A: Micro QR code is also available, its size is about 15x15 and more px, but not every QRcode reader can read that.
I tried to make this one at my homepage: http://tim.tom.ru

A: I ended up bundling the smallest QR code I could generate 27x27 together with 3 more sizes 54x54, 81x81, and what seemed to be the default: 108x108 using imagemagick to pack them up, roughly as described here: http://bergamini.org/computers/creating-favicon.ico-icon-files-with-imagemagick-convert.html
I did not scale them because at least Chrome and Firefox were able to scale them to their needs, and this way I did not risk messing with the information in the QR code itself. Note that the QR codes go in multiples of 27x27 and the favicons go in multiples of 16x16, hence the risk of losing information when rescaling.
I do not know what happens with IE because I don't have access to it.
The previous answer incorrectly mentions 25x25 as the size of the image because it does not include the white pixel border on each size, which I cannot see as redundant because it serves a purpose in marking off the actual content of the QR code.
I did not research whether removing that 1-pixel white border can still allow a reader to read the QR-code against a variety of backgrounds by making use of the redundant loss-tolerance information in the QR-code.
I did not worry about pixel-resolutions or scanner distance and assumed that the user would be able to create ideal conditions for those factors.
I probably have useless QR-code favicon in the sense that it cannot be scanned right off the browser bar, but hey, it is a legitimate favicon from a non-QR perspective and if someone explicitly downloads the favicon.ico then they do have access to a full QR code :-)
I am accepting my own answer because the other one is less sufficient and I will be happy to switch to accepting another answer if someone comes up with a better one :)


text:
Q: Override as_json or to_json model class name I'd like to modify the classname when calling to_json on an AR model.
i.e.
Book.first.to_json
 #=> "{\"book\":{\"created_at\":\"2010-03-23

Book.first.to_json(:root => 'libro')
 #=> "{\"libro\":{\"created_at\":\"2010-03-23

Is there an option to do this?

A: Since 3.0.5, at least, you do now have the option of passing a :root option to the to_json call. Here is the source of the as_json method on active record now.
def as_json(options = nil)
    hash = serializable_hash(options)

    if include_root_in_json
      custom_root = options && options[:root]
      hash = { custom_root || self.class.model_name.element => hash }
    end

    hash
end

So to use this just @obj.to_json(:root => 'custom_obj')

A: To be compatible with Rails 3, override as_json instead of to_json. It was introduced in 2.3.3:
def as_json(options={})
  { :libro => { :created_at => created_at } }
end

Make sure ActiveRecord::Base.include_root_in_json = false. When you call to_json, behind the scenes as_json is used to build the data structure, and ActiveSupport::json.encode is used to encode the data into a JSON string.

A: You could override the default to_json method in your model, build up a hash of the attributes you want, and then call the hash's to_json method on that.
class Book < ActiveRecord::Base

  def to_json
    { :libro => { :created_at => created_at } }.to_json
  end

end

#=> "{\"libro\":{\"created_at\":\"2010-03-26T13:45:28Z\"}}"

Or if you want all of the records attributes...
def to_json
  { :libro => self.attributes }.to_json
end


text:
Q: How does one normalize this wavefunction? Here is the question:

So I could write $ N = \dfrac{1}{{\sqrt{<Ψ|Ψ>}}} $, right?
Considering the parentheses in the exponential term, it looks like a good idea to switch to spherical polar coordinates. So I used $ x = r sin(θ)cos(φ)$ ; $ y = r sin(θ)sin(φ) $ ; $ z = r cos(θ) $ to rewrite Ψ (without the N, because I'll use the equation above eventually) $$ Ψ(x,y,z) = \sqrt{r sin(θ)cos(φ)r sin(θ)sin(φ)r cos(θ)} * e^{-ar^2} $$$$Ψ(x,y,z) = \sqrt{r^3 sin^2(θ)cos(θ)cos(φ) sin(φ)} * e^{-ar^2} $$$$Ψ(x,y,z) = r^{3/2} sin(θ)[cos(θ)]^{1/2}[cos(φ)]^{1/2} [sin(φ)]^{1/2} * e^{-ar^2} $$
So then, because there are no imaginary terms in the wavefunction,
$$ <Ψ|Ψ> = \int_{0}^{∞} dr \int_{0}^{2π} dθ \int_{0}^{π} dφ [ r^3 sin^2(θ)cos(θ)cos(φ)sin(φ) * e^{-2ar^2}]$$
I don't know if what I've done so far makes sense, or where to go from there. I get the feeling there is an easier way to do this.

A:
So I could write $ N = \dfrac{1}{{\sqrt{<Ψ|Ψ>}}} $, right?

Well, no, not exactly, since you have included "N" in your definition of Psi. But I think that what you think you mean is correct. What you mean to say is that if
$$
\Psi(x,y,z)=Nf(x,y,z)
$$
then
$$
N=\frac{1}{\sqrt{<f|f>}}
$$
not
$$
N=\frac{1}{\sqrt{<\Psi|\Psi>}}\;.
$$
In which case what you are doing is correct:
$$
\int \Psi^2 \equiv 1 = N^2\int d^3r x y z e^{-2a(x^2+y^2+z^2)}\;.
$$
so
$$
N=\frac{1}{\sqrt{\int d^3r x y z e^{-2a(x^2+y^2+z^2)}}}
$$


text:
Q: foldRight on infinite lazy structure According to http://en.wikipedia.org/wiki/Fold_(higher-order_function), a right fold can operate on infinite lists if the full list does not have to be evaluated. This can be seen in action in haskell:
Prelude> take 5 (foldr (:) [] [1 ..])
[1,2,3,4,5]

This does not seem to work well in scala for streams:
Stream.from(1).foldRight(Stream.empty[Int])( (i, s) => i #:: s).take(5)
// StackOverflowError

or on iterators:
Iterator.from(1).foldRight(Iterator.empty: Iterator[Int]){ (i, it) =>
  Iterator.single(i) ++ it
}.take(5)
// OutOfMemoryError: Java heap space

Is there a practical solution to achieve a lazy fold right in Scala?

A: This article makes the same observation, and suggests a lazy solution using scalaz.  Credit to the author, and Tony Morris.


text:
Q: How to add component props to the array when click on that component? How to add component props to the array when you click on that component?
So, I have mapped components <Card />, and when you click on the <Card /> their {name} should be added to the array or removed from the array.
But peopleArr stays empty.
// App.tsx

import React from 'react';
import { useState } from "react";
import Card from "./Card";
import people from "../../data/people";

let arr: string[] = [];

function App() {
const [peopleArr, setNames] = useState(arr);

function addName(name: string) {
  if (name && !peopleArr.includes(name)) {
    setNames((peopleArr) => [...peopleArr, name]);
} else {
    peopleArr.filter((el: string) => el !== name);
}
}

return (

  {people.map((person) => (
    <Card key={person.id} name={person.name} onClick={() => addName(person.name)} />))}

);
}

I tried this and this didn't work out at all
<Card key={person.id} name={person.name} onClick={() => addName(person.name)} />))}

And I tried to add all that things inside <Card /> component and it didn't work out either, also it saved only one name.

A: I think issue is in function calling,your function name is addName but you are calling it addCard

A: The answer is that I had to add in  component itself the props.OnClick
export default function Card({
    key,
    name,
    onClick,
}: {
    key: string;
    name: string;
    onClick: () => void;
}) {
    return (

    );
}


text:
Q: Flutuar metade da lista do Menu Dropdown para outra posição Como fazer para na sexta célula do Menu Dropdown flutuar para esquerda como no exemplo da imagem abaixo:

Tentei sem sucesso algo como:

Código do Menu

Banheiro

Cozinha

Infantil

Jarras & Copos

Limpeza

Mesa

Microondas

Organização

Potes

Tábuas

+ PRODUTOS

A: Imagino que cada
 seja um botão do menu, onde também está incluído um
 que é o menu dropdown do respectivo botão.
Nisso, o seletor correto dos menus, de 6 a 10, seria:
#main-navigation-2 nav ul li.dropdown:nth-child(6) ul,
#main-navigation-2 nav ul li.dropdown:nth-child(7) ul,
#main-navigation-2 nav ul li.dropdown:nth-child(8) ul,
#main-navigation-2 nav ul li.dropdown:nth-child(9) ul,
#main-navigation-2 nav ul li.dropdown:nth-child(10) ul
{
   right: 0;
   left: auto;
}

Ou simplesmente crie um class e adicione nos elementos:
ul.menu_direita{
   right: 0;
   left: auto;
}

Teste (execute em tela cheia):

ul.menu_direita{
   right: 0;
   left: auto;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">

Banheiro

+ PRODUTOS

Cozinha

+ PRODUTOS

Infantil

+ PRODUTOS

Jarras & Copos

+ PRODUTOS

Limpeza

+ PRODUTOS

Mesa

+ PRODUTOS

Microondas

+ PRODUTOS

Organização

+ PRODUTOS

Potes

+ PRODUTOS

Tábuas

+ PRODUTOS

A: Você pode utilizar a classe .dropdown-menu-right para alterar o alinhamento do dropdown

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Item 1

Item 2

Algo

+ PRODUTOS

A: Fiz algo parecido, isso já, só que determinava a direção do menu de acordo com o tamanho da tela, o código era mais ou menos como no exemplo, o menu não era com bootstrap e nem responsivo, fiz o exemplo com as classes do bootstrap, espero que ajude ...

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          Item 1

          Item 2

item-2.1

item-2.2

item-2.3

item-2.4

          Item 3

item-3.1

item-3.2

item-3.3

item-3.4


text:
Q: display tooltip on button focus in blackberry Can anybody tell me how to display ToolTip on blackberry on button focus listener? I am using blackberry 6.0. I have tried Status.show() method. but it display huge tool tip between of the screen. Any other way to display tooltip which display nearby of the field.

A: well, the best way i would suggest is, create a custom labelfield with a arrow kind of a bg image , on button focus listner , show the labelfield with a timer running , and remove the labelfield after sometime, dont know if this is what u r asking for,, we try the same approach in our project.


text:
Q: How to automate an "onclick" if there's no element ID for that line? In Javascript, I'm trying to automate an "onclick()", but the problem is that I don't know how to direct my "onclick()" to that element of interest.
When the element DOES have an ID though, I do this:
var redbutton = "document.getElementById("red_button")"

if (redbutton) {
    redbutton.onclick();
    }

But this time, after looking at the HTML of the page, my "onclick" of interest does not have an ID, so I don't know how to tell my browser to click it.
However, in the line right before it, there is an ID:

Is there a way I can direct my code to that line, then tell it to perform the "onclick"?

A: In jQuery, you can do something like this to trigger a click on the first child:
$('#buttoncolor_pane').children().first().click()

A: You could use querySelector or querySelectorAll: (can be called on a node or document)
// get all div elements that are direct children of #buttoncolor_pane
var nodes = document.querySelectorAll('#buttoncolor_pane > div');
if (nodes === null) {
    return; // or do some other error handling
}

for (var i = 0; i < nodes.length; i++) {
    nodes[i].onclick();
}

You can use any query selector you like  as a parameter. If you just want one, use querySelector instead. it's the same, but instead of returning a NodeList, it returns a Node, so you can just use it directly.
In this particular case, querySelectorAll will only return one element, but I think you get the idea.
Or, if you really just want the first child, then use firstChild:
document.getElementById('buttoncolor_pane').firstChild.onclick();


text:
Q: Django Login with preset single Username and Password I am trying to create a simple login page, for anyone who has the username and password should be able access to some specific links.
I found some tutorials which teach registration, login, logout using auth templates, but they need me to do user registration first.
I could not find any basic tutorial, which can just help me set a default username and password, without creating a signup page.
I know this question is not specific, but any heads up will be very helpful!

A: If you don't want to create a signup page, simply don't create it.
Only create a login page.
Another thing, you want to give access to specific links only to those who have a username password,
I do it by this way,
 {% if user.is_authenticated %}

 Sign Out

 {% else %}

 Sign Up

 Login

 {% endif %}

Its simple enough. Don't create the signup view and template. Just create the login,logout view and template.


text:
Q: Cassandra CQL versions What version of CQL is CQLv4?  Looking at the product compatibility page of the documentation shows versions 3.4, 3.3, 3.2... etc.  Does the v4 in CQLv4 stand for 3.4?
I'm trying to find which versions of Cassandra are compatible with CQLv4.
https://docs.datastax.com/en/landing_page/doc/landing_page/compatibility.html?scroll=compatibilityDocument__cql-versions

A: I think that this table could do a better job for you. Protocol version 4 starts with Cassandra 2.2, and continues to version 3.x


text:
Q: Post a json patch in Swift 5 I'm testing an api call in Swift with Patch to update an object partially.
It worked well with Postman
PATCH http://localhost:5000/api/accounts/eca9c1b05fb24ca192afe370aa5a1965

[
    {
        "op": "add",
        "path": "/firstname",
        "value": "wakaka"
    }
]

Here's my playground:
let urlString = "http://localhost:5000/api/accounts/eca9c1b05fb24ca192afe370aa5a1965"

let url = URL(string: urlString)

var request = URLRequest(url: url!)

//        guard var request = request else { return nil }

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("gzip, deflate, br", forHTTPHeaderField: "Accept-Encoding")

request.httpMethod = "PATCH"

let jsonPatch = "[{\"op\" : \"add\", \"path\" : \"/firstname\", \"value\": \"my first name\"}]"

do {
    let encodedResult = try JSONEncoder().encode(jsonPatch)
    print(encodedResult.debugDescription)

    request.httpBody = encodedResult
    print(request.httpBody?.description)
} catch let error {
    print(error.localizedDescription)
}

// decoding
URLSession.shared.dataTask(with: request) { (data, response, error) in
    if error != nil {
        print("err: ",error.debugDescription)
        return
    }

    // handling api's errors
    if let res = response as? HTTPURLResponse {
        print(res.statusCode)

        switch res.statusCode {
        case 400:
            print("400")
//            completion(.failure(ApiError.badRequest))
            return
        case 409:
            print("409")
            return
        case 422:
            print("422")
            print(res.debugDescription)
            return
        default:
            break
        }
    }

    // OK
    do {
        let result = try JSONSerialization.jsonObject(with: data!, options: [])
        print("json:", result)

    } catch let jsonError {
        print("error:", jsonError.localizedDescription)
    }
}
.resume()

The result I got:
<NSHTTPURLResponse: 0x600000921320> { URL: http://localhost:5000/api/accounts/eca9c1b05fb24ca192afe370aa5a1965 } { Status Code: 422, Headers {
"Content-Length" =     (
350
);
"Content-Type" =     (
"application/problem+json; charset=utf-8"
);
Date =     (
"Thu, 10 Jun 2021 15:59:29 GMT"
);
Server =     (
Kestrel
);
} }
That weird when it returns 422 while my call on Postman works well. Thanks for any advice!


text:
Q: How will a rotating, circular, and cylindrical body of a superfluid develop in outer space? Let's consider a rotating (about its center, in the plane cutting the initial circular and cylindrical form into two halves), circular, and cylindrical body of a superfluid somewhere in outer space. Obviously, the fluid will never stop rotating (that's why I choose a superfluid instead of a normal fluid with viscosity).
How will the form of this body of superfluid evolve?
Will it because of centrifugal forces flatten out? Will rings emerge? Will different parts have different velocities after some time? Or will all the constituents parts move away from each other due to a lack of viscosity (like a vertical ray of water, under the influence of gravity, will be divided into droplets lower than a ray of honey, due to its lower viscosity? For sure some orderly form will develop.


text:
Q: Accessing SF Explorer on secured cluster I followed the steps to secure a SF cluster using a self-signed cert and an ARM template using one of the samples. It deploys fine but I am unable to access the SF Explorer due to the security cert not being trusted. If I tell Chrome to proceed anyway I get just a blank page, no SF Explorer.
How do I get the cert installed correctly locally and tell Chrome (or other browsers) to use it? I am trying to access the SF Explorer via https instead of the normal http.
Along the same lines, how will the cluster being secure change how I deploy apps from Visual Studio and powershell commands? Have I missed some pertinent document on this or is it not well covered?

A: Installing the cert to the CurrentUser store on your PC should be sufficient to make it accessible for authenticating to SF Explorer. Note that this won't make the warning go away, however, as that is a function of the browser not trusting the server's certificate. You can get rid of that warning by adding the cert to the trusted store on your machine.
Once the cert is installed in the CurrentUser store, the browser should pop up a dialog to ask you to choose the cert you want to use to connect to SF Explorer.
As for deploying apps, the Publish flow in VS will automatically fetch the necessary cert metadata for secure clusters and store it in your publish profile so that the cert gets picked up from the local store at connection time, as described here.


text:
Q: Postgres: optimize query where column is in string Lets say I have a table like so:
webpages

id  |  url
------------------------
 1  |  http://example.com/path
 2  |  example2.biz/another/path
 3  |  https://www.example3.net/another/path

And I want to search which webpages' url column is a substring of an input string. I know I can do it like this:
SELECT id FROM webpages WHERE STRPOS(url, 'example.com/path/to/some/content') > 0;

Expected result: 1

But I'm not sure how I might optimize this kind of query to run faster. Is there a way?
I found this article, it seems to suggest not - though I'm not sure if that's still true as it's from over a decade ago.
https://www.postgresql.org/message-id/046801c96b06%242cb14280%248613c780%24%40r%40sbcglobal.net


text:
Q: How to send a question from an external resource too IBM Watson assistant so that the chatbot can answer I have a speech to text converter implemented in python and I want the text result to be sent to the chatbot so that it can answer me.
Example:
Guy (voice): I need my bank account info
The code translates that to text and sends "I need my bank account info" to the chatbot.
The chatbot then replies with bank account info or anything (doesnt matter)

A: There is a Python SDK, amongst others, that will allow you to interact with the Watson Assistant service - https://cloud.ibm.com/apidocs/assistant/assistant-v2?code=python
The flow is:

*

*authenticate

*create a session

*send a message

You will of course need to create the assistant dialog - https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-getting-started


text:
Q: How to build java agent from source and static load in tomee application by maven? We are using java agent to customize some runtime initialization steps, it works by manually build the java agent and include the jar in JAVA_OPTS in catalina.sh. As it's not good to add jar into code repository, we expect build both java agent and our web application by maven, besides inject the java agent in the application as described above. How could we achieve it by maven? Thanks!

A: In one pom.xml, We used maven-war-plugin to build application war and maven-assembly-plugin to build java agent fat jar:
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 http://maven.apache.org/xsd/assembly-2.1.0.xsd">
  <id>agent</id>
  <formats>
      <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <fileSets>
      <fileSet>
          <directory>${project.build.directory}/classes</directory>
          <outputDirectory>.</outputDirectory>
          <includes>
            <include>package/**</include>
          </includes>
      </fileSet>
  </fileSets>
  <dependencySets>
    <dependencySet>
      <useProjectArtifact>false</useProjectArtifact>
      <outputDirectory>lib</outputDirectory>
      <unpack>true</unpack>
      <includes>
        <include>org.json:json</include>
      </includes>
    </dependencySet>
  </dependencySets>
</assembly>


text:
Q: How to get the height of Mac unified title and toolbar in Qt/C++ I have a Qt 4.7.4 with C++ app that uses the unified title and toolbar on Mac:
    setUnifiedTitleAndToolBarOnMac(true);
At some point while my app is running, I need to know programmatically what the height of the unified title and toolbar is.
How can I get its height?

A: At least with Qt 4.8.4 and Mountain Lion, this looks a bit buggy:
With toolbar on, QMainWindow::frameGeometry() reports wrong y position but correct total window size. Its height() minus QMainWindow::geometry()'s height() is the height of title bar and unified toolbar together in my tests. To find out how tall the toolbar alone is, you could hide it and use the difference.
The Qt people working on this seem to have a few problems and have discontinued QMainWindow::setUnifiedTitleAndToolBarOnMac():

The unified toolbar implementation from Qt 4 has not and will not be ported
    to Qt 5. This means calling QMainWindow::setUnifiedTitleAndToolBarOnMac has
    no effect on Qt 5. A replacement API which wraps NSToolbar is available in
    QtMacExtras.


text:
Q: copy NSManagedObject to a new object in memory I have a menu screen that populates with data from an NSManagedObject.  While this screen is up the user can enter in all sorts of values. etc.
The problem I am having is that I need to not alter the initial NSManagedObject used to populate the screen.  I need a copy that the user can alter instead because if they cancel out before everything is done, then what was the original and correct information gets corrupt by impartial data.
However, I am having issues implementing any kind of copy method or process inside my NSManagedObject because all of the properties are @dynamic.
If I just 'return self' in a copyWithZone method inside the NSManagedObject, would that properly copy everything?

A: What you want is to make your changes to the same NSManagedObject, but in a child NSManagedObjectContext. That way, if you need to discard the changes, you can just throw the child context away without affecting your main context or object. See this question.

A: Why not use a category to add a copy method to your custom NSManagedObject?
If your NSManagedObject was User, then create a new category User+copy.h/m where in you would add the copy method which would simply copy all the individual fields one by one.


text:
Q: Not getting Places data using google Places API - This API project is not authorized to use this API I am using the code from the question asked here Autocomplete textview google places api description -> place_id. I changed the code to add it to my app. When I run the code it is giving me the below response when I run the code
07-28 11:17:19.244: E/result(350): {"error_message":"This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console: Learn more: https:\/\/code.google.com\/apis\/console","predictions":[],"status":"REQUEST_DENIED"}

I searched for some threads and from the below threads

*

*Maps API keys for geocoding not working

*This IP, site or mobile application is not authorized to use this API key
and one or two other

I did the follow steps as suggested.

*

*Created a Server Key from console and added it to project.

*Enabled Places API from console.

*Enabled Geocoding API from console.

You can see in below image.

and when I run the code it still shows me the error mentioned above. Do I need to Enable any other APIs from console.
The maps are working good except this. In case you want to know this is my api key added in manifest.
<!-- Goolge Maps API Key Development mode -->
            <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAbo3luzbyQTuuPLOyo_Ml***********" />

and I am adding server key directly to request url as below
private ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
        Log.e("result",jsonObj.toString());
        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description")+ "," + predsJsonArray.getJSONObject(i).getString("place_id") );
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }
    return resultList;
}

Please Help.

A: Needed some more thorough research and after some trial and error it worked. main thing was that I needed to enable Google Places API Web Service. and it worked like charm.
Hope this helps someone out there.


text:
Q: how can I start laravel artisan serve I am using Laravel and trying to start a PHP artisan server but I get the following error:
PHP Fatal error:  Uncaught Error: Class 'Illuminate\Foundation\Application' not found in C:\Users\Admin\Budget\bootstrap\app.php:14
Stack trace:
#0 C:\Users\Admin\Budget\artisan(20): require_once()
#1 {main}
  thrown in C:\Users\Admin\Budget\bootstrap\app.php on line 14

How can I fix this?


text:
Q: Resize a QWidget containing a QVBoxLayout in runtime when contents are partially Hidden In this application, a list of HBoxLayouts is generated and put into a VBoxLayout in order to form a dynamically filled list of commands.  There is a button above each sub-list which has the capability to hide the controls below it.  The problem: when a sub-list is hidden, the widget which contains the broadest VBoxLayout does not change in size! The VBoxLayout then stretches to compensate.  I want the container widget to shrink when it contains fewer items!
 It looks like this:
The problem is, when I hide a list under one of the PushButtons, the containing widget won't shrink! the VBoxLayout just expands when there are less visible items :(
Here is a picture of how I see my little GUI.
Here is some code from the broader layout setup:
scrollArea = new QScrollArea(this);
scrollAreaLayoutWidget = new QWidget(scrollArea);
scrollAreaLayout = new QVBoxLayout(scrollAreaLayoutWidget);
//scrollAreaLayout is filled with all the stuff you see inside the scroll area...
scrollArea->setWidget(scrollAreaLayoutWidget);

I have tried changing the QSizePolicy of the container widget (blue box) in a number of ways.  I've found dozens of resizing questions but I have somehow not discovered an answer. Is there a magic auto-resize setting that I'm missing?
Let me know if this is painfully vague or incomplete.
Any comment is welcome!

A: Turns out all I had to do was create a custom SLOT for when the button that hides part of the Ui is clicked and hide the relevant widget within that function. In the same function, I called [containerWidget]->adjustSize(); and it did exactly what I was looking for.


text:
Q: mysql join query help I am using mysql db.
I have 2 tables.
I'm building a user suggestion list which selects user list from 2 tables.
First table (users) have the user information.
Second table (followers) contains follow list.
I need to select suggestions
My query is like
SELECT a.*, b.userid, b.friendid, a.userid
FROM users a,followers b
WHERE a.userid != '$uid'
AND (b.friendid != a.userid AND b.userid != '$uid')

But this query returns all the data including already followed users also.
Please help me.
Thanks in advance.

A: You're not joining the two tables, so you're going to get everything that isn't excluded by the WHERE clause.
Your question is a bit unclear, but I suspect you're looking for:
SELECT a.*, b.userid, b.friendid, a.userid
FROM users a,followers b
WHERE a.userid != '$uid'
AND b.userid = a.userid
AND b.friendid != a.userid

A: Try
select * from users
 where userid != '$uid' and
 userid not in (select friendid from followers where userid='$uid')


text:
Q: react history.push does not work neither does useHistory I am wanting to redirect to another page on form submit.
I have read and seen several articles advising on using:
this.props.history.push("/")

As well as the suggestion to use:
import { useHistory  } from 'react-router-dom';
//Followed by
let history = useHistory();
history.push("/");

However neither work for me, the:
this.props.history.push("/")

Produces the following error:
Uncaught (in promise) TypeError: _this.props.history.push is not a function

And the usage of:
import { useHistory  } from 'react-router-dom';
//Followed by
let history = useHistory();
history.push("/");

produces the following error:
sp-webpart-workbench-assembly_en-us_3b6fc7db2fe02279bf3499609f870638.js:69 Uncaught (in promise) Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321

For reference, here is what my component looks like, no duplicate calls:
    import * as React from 'react';
import { HttpClient, AadHttpClient, SPHttpClient, SPHttpClientConfiguration, HttpClientResponse, ODataVersion, ISPHttpClientConfiguration } from '@microsoft/sp-http';
import styles from './MyChildComponent.module.scss';
import { MyChildComponentProps } from './MyChildComponentProps';
import { Form, Formik, Field } from 'formik';
import {
  FormikTextField,
  FormikDropdown,
} from 'formik-office-ui-fabric-react';
import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react';
import { FormValuesValidation } from '../../utility/FormValuesValidation';
import { useHistory  } from 'react-router-dom';

export default class MyChildComponent extends React.Component<MyChildComponentProps, {}> {
  private error: Error = null;

  public constructor(props: MyChildComponentProps){
   super(props);
   this.state = {
   };
 }

  public componentDidMount() {

  }

  public render(): React.ReactElement<MyChildComponentProps> {

    let formValues = new FormValuesValidation();
    formValues.assignment = this.props.memberID;
    formValues.fullname = this.props.name;

    return (

          <Formik
            initialValues={formValues}
            onSubmit={(values, actions) => {
              try{
                this.props.service.postMyForm(this.props.memberID, values)
                .then((result) => {
                 switch (result) {
                   case 200:
                      this.props.history.push("/");
                   case 500 : case 404: case 401:
                      this.props.history.push("/errorPage");
                   default:
                     break;
                 }
                },
                  (error: any) => {
                    console.log("Something really bad happened", error);
                  }
                );
              } catch (e) {
                console.log("an error occured", e);
                this.error = e;
              }
            }}
            render={({ values, touched, errors, ...props }) => (

                <form onSubmit={props.handleSubmit}>

                  <Field
                    name="fullname"
                    label="Employee Name"
                    component={FormikTextField}
                    disabled
                  />

                  <Field
                    name="memberID"
                    label="Employee No"
                    component={FormikTextField}
                    disabled
                  />

                    <PrimaryButton
                      type="submit"
                      disabled={!props.dirty || !props.isValid}
                    >
                      Submit
                    </PrimaryButton>

                    <DefaultButton
                      type="button"
                      onClick={() => props.resetForm()}
                      disabled={!props.dirty}
                    >
                      Reset
                    </DefaultButton>

                </form>

            )}
          />

    );
  }
}

The component I am trying to do this in is a child component and pass in history as a props to the component.
Any help appreciated!

A: You must use withRouter to be able to use the history object as stated in react-router doc:

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

So like the doc, you should do something like this:
class YourComponent extends React.Component {

  render() {
    const history = this.props.history;

    return <button onClick={() => {history.push("/")}}></button>;
  }
}

const YourComponentWithRouter = withRouter(YourComponent);

A: So resolved this by converting my functional component into a class component and then importing:
import { RouteComponentProps } from 'react-router';

As I was receiving the following error:
Argument of type 'typeof MyChildComponent ' is not assignable to parameter of type 'ComponentType<RouteComponentProps<any, StaticContext, unknown>>'.

The error was due to the types as I am using Typescript, below is what my converted/completed code looks like, I had to extend my props to use RouteComponentProps:
import * as React from 'react';
import { HttpClient, AadHttpClient, SPHttpClient, SPHttpClientConfiguration, HttpClientResponse, ODataVersion, ISPHttpClientConfiguration } from '@microsoft/sp-http';
import styles from './MyChildComponent.module.scss';
import { Form, Formik, Field } from 'formik';
import {
  FormikTextField,
  FormikDropdown,
} from 'formik-office-ui-fabric-react';
import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react';
import { FormValuesValidation } from '../../utility/FormValuesValidation';
import { useHistory, withRouter, Redirect  } from 'react-router-dom';
import { RouteComponentProps } from 'react-router';
import { MyServices} from "../../../services/myservices/services";

class MyChildComponent extends React.Component<MyChildComponentProps> {
  private error: Error = null;

  public constructor(props: MyChildComponentProps){
   super(props);
 }

    public componentDidMount() {

  }

    public render(): React.ReactElement<MyChildComponentProps> {
        let formValues = new FormValuesValidation();
    formValues.memberID= this.props.memberID;
    formValues.fullname = this.props.name;

    return (

          <Formik
            initialValues={formValues}
            onSubmit={(values, actions) => {
              try{
                this.props.service.postForm(this.props.memberID, values)
                .then((result) => {
                 switch (result) {
                   case 200:
                     this.props.history.push("/");
                     break;
                   case 500 : case 404: case 401:
                      this.props.history.push("/errorPage");
                      break;
                   default:
                     break;
                 }
                },
                  (error: any) => {
                    console.log("Something really bad happened", error);
                  }
                );
              } catch (e) {
                console.log("an error occured", e);
                this.error = e;
              }
            }}
            render={({ values, touched, errors, ...props }) => (

                <form onSubmit={props.handleSubmit}>

                  <Field
                    name="fullname"
                    label="Employee Name"
                    component={FormikTextField}
                    disabled
                  />

                  <Field
                    name="memberID"
                    label="Employee No"
                    component={FormikTextField}
                    disabled
                  />

                    <PrimaryButton
                      type="submit"
                      disabled={!props.dirty || !props.isValid}
                    >
                      Submit
                    </PrimaryButton>

                    <DefaultButton
                      type="button"
                      onClick={() => props.resetForm()}
                      disabled={!props.dirty}
                    >
                      Reset
                    </DefaultButton>

                </form>

            )}
          />

        );
    }
}

export interface MyChildComponentProps extends RouteComponentProps {
  description: string;
  service: MyServices;
  memberID: string;
  name: string;
}

export default withRouter(MyChildComponent);


text:
Q: Full Outer Join with Group By [UPDATED]: I have updated the question with the WHERE clause.
I have the following SQL Fiddle. The result is:
|   User |          Name |   Time |
|--------|---------------|--------|
|  00001 |     Mary Jane |     12 |
|  00002 |   Joana Smith |      7 |
|  00003 |  George Andrz |      2 |
|  00004 | Julia Roberts |      4 |

I am expecting this:
|   User |          Name |   Time |
|--------|---------------|--------|
|  00001 |     Mary Jane |     12 |
|  00002 |   Joana Smith |      7 |
|  00003 |  George Andrz |      2 |
|  00004 | Julia Roberts |      4 |
|  90000 | Anderson Math |      0 |
|  90001 |      Josh Xin |      0 |

The difference is: There are some users in the table MainUsers that
  could not have done the TimeSheet yet, so the TimeSheet table is empty
  for the person. But I would like to show the name, with the Time = 0

SQL Fiddle
MS SQL Server 2008 Schema Setup:
CREATE TABLE MainUsers
(
  id int identity primary key,
  UserID varchar(5),
  FullName varchar(500),
);

INSERT INTO MainUsers
(UserID, FullName)
VALUES
('00001', 'Mary Jane'),
('00002', 'Joana Smith'),
('00003', 'George Andrz'),
('00004', 'Julia Roberts'),
('90000', 'Anderson Math'),
('90001', 'Josh Xin');

CREATE TABLE TimeSheet
(
  id int identity primary key,
  UserID varchar(5),
  FullName varchar(500),
  Minutes int,
  TimeStamp Datetime,
);

INSERT INTO TimeSheet
(UserID, FullName, Minutes, TimeStamp)
VALUES
('00001', 'Mary Jane', 240, '2015-09-16 08:16:00'),
('00001', 'Mary Jane', 480, '2015-09-16 08:16:00'),
('00002', 'Joana Smith', 320, '2015-09-16 08:16:00'),
('00002', 'Joana Smith', 120, '2015-09-16 08:16:00'),
('00003', 'George Andrz', 120, '2015-09-16 08:16:00'),
('00004', 'Julia Roberts', 240, '2015-09-16 08:16:00');

Query 1:
SELECT u.UserID AS [User], u.FullName AS Name,
       SUM(t.Minutes) / 60 AS [Time]
FROM MainUsers u LEFT JOIN
     TimeSheet t
     ON u.UserID = t.UserID
WHERE
    month(TimeStamp) = 9 and year(TimeStamp) = 2015
GROUP BY u.UserID, u.FullName
ORDER BY u.UserID ASC

Results:
|  User |          Name | Time |
|-------|---------------|------|
| 00001 |     Mary Jane |   12 |
| 00002 |   Joana Smith |    7 |
| 00003 |  George Andrz |    2 |
| 00004 | Julia Roberts |    4 |

Thanks.

A: try this:
SELECT
    u.UserID AS 'User',
    u.FullName AS Name,
    isnull(SUM(Minutes) / 60,0) AS [Time]
FROM
    MainUsers u left OUTER JOIN
    TimeSheet t  ON
    u.UserID = t.UserID
GROUP BY
    u.UserID,
    u.FullName
ORDER BY
    u.UserID

SQL Fiddle
if you want to include conditions on your timesheet table, such as
month(timestamp) = 9 and year(timestamp) = 2015
and you do it in the WHERE clause, it converts your outer join to an inner join because the WHERE clause requires fields in the timestamp table.  To limit by month and year of your left outer joined table, you put the conditions in the JOIN clause instead of WHERE, like:
SELECT
    u.UserID AS 'User',
    u.FullName AS Name,
    isnull(SUM(Minutes) / 60,0) AS [Time]
FROM
    MainUsers u left OUTER JOIN
    TimeSheet t  ON
    u.UserID = t.UserID and
    month(timestamp) = 9 and year(timestamp) = 2015
GROUP BY
    u.UserID,
    u.FullName
ORDER BY
    u.UserID

sql fiddle

A: I think you want a left join.  Presumably, everyone with a timesheet is a valid user.  And you seem to want to keep all the users.
In general, when you use full outer join you have to be very careful about NULL values.  COALESCE() ends up being used extensively.  So, your query can be written as:
SELECT u.UserID AS [User], u.FullName AS Name,
       SUM(t.Minutes) / 60 AS [Time]
FROM MainUsers u LEFT JOIN
     TimeSheet t
     ON u.UserID = t.UserID
GROUP BY u.UserID, u.FullName
ORDER BY u.UserID ASC;

Also note that the query is much easier to follow when your table aliases are abbreviations for the table names. A and B don't mean anything.  But it is clear that t stands for TimeSheet.
Finally, the time column is probably hours as an integer -- assuming that Minutes is an integer. (And it would be better called something like "hours".)  If you want decimal hours, then divide by 60.0, rather than 60.

A: *

*Change Join from FULL OUTER to RIGHT OUTER

*Group by should be applied on userid and name of MainUsers table and not on TimeSheets

*Select list should be accordingly modified.

SQL Fiddle
Query 1:
SELECT
    B.UserID AS 'User',
    B.FullName AS Name,
    SUM(A.Minutes) / 60 AS [Time]
FROM
    TimeSheet A
RIGHT OUTER JOIN MainUsers B ON A.UserID = B.UserID
GROUP BY
    B.UserID,
    B.FullName
ORDER BY
    B.UserID ASC

Results:
|  User |          Name |   Time |
|-------|---------------|--------|
| 00001 |     Mary Jane |     12 |
| 00002 |   Joana Smith |      7 |
| 00003 |  George Andrz |      2 |
| 00004 | Julia Roberts |      4 |
| 90000 | Anderson Math | (null) |
| 90001 |      Josh Xin | (null) |

I guess, This is what you are looking for.
Hope it might help you. :)


text:
Q: Implementing Maybe version of GHC.Exts 'the' function GHC.Exts exports the function the:

the ensures that all the elements of the list are identical and then returns that unique element

This function is partial as it throws an error in case not all elements of the list are equal.
How can I implement a function theMay that returns a Maybe instead?

A: the is defined as follows:
the :: Eq a => [a] -> a
the (x:xs)
  | all (x ==) xs = x
  | otherwise     = error "GHC.Exts.the: non-identical elements"
the []            = error "GHC.Exts.the: empty list"

Based on this we can directly deduce theMay:
theMay :: Eq a => [a] -> Maybe a
theMay (x:xs)
  | all (x ==) xs = Just x
  | otherwise     = Nothing
theMay []         = Nothing

A: Same thing, but using the Maybe monad:
import Data.Maybe (listToMaybe)
import Control.Monad (guard)

theMay :: Eq a => [a] -> Maybe a
theMay xs = do
    x <- listToMaybe xs
    guard $ all (x ==) xs
    return x

(Apologies for golfing in your Q&A...)


text:
Q: BeautifulSoup not handling HTML table inside anchor tag Consider the sample HTML code:
<!DOCTYPE html>

    <title>Testing</title>

                Hello

On using BeautifulSoup on this via:
html_soup = BeautifulSoup(html_source_code,"lxml")
I get:
<!DOCTYPE html>

    <title>Testing</title>

            Hello

Note how the table is no longer contained within the anchor tag, thereby altering the output.
I have run the source code through online validators (e.g. https://validator.w3.org/) and they return no errors or warning, and so I believe there is nothing wrong with the HTML code itself.
Why does BS cause this error, and how can I fix it?
p.s. Not trivial for me (in my real use case) to move the  tags to inner  elements owing to pre-defined and CSS and JS features.

A: Use "html.parser"
Ex:
from bs4 import BeautifulSoup

html_source_code = """<!DOCTYPE html>

    <title>Testing</title>

                Hello

"""

html_soup = BeautifulSoup(html_source_code,"html.parser")
print(html_soup.prettify(formatter='html'))

Output:
<!DOCTYPE html>

  <title>
   Testing
  </title>

      Hello


text:
Q: When should I use the destructor? In C# I learned I can create a class destructor as follows:
public class MyClass
{
    ~MyClass()
    {

    }
}

My question is when and in what situation should I be using a destructor in C#, if ever?
Is there one common use case I should watch out for?

A: The programmer has no control on when the destructor is going to be executed because this is determined by the Garbage Collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits. When a destructor executes what is happening behind the scenes is that the destructor implicitly calls the Object.Finalize method on the object's base class.
destructor code is implicitly translated to something like this :
protected override void Finalize()
{
   try
   {
      // Cleaning up .
   }
   finally
   {
      base.Finalize();
   }
}


text:
Q: What is the relation of different services in software design/architecture? Only in the past 3 years I got in contact with enterprise architecture and its terminology. The more I read about it the more I was confused about the term "service" that appears to have a multitude of meanings.
For example in the context of Domain-Driven Design (DDD) there are domain services, application services and infrastructure services. There is the term service layer and, of course, there is Service-Oriented Architecture and microservices.
What I keep wondering about is which of these terms describe intersecting concepts and which do not. Are the services from DDD part of (a) service layer(s) or does the term service layer only apply if it necessarily provides access to some sort of networking client? Does the term "service" in service layer, SOA und microservices refer to this same aforementioned concept or is one a subset of the other?
Update
I am quite certain now that the way I asked this question makes it easy to misunderstand it. It was never supposed to be a general question about the term "service" but about the relation between the given terms in the second paragraph (e.g. Which ones do intersect? Which one is (or could be) a subset of the other? What level of abstraction do these concepts belong to? Are there potentially is-a relationships among these concepts? etc.)
Update 2
This SE answer and this blog post answer my question.

A: The fundamental meaning of the word "service," as it pertains specifically to Software Engineering contexts, is the same meaning as the word "service" when applied to any other context:

A system supplying a public need, such as transport, communications, or utilities such as electricity and water.

All services (including public utility and computing services) have some common characteristics and considerations:

*

*Access Controls

*Billing

*Capacity

*Interfaces

*Maintenance

*Metering

*Quality of Service

*Regulation

*Resources

And so on.
In the case of a computing service, the public need is often data, but it can also be storage, infrastructure, application, processing or computational resources.

A: While I agree with @RobertHarvey, I think I also understand what the OP is looking for. I think the simplest way to describe it is thusly:
A DDD service provides a cross-cutting capability within a given piece of software.
A networked service (eg web service) is itself a piece of software which provides cross-cutting capability to other pieces of software.
Note that a DDD service could easily be a facade for an application to access a networked service.


text:
Q: Html to Markdown How to convert HTML to Markdown using powershell?
Is there any possibility to convert it without using ugly constructions as:
    $content = $content -replace "", "*"
    $content = $content -replace "", "*"
    $content = $content -replace "", "**"
    $content = $content -replace "", "**"
    $content = $content -replace "", "**"
    $content = $content -replace "", "**"
    $content = $content -replace """, "'"
    $content = $content -replace ''
    $content = $content -replace ''


text:
Q: An Array of objects in php  I dont understand this why i get this error! is so simple yet very different in php.
<?php
    $x=new DisplayTaxonomy ();
    $myarray= array();
    $x->setADTitle("bunkers");
    echo $x->getADTitle();

    $myarray =$x;//i also tried array_push($$x, $myarray); same error
    echo $myarray[0]->getADTitle();
?>

Fatal error: Cannot use object of type DisplayTaxonomy as array in C:\xampp\htdocs\wordpress\wp-content\plugins\exec-php\includes\runtime.php(42) : eval()'d code on line 9
<?php
 class DisplayTaxonomy {
    public $ADTitle;
 public function setADTitle($ADTitle)
    {
        $this->ADTitle = $ADTitle;
    }
    public function getADTitle()
    {
        return $this->ADTitle;
    }
?>

A: Use the [] operator to append $x onto $myarray:
$myarray[] = $x;
echo $myarray[0]->getADTitle();

Or via array_push(), which as a function call can be a tiny bit less efficient than using the [] lanugage construct.
array_push($myarray, $x);

The methods for defining and adding to arrays are detailed in the PHP manual on Arrays.

A: $myarray = $x;

should be
$myarray[] = $x

A:
As of PHP 5.4 you can also use the short array syntax, which replaces
  array() with [].

This allows you to both initialize and add objects to an array:
<?php
class DisplayTaxonomy
{
    public $ADTitle;

    public function setADTitle($ADTitle)
    {
        $this->ADTitle = $ADTitle;
    }

    public function getADTitle()
    {
        return $this->ADTitle;
    }
}

$x = new DisplayTaxonomy();
$x->setADTitle("bunkers");
//echo $x->getADTitle();

$myarray[] = $x; // Notice no previous array initialization
echo $myarray[0]->getADTitle();
?>

A: In php, array appending is like this:
$myarray[] = $x

What you are doing is assigning $myarray to your DisplayTaxonomy object, and then trying to use your object as an array with array-subscripting ($myarray[0]). Thus the error.
As an aside, if you are going to use getters and setters for a property, you should not expose that property as public. Try either protected $ADTitle; or just don't use getters and setters.

A: The reason is because you're assigning the object to $myarray when you do:
$myarray = $x. At this point, $myarray is no longer an array, but the object that you assigned to it, namely $x.
In your comment in the code, you say that you also tried array_push($$x, $myarray). The reason that this doesn't work is for two reasons.
Reason 1: You are using $$x instead of $x. If you have two dollar signs ($$x), it is the equivalent of ${$x}, which will first turn $x into a string (probably "Object #1" or something like that), and then look for the variable called: ${'Object #1'}, which obviously doesn't exist. For example, if you have a variable called $something, you can also use it like this: ${'something'}. So if you have a variable that contains the literal string "something", for example $var_name = 'something';, then you could do either ${$var_name} or $$var_name. Both cases will get the content of the variable $something.
Reason 2: You're also putting them in the wrong order in array_push.
This should work instead:
array_push($myarray, $x)
But as others have pointed out, this is the exact equivalent: $myarray[] = $x.
I hope that helps explain how things work.


text:
Q: Changing URI suffix in Joomla when adding child php pages I have added a new directory in my joomla website:
http://sitedomain.tld/xxx/
then I have added index.php in that directory
here is the code
    define( '_JEXEC', 1 );

define('JPATH_BASE', '..' );

define( 'DS', DIRECTORY_SEPARATOR );

require_once ( '../includes/defines.php' );
require_once ( '../includes/framework.php' );

//JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null;

/**
 * CREATE THE APPLICATION
 *
 * NOTE :
 */

$mainframe =& JFactory::getApplication('site');
$template_name = $mainframe->getTemplate();;

$mainframe->initialise();

JPluginHelper::importPlugin('system');

/**
 * ROUTE THE APPLICATION
 *
 * NOTE :
 */
$mainframe->route();

// authorization
$Itemid = JRequest::getInt( 'Itemid');
$mainframe->authorize($Itemid);

// trigger the onAfterRoute events
//JDEBUG ? $_PROFILER->mark('afterRoute') : null;
//$mainframe->triggerEvent('onAfterRoute');

/**
 * DISPATCH THE APPLICATION
 *
 * NOTE :
 */
$option = JRequest::getCmd('option');
//$mainframe->dispatch($option);

// trigger the onAfterDispatch events
//JDEBUG ? $_PROFILER->mark('afterDispatch') : null;
//$mainframe->triggerEvent('onAfterDispatch');

/**
 * RENDER  THE APPLICATION
 *
 * NOTE :
 */

$mainframe->render();

/**
 * RETURN THE RESPONSE
 */

var_dump($document->getHeadData());
echo JResponse::toString($mainframe->getCfg('gzip'));

sdwdwd
wdwd
When I view this page in the browser, all the dynamic links like CSS, JS and images were suffixed by the /xxx/ path which make them broken !
How can I drop this suffix or how do I change this suffix from /xxx to / to it points to the original files location?
I have tried setting the JDocument::setBase and also tried to play with the JURI object and changed its _path and _uri without any change
Thanks

A: Shouldn't JPATH_BASE be an absolute path (eg. realpath('..'))?
Also, you can try setting  in template.

A: I don't recommend circumventing the Joomla rendering process like this. You would be much better off creating a component rather than trying to do whatever you're goals are here.
Essentially I think the issue is you're actually creating a new instance and too many things expect resources to be located in certain paths. You're asking for a lot of trouble here, I can't even being to think of all the settings that would be affected by this move. That is why I would not do this, and make a component.


text: Q: Replying to tweets using the twitteR package in R I'm trying to build a twitter bot with this general functionality: people tweet at my account, I do some natural language processing, and reply to their tweet with some results. What I'm not able to find in the twitteR package is a function that retrieves tweets that have been made directly at your account. Does this exist, or am I supposed to use a combination of the other functions in the package? Haven't been able to do it using the other functions.


text:
Q: store the data of the csv file into a 2d array suppose I have the following csv file called mycsv.csv
   "Date"      "order 1"   "order 2"   "order 3"          "total cost"
   01/04/2006   4 tires      1 oil       6 sparks plugs    "434.00$'
   03/08/2006   3 tires      2 oil       2 sparks plugs    "234.00$'
   03/12/2006   2 tires      0 oil       1 sparks plugs    "134.00$'

I want to know how to store the those  data in a 2d array, any help will be greatly appreciated!

A: You might use fgetcsv(see: http://php.net/manual/en/function.fgetcsv.php). The difference to str_getcsv is that it takes a File resource as parameter and not a String.
You might also store each row in another Array to have a 2D Array e.g. (adjusted manual page example)
$twoDarray = array();
if (($handle = fopen("mycsv.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $twoDarray[] = $data;
    }
    fclose($handle);
}

A: Use the str_getcsv function: http://php.net/str_getcsv
$result = array();

$keys = array('Date', 'order 1', 'order 2', 'order 3', 'total cost');

foreach (file('mycsv.csv') as $key => $str)
{
    if ($key == 0)
        continue;   // skip first line

    $values = str_getcsv($str, "\t", '', '');

    $result[] = array_combine($keys, $values);
}

print_r($result);

A: Normally, I use str_getcsv() PHP native function to parse CSV data.

A: Another quick way to do this:
$data = array_map(function($line) {
    return str_getcsv($line, ',');
}, file('data.csv', FILE_IGNORE_NEW_LINES));

A: The easiest way to archive this is using the fgetcsv-function.
Example (taken from the manual page and slightly altered):
if (($handle = fopen("mycsv.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
}

A: As mentioned on comment from PHP documentation
$csv = array_map('str_getcsv', file('data.csv'));


text:
Q: Strict Properties Without Option Strict On When Option Strict is turned Off, which is the default for my application, VB will automatically convert the value when property is String. It appears to call the toString() of the incoming value's Object. I believe casting will work for any property that can be safely casted (eg integer to double). I want the properties to behave in a strict manner, in that the Type passed MUST match the type on the declared property.
Is there a way to make Objects Properties Strict at the Object level without having to resort to the Option Strict On configuration on?
For example:
Option Strict Off
Class TestObj
    Private _foo As String
    Public Property Foo as String
        Get
            Return _foo
        End Get
        Set(v As String)
            console.write(String.format("v = <{0}> {1}", v.GetType().FullName, v))
            _foo = v
        End Set
    End Property
End Class

Dim o as new TestObj()
o.Foo = "some_str"
o.Foo = 1234
o.Foo = DateTime.now()

In the above case, all values are converted to Strings at arrival to the setter:
v = <System.String> some_str
v = <System.String> 1234
v = <System.String> 7/7/2022 8:22:49 PM

I am aware of DynamicObject and ability to tightly control setters like Python's __setattr__ but this breaks autocomplete functionality in editors as it would preclude defining properties on the class to get the functionality.

A: I strongly agree with the commenters that Option Explicit On and Option Strict On are simply a must - as the default settings of Visual Studio for new VB projects as well as for each project within the solution(s) you took over.
I my opinion one has to invest first some effort into clean-up work when taking over legacy solutions including

*

*Add an ".editorconfig" if there isn't any

*Convert the projects to SDK projects where possible

*Go through the code and

*

*format the code to your liking using the current naming convention where possible

*correct/complement/remove/translate-to-English the documentation comments

*add some //TODO:  - comments where refactoring is needed wherever you notice a code repetition, repeated property access, huge methods that needs to be split into smaller parts, if-not-condition-then-else that needs to be reverted etc. but don't code it yet - these refactorings could introduce some bugs, we need to finish the next step first.

*put every top-level type in its own file (except overloaded generic types of the same name) and make sure the type name matches the file name

*Go through the unit tests and fix them, remove unnecessary ones and complement the missing ones.

*Change all projects to Option Explicit On, Option Strict On and Option Compare Binary (use explicit StringComparer.OrdinalIgnoreCase / StringComparer.InvariantCultureIgnoreCase where needed). (Option Infer On or Off, what you prefer). If you hate to have 1000s of errors, add an Option Strict Off on top of each VB file which you later removed again file by file, otherwise do a bulk mutation.

*Fix all compile errors (per file or bulk mutation)

*Run unit tests, fix code of failing tests (repeat this after each of the following steps)

*Update the .NET framework version if possible (e.g. to current or .NET 4.8)

*Update the NuGet packages

*Do all the previously tagged refactorings

*Enable the analyzer warnings

*Fix all the warnings and infos or suppress them, individually or in the project file by adding the according entry to the <NoWarn> element.

*Start implementing the changes why you originally cloned the repository...
Of course that comes with a price but not doing it also has its price - I'm certain you are going to find dozens of little mistakes in the original code during the process of going Strict. And the time one spends formatting the code files is not just wasted time neither as in the process one also learns to understand the code...


text:
Q: Show more than 10 calls in Codeception stack trace I'm debugging some recursive code via Codeception and it's only showing the last 10 calls, so I don't know what the path through the code is. Xdebug is set to show as much information as possible so, I don't think it's that.
I haven't yet found any configuration option to increase the number of stack trace levels show in Codeception's output.
How can I increase the number of calls in Codeception's output?
Truncated error message:
There was 1 error:

---------
1) Hl7MessageHeaderSegmentWriterTest: Should build a message header segment
 Test  tests\unit\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7MessageHeaderSegmentWriterTest.php:testShouldBuildAMessageHeaderSegment

  [PHPUnit_Framework_Exception] Object of class DateTimeImmutable could not be converted to string

#1  Codeception\Subscriber\ErrorHandler->errorHandler
#2  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:283
#3  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:251
#4  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7SimpleElementWriter.php:49
#5  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:54
#6  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:29
#7  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:54
#8  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:29
#9  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:54
#10 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7HeaderSegmentWriter.php:18

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

Normal error message (note the last line is the entry point from codecept.phar):
There was 1 error:

---------
1) Hl7MessageHeaderSegmentWriterTest: Should build a message header segment
 Test  tests\unit\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7MessageHeaderSegmentWriterTest.php:testShouldBuildAMessageHeaderSegment

  [Exception] foo

#1  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Data\Hl7DateTimeWrapperDataWriter.php:45
#2  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Data\Hl7TimeStampDataWriter.php:54
#3  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:30
#4  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:24
#5  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:20
#6  C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:13
#7  C:\server\Apache24\htdocs\dev.hmr-app\tests\unit\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7MessageHeaderSegmentWriterTest.php:53
#8  HMRX\CoreBundle\Utils\Hl7Writer\Hl7MessageHeaderSegmentWriterTest->testShouldBuildAMessageHeaderSegment
#9  C:\usr\bin\codecept.phar:7

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

Xdebug config from phpinfo():
xdebug

xdebug support => enabled
Version => 2.5.5

Supported protocols => Revision
DBGp - Common DeBuGger Protocol => $Revision: 1.145 $

Directive => Local Value => Master Value
xdebug.auto_trace => Off => Off
xdebug.cli_color => 0 => 0
xdebug.collect_assignments => Off => Off
xdebug.collect_includes => On => On
xdebug.collect_params => 0 => 0
xdebug.collect_return => Off => Off
xdebug.collect_vars => Off => Off
xdebug.coverage_enable => On => On
xdebug.default_enable => On => On
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.extended_info => On => On
xdebug.file_link_format => no value => no value
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.halt_level => 0 => 0
xdebug.idekey => no value => no value
xdebug.max_nesting_level => 256 => 256
xdebug.max_stack_frames => -1 => -1
xdebug.overload_var_dump => 2 => 2
xdebug.profiler_aggregate => Off => Off
xdebug.profiler_append => Off => Off
xdebug.profiler_enable => Off => Off
xdebug.profiler_enable_trigger => Off => Off
xdebug.profiler_enable_trigger_value => no value => no value
xdebug.profiler_output_dir => \ => \
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.remote_addr_header => no value => no value
xdebug.remote_autostart => Off => Off
xdebug.remote_connect_back => Off => Off
xdebug.remote_cookie_expire_time => 3600 => 3600
xdebug.remote_enable => On => On
xdebug.remote_handler => dbgp => dbgp
xdebug.remote_host => localhost => localhost
xdebug.remote_log => no value => no value
xdebug.remote_mode => req => req
xdebug.remote_port => 9000 => 9000
xdebug.scream => Off => Off
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.show_mem_delta => Off => Off
xdebug.trace_enable_trigger => Off => Off
xdebug.trace_enable_trigger_value => no value => no value
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.trace_output_dir => \ => \
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.var_display_max_children => -1 => -1
xdebug.var_display_max_data => -1 => -1
xdebug.var_display_max_depth => -1 => -1

A: Run codeception with -vvv flag to get a full stacktrace.

A: The number $limit = 10 is hard-coded in \Codeception\Subscriber\Console::printExceptionTrace
you could temporarily edit that number to be slightly higher.
The $this->rawStackTrace is the codeception flag which is set from the -vvv Symfony Console parameter, and which bypasses the limited rendering loop and just dumps the raw stack trace.
Both of them also skip the filtered classes defined in \PHPUnit\Util\Filter::$filteredClassesPattern so you could add more classes to that array to remove the application stuff (if that's what you mean by the phar calls, I'm not using a phar, I'm using it via composer which is simpler to edit).


text:
Q: how to represent product_id and product attribute data in redis I have data with multiple Products, Product_id: 1  and Product_attributes: Vitamin_A -> 200, Vitamin_D -> 400 Product_id: 2  and Product_attributes: Vitamin_A -> 200, Vitamin_D -> 400 ....
What is the best way to store this in Redis store ? I was thinking about HMSET but I don't know whether it will be possible to access each individual attribute (Vitamin_A for example) through that ?

A: A hash in Redis is a perfect use case for this. You can grab the individual field inside the hash doing HGET product_id:1 Vitamin_A or get all of the attributes using HGETALL product_id:1. Take a look at the hash commands for more info.


text:
Q: Switch account in web app when using Google Sign-in I've implemented Google Sign-In in my web app and the users should have the option to switch accounts.
Switching accounts would be done basically by logging out, then logging in, but after having the option to select one of the accounts.
However, it seems that whenever the user wants to log in back, they are not prompted which account to select and instead, they are logged in with the one used initially.
So, how can it be done?

A: You can call signIn with options to control this.
signIn({ prompt: 'select_account' }) is what you want.

select_account
The authorization server prompts the user to select a Google account. This allows a user who has multiple accounts to select amongst the multiple accounts that they may have current sessions for.

See https://developers.google.com/identity/sign-in/web/reference#googleauthsigninoptions.


text:
Q: Accessing public methods of a Private Inner Class, from outside the Enclosing class I have the following code class Agent.java :
 public class Agent {
      Helper helper ;

      private class SpecificBehaviour extends Behaviour{
         private Apple a;
         public SpecificBehaviour(Apple a){
          setApple(a);
          }
          public void setApple(Apple a){
           this.a=a;
          }
          public Apple getApple(){
          return a;
          }
         }

         public void someMethod(){
         helper = new Helper(this);
        }

}

In the Helper.java ( another class  within the same package) I would like to access the getApple() method. did some search and found this  link
 I am wondering if there is a better/ easier way of doing this ?

A: There are at least two issues here:

*

*Helper doesn't know of the existence of SpecificBehaviour, because it's a private class. It could potentially know about the Behaviour class, which you haven't given any details of. If getApple() is declared in Behaviour, and if Behaviour is visible to Helper, then the visibility part needn't be a problem.

*Helper will need a reference to an instance of SpecificBehaviour, which means you'll need to instantiate SpecificBehaviour. For that, you'll also need an instance of Agent, because SpecificBehaviour is an inner class. It's not clear whether you have such an instance.

Basically I think the presence of a private inner class is adding confusion here. If you're reasonably new to Java, I'd strongly recommend sticking to top-level classes for the moment. They have a few subtleties around them, and it's best to try to learn one thing at a time.
If this doesn't help, please give more context - your question is quite vague at the moment. Where do you want to use getApple within Helper? Should part of the state of Helper be a reference to an instance of SpecificBehaviour, or should it be a method parameter? Have you created an instance of Agent? What does Behaviour look like? You may find that in the course of answering these questions one at a time, you're better able to figure out the problem for yourself.

A: - Use Composition principle to get the access to the getApple() method.
Eg:
public class Agent {

      Apple a = new Apple();     // Agent class has a reference of type Apple.

     .....
     .....
 }

- Second way would be to make the getApple() method static in Apple class, and then access it from Agent class using the Class name with . (dot) operator.
Eg:
  public class Agent {

          public void go(){

            Apple.getApple();

        }

         .....
         .....
     }

A: You need to ask the Agent object you are passing to the Helper for the instance of the private class SpecificBehaviour. This is the way it works. Encapsulation remember.

A: Jon Skeet stated that and I completely agree on it:

Helper will need a reference to an instance of SpecificBehaviour,
  which means you'll need to instantiate SpecificBehaviour. For that,
  you'll also need an instance of Agent, because SpecificBehaviour is an
  inner class. It's not clear whether you have such an instance.

Actually, you can understand how weird your try is by testing the sample code below:
Agent.java
public class Agent
{
    private class SpecificBehaviour
    {
        public String toString()
        {
            return "specific behaviour";
        }
    }
    public Class getInner()
    {
        return SpecificBehaviour.class;
    }
}

Helper.java
public class Helper
{
    public static void main(String[] args)
    {
        try
        {
            Agent agent = new Agent();
            System.out.println(agent.getInner().newInstance().toString());
        }
        catch (InstantiationException e) {  e.printStackTrace();  }
        catch (IllegalAccessException e) {  e.printStackTrace();  }
    }
}

The code above just compiles fine. And let's see what the output is:
java.lang.InstantiationException: Agent$SpecificBehaviour
    at java.lang.Class.newInstance0(Class.java:340)
    at java.lang.Class.newInstance(Class.java:308)
    at Helper.main(Helper.java:5)


text:
Q: Seed Django + Postgres with .sql file I have a .sql file which I'd like to seed my django + postgres app with on build. That way I'll have some data in my app during development.
Here's my docker stuff:
Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip3 install -r requirements.txt
COPY . /code/

docker-compose.yml
version: "3.9"

services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

A: Django supports this usecase with fixtures: https://docs.djangoproject.com/en/3.2/howto/initial-data/
You can serialize your .sql database into a json file and feed that during build with the loaddata command.


text:
Q: Postgres + Play 2.2.1 Java - Driver not found : [ org.postgresql.Driver ] I'm trying to connect the sample 'computer-database-jpa' to postgres , but I cant.
https://github.com/playframework/playframework/tree/master/samples/java/computer-database-jpa
Could you help me?
My steps:

*

*add jar (build path> configure build path > add external jars ... )

*add to build.sbt: "postgresql" % "postgresql" % "9.3-1100.jdbc4"

*add to application.conf:
db.default.driver=org.postgresql.Driver

db.default.url=" jdbc:postgresql://localhost:5432/teste "

db.default.user="postgres"

db.default.password="postgre"

Result:
Browser message: Driver not found : [ org.postgresql.Driver ]
Where is the problem ?

A: PostgreSQL artifacts have moved to a new group ID org.postgresql.
"org.postgresql" % "postgresql" % "9.3-1100-jdbc4"


text:
Q: Upload document to Microsoft Dynamics CRM integrated with Sharepoint I need to be able to upload a document created totally outside Sharepoint and CRM into the CRM document management system on the associated Sharepoint site. By the way it is Microsoft Dynamics CRM online. I have searched high and low, asked Sharepoint experts, called Microsoft Support but cannot find a solution. The document is created dynamically, probably in some sort of batch process, so this needs to be handled programmatically. The application is written in C# and I want, after creating the document, to find the relevant Sharepoint folder within the CRM system, which will be under one of the account entities, and upload it there. The one solution I did come across is this:
Add document sharepoint using web service Microsoft Dynamics CRM
Which seems promising but I can't get it to work. Has anyone ever done anything like this before?


text:
Q: Click on Camera Shutter using UIAutomator I am writing an Espresso test for my app, and am trying to automate clicking the shutter button after opening of a camera in my app.
I am using Espresso and UIAutomator in the Android Emulator. I managed to dump this UI in UIAutomatorViewer.
I can't figure out why I am unable to click on the shutter button using UIAutomator using this code:
public void clickCameraShutterButton() throws UiObjectNotFoundException
{
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiSelector shutterSelector = new UiSelector().resourceId("com.android.camera:id/shutter_button");
    UiObject shutterButton = device.findObject(shutterSelector);
    shutterButton.click();
}

The camera just sits there, and the shutter button is never clicked. This is the stack trace I'm getting in the Android Studio monitor:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

Any advice would be appreciated.

A: You can try this code:
device.findObject(new UiSelector().resourceId("com.android.camera:id/shutter_button")).click();

or
device.findObject(new UiSelector().description("Shutter button")).click();

or
device.executeShellCommand("input keyevent 27");

this mean KEYCODE_CAMERA value is 27
or
device.click(x,y);

A: This worked for me
@Before
public void setUp() {
    // Initialize UiDevice instance
    final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);
}

...

/**
 * @@Test comment here@@
 *
 * @throws Exception
 */
@Test
public void culebraGeneratedTest_CameraShutter() throws Exception {
    mDevice.findObject(By.res("com.android.camera2:id/shutter_button").desc("Shutter").clazz("android.widget.ImageView").text(Pattern.compile("")).pkg("com.android.camera2")).clickAndWait(Until.newWindow(), DEFAULT_TIMEOUT);
}

This test finds the shutter and clicks on it.
If you are interested this test was automatically generated using CulebraTester.

A: Just need to put the UI Automator Viewer "resource-id" value at the place of *
mdevice.findObject(new UiSelector().resourceId("*")).click();


text:
Q: Find "Request time out" when tracert command is running via batch file I have to check multiple ip addresses. So, I make a batch file to get all ip result as shown in below.
@echo off
if exist D:\tracert\computers.txt goto Label1
echo.
echo Cannot find d:\tracert\computers.txt
echo.
Pause
goto :eof

:Label1
for /f %%i in (d:\tracert\computers.txt) do call :trace %%i
notepad D:\tracert\%1.txt
goto :eof

:trace
echo Tracing %1
tracert -h 200 %1 >> D:\tracert\testing.csv

In computers.txt file, I write all ip line by line.
The above code has no problem and I can get the result correctly. But, the problem is, I can't try to find Request time out. when I run tracert command.
I want to find Request time out. and if found, I want to stop current tracert command and write result into a file and loop for next ip again. If not found, just only write result into a file.
The main reason that I want to make like this because I want to reduce the amount of time taken when I run this batch file.
So, I change the code like this but it doesn't work.
:trace
echo Tracing %1
tracert -h 200 %1
if find /c /i "Request time out." GEQ 0 (
    echo %1>>D:\tracert\%1.txt
    goto :Label1
) else ( echo %1>>D:\tracert\%1.txt )
notepad D:\tracert\%1.txt

I'm not sure I can search as shown in above because I'm in newbie in batch.
I'm very appreciate for any suggestion.

A: Here's an idea, only for the fix and subject to the find string being correct:
:trace
echo Tracing %1
tracert -h 200 %1 | find /i "Request time out" && (
    >>D:\tracert\%1.txt echo %1) || (>>D:\tracert\%1.txt echo %1
    goto :Label1)
start D:\tracert\%1.txt

You really should learn to use double quotes to protect string/variable content, but that is outside of the scope of your question so has been left untouched.

A: You need to ensure that you have the spelling correct, else you will not find the string. Notice the d in timed
@echo off
:trace
echo Tracing %1
tracert -h 200 %1 | find /i "Request timed out" >>%1.txt

Secondly, the IP will always return a valid IP or something starting with Request. So this will also work.
@echo off
:trace
echo Tracing %1
tracert -h 200 %1 | find /i "Request" >>%1.txt

It will therefore echo to hostname01.txt the content will be:

2     *        *        *     Request timed out.
3     *        *        *     Request timed out.


text:
Q: When is subscribe method of Angular Http module called I have a component class and service class. I have the logic of flipping a flag when http 200 status code is received. Based on the response received, I flip the flag using an if condition.
Requests(data:Array<String>):Observable<any>{
    return this.http.post(this.Url,data)
      .map(
        (res:Response) => {
          if(res.status === 200 || res.status===201) {
            return res.json()
          }
        }
      )
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  }

The component file goes like this.
methodName(selectedData){

    this.service.Requests(Id).subscribe((Response => {
      this.rResponse = Response;

    }));
    if(rResponse){
    // My logic to flip the flag
        }
      }
    }
    }

So based on the response received from service, I will flip the flag.
But when I run my code in debugger tools, the logic to flip the flag is never called even if there is a value in rResponse variable. Infact, when methodName function is called, the code flow tries to check for the value of rResponse under if loop first and then calls the subscribe method at the end.
If you could please suggest the flow in which subscribe method works. Why is the if condition called before the actual subscribe method is called.
This is not a duplicate because I want to understand why the flow does not go to my if loop. There is nothing undefined. I am getting values from the service

A: What I understand is you want to do some logic upon receiving value in rResponse.
As you might know that subscribe method call is asynchronous in nature i.e once request it made execution resumes to next lines.
So, as you have written if condition outside subscribe method, if condition gets executed immediately before completion of service call. Which results in empty response.
So, you need to place the if condition in the same block where you are assigning the this.rResponse = Response;
methodName (selectedData) {
    this.service.Requests(Id).subscribe((Response => {
        this.rResponse = Response;
        if(this.rResponse) {
            // My logic to flip the flag
        }
    }));
}


text:
Q: Selenium RemoteWebDriver c# - System.InvalidOperationException I have a sample UI test project using v3.4.0 of Selenium.WebDriver.
Everything works fine when I run the tests against a local driver but I want to get things working using Selenium Grid 2.
As soon as I try to instantiate a new RemoteWebDriver I get an exception with little detail.
Driver = new RemoteWebDriver(new Uri(GridUrl), Capabilities);

Note: GridUrl is "http://localhost:4444/wd/hub"
Throws a System.InvalidOperationException with StackTrace as follows:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(Uri remoteAddress, ICapabilities desiredCapabilities)
   at xxxx.Ui.Tests.SeleniumTests.TestInitialize() in C:\Users\xxxx\Documents\Visual Studio 2015\Projects\xxxx.Ui.Tests\xxxx.Tests\PersonTests.cs:line 38

Hub configuration
I have v3.4.0 of the hub running locally with the following configuration:
{
  "port": 4444,
  "newSessionWaitTimeout": -1,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {},
  "capabilityMatcher":"org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
  "throwOnCapabilityNotPresent": true,
  "cleanUpCycle": 5000,
  "role": "hub",
  "debug": false,
  "browserTimeout": 0,
  "timeout": 1800
}

Hub started with:

java -jar selenium-server-standalone-3.4.0.jar -role hub

This has come up OK and looks to be running.

Node configuration
I have tried a number of nodes (chromedriver.exe, IEDriverServer.exe and geckodrvier.exe). None of these work with the RemoteWebDriver. All of them are in a directory that has been added to my system PATH variable.
Chrome config
{
  "capabilities":
  [
    {
      "browserName": "chrome",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver"
    }
  ],
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5556,
  "register": true,
  "registerCycle": 5000,
  "hub": "http://localhost:4444",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {}
}

Node started with:

java -jar selenium-server-standalone-3.4.0.jar -role node -nodeConfig chromeNodeConfig.json

The other node configs are largely the same except for the different browser names and ports.
Once all nodes are started, the console looks as follows:

I'm not able to get much from the exception. Is it a versioning issue of the drivers I have? I have tried customising my DesiredCapabilities to ensure I'm matching those in the node config. All of that looks fine.

Update
As requested I'm adding a bit more detail as to how I'm trying to launch a browser. None of the browsers work with the RemoteWebDriver whereas they do with the local drivers. Showing the Chrome example - only difference between each is regarding the Capabilities that I'm passing in to the base class constructor.
In my test class
[TestClass]
public class PersonTests : PersonTestBase
{
    public PersonTests()
        : base(DesiredCapabilities.Chrome())
    {
    }

    [TestCategory("Chrome")]
    [TestMethod]
    public void Chrome_ShouldCreatePlacement()
    {
        this.ShouldCreatePerson();
    }
}

In my base class I am doing the following
public abstract class PersonTestBase
{
    protected IWebDriver Driver;
    protected ICapabilities Capabilities;
    protected string TargetUrl;
    protected string GridUrl;

    protected PersonTests(ICapabilities capabilities)
    {
        this.Capabilities = capabilities;
    }

    [TestInitialize]
    public void TestInitialize()
    {
        TargetUrl = "http://urlOfMyWebsite";
        GridUrl = "http://localhost:4444/wd/hub"

        Driver = new RemoteWebDriver(new Uri(GridUrl), Capabilities);
    }

    [TestCleanup]
    public void TestCleanup()
    {
        Driver.Quit();
    }

    protected void ShouldCreatePerson()
    {
        Driver.Navigate().GoToUrl(TargetUrl);

        //rest of test code ommitted
    }
}

A: V3.5.1 Fixes this issue.
Upgrade your Selenium NuGET package using NuGET manager & your selenium-standalone jar.

A: Downgrade to 3.3.0 until this issue gets resolved and a new release of Selenium Standalone Server is available (Recommended solution)
Or

*

*Download the Solution

*Comment this line

*Build dotnet language bindings

*

*Open command window in root directory

*Run go //dotnet:release

*And reference the binaries built in {root}/build/dotnet/dist

Note: This workaround does NOT fix anything! It ignores the piece of selenium grid code that causes failure.
Another note: Be aware that upgrading to Selenium 3.4 may require upgrading webdrivers as well

A: Downgrading to 3.3.0 as it was suggested by Stephen may cause known issue. Try downgrading to v3.3.1 instead.
You can get the v3.3.1 from here:
http://selenium-release.storage.googleapis.com/index.html?path=3.3/