text:
Q: Private enum access fails to compile from a nested class's friend function I am currently porting a project that has so far only been built using Clang, to also work with GCC. The project contains code similar to below and compiles fine with Clang, however GCC gives an error message.
class Outer
{
  enum
  {
      ONE, TWO, THREE, COUNT
  };
public:
  class Inner
  {
    friend class Outer;
    friend void somefunc()
    {
      int x = Outer::COUNT;
    }
  };
};

The error is:
<source>: In function 'void somefunc()':

<source>:15:32: error: 'Outer::<unnamed enum> Outer::COUNT' is private within this context

   15 |                 int x = Outer::COUNT;

      |                                ^~~~~

<source>:6:26: note: declared private here

    6 |         ONE, TWO, THREE, COUNT

      |                          ^~~~~

Note the friend keyword in the somefunc signature. Removing this makes the code compile fine with GCC, I'm wondering which compiler is correct? I am under the impression that friend functions have the same access as member functions which would make this a GCC bug.
Godbolt link: https://godbolt.org/z/OAR0gc

A: This is the age-old question of whether the body of a friend function declared-in-line, being lexically part of the class in which it's declared, has access to all names that the class has access to. The last time this was discussed by CWG, in 2021, there was no consensus as to which interpretation of the standard is correct. This is issue 1699.
Interestingly, some compilers have changed their opinion since this question was posted. As of October 2022, Clang and GCC will compile the code when the friend function is defined inline, while MSVC will not [Godbolt]; all 3 compilers reject the code when the friend function is defined out-of-line [Godbolt].

A: friend class Outer;

1. Is not needed, nested class has access to private members of embracing class.
friend void somefunc()

2. According to https://en.cppreference.com/w/cpp/language/friend point 2, function that member of "Inner" and friend can't get privilege from point 1. Remove friend keyword.


text:
Q: Problem with binomial coefficients? I am trying to find the sum of $$\sum_{x=0}^{n-2}\left (\frac{1}{x+1}{2x \choose x} \cdot \frac{1}{n-x-1}{2n-2x-4 \choose n-x-2}\right)\;.$$ I am told the answer is $$\frac{1}{n}{2n-2 \choose n-1}$$ Could someone show me how this is derived? I applied the binomial coefficients but am not getting anything near the answer.
Attempt: $$\frac{1}{x+1}{2x \choose x} = \frac{(2x!)}{(x!)(x!)(x+1)}$$
$$\frac{1}{n-x-1}{2n-2x-4 \choose n-x-2} = \frac{(2n-2x-4)!}{(n-x-2)!(n-2-x)!(n-x-1)}$$ I then tried to sum the product but it seems too complicated to be reduced. Please help.

A: This is the recurrence formular for the Catalan numbers.
Let $C_x=\frac{1}{x+1}\binom{2x}{x}$ be the x-th Catalan number.
Then what we want to show is $C_n=\sum_{x=0}^{n-2}C_{x}C_{n-x-2}$, and this has been treated in, for example see this wiki article.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I provide fallbacks for HTML5/CSS3 elements in a web page at this point? I'm wondering if I should bother providing a fallback for HTML5 tags and attributes and CSS3 styling at this point in time.
I know that there's probably still a lot of people out there who use older versions of browsers and HTML5/CSS3 are still fairly new.
I read this article: Should I use non-standard tags in a HTML page for highlighting words? and one answer mentioned that people kind of "cheat" with older browsers by using the new tags and attributes, but styling them in CSS to ensure they show up right. This question: Relevance of HTML5: Is now the time? was asked about two years ago and I don't know how relevant it is anymore.
For example, I want to use the placeholder and required attributes in a web form I'm building and it has no labels to show what each <input> is. How do I handle this, or do I bother?

A: It really is up to who is your target audience? Is it fair to expect decent level of techiness (read: probably uses the latest browsers), so it would be a non-issue to use whatever technology the last couple versions of the major browsers support. If you can expect a sizable portion of the visitors using outdated browsers, you might want to consider using fallbacks.
In almost all cases, that means creating a separate CSS for mostly Internet Explorer, heh. For the issues not related to formatting, there's the possibility of using a separate container page for a HTML 4.01-based version. But of course keep the content separate, so you don't have to maintain two versions of the same data!
A simplified example, using PHP:

...
<?php
    $browser = new SupportChecker();
    if($browser->supports('html5') == true) {
        echo '
';
        include('content.txt');
        echo '
';
    } else {
        echo '
'
        include('content.txt');
        echo '
'
    }
?>
...

Of course for an actual page, a more sensible way to achieve that would be used. The above is just a description of the idea. The same will apply for the header of the page. You could start the page with the inclusion of a header based on the support:
<?php
    $browser = new SupportChecker();
    if($browser->supports('html5') == true) {
        include('html5_header.txt');
        $_SESSION['support'] = 'html5';
    } else {
        include('regular_header.txt');
        $_SESSION['support'] = 'regular';
    }
?>

That could be usable, I would presume. Then just compare to the session variable.


text:
Q: How to pass dictionary items to a function in C# I am writing a custom helper to handle nested navigation menu. I am having some trouble with passing a set of arrays (or dictionary) to the function.
Below is the Razor call to the ActionMenuItem
@Html.ActionMenuItem("All Reports", "index", "report", "icon-bar-chart", "last", new {"title" = "Report 1", "action" = "report1"}, new {"title" = "Report 2", "action" = "report2"})
public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName, String iconType = null, string classCustom = null, params Dictionary<string, string> subMenu)

My function works well, up until the dictionary items.
I am able to generate a single level menu, but trying to get it to work with nested menus.
Any help, and lessons is much appreciated!
Thank you,
RD

A: Could you do something like this:
public static MvcHtmlString ActionMenuItem(
    this HtmlHelper htmlHelper,
    String linkText,
    String actionName,
    String controllerName,
    String iconType = null,
    string classCustom = null,
    params KeyValuePair<string, string>[] subMenus)
{ ... }

var dict = new Dictionary<string, string>()
{
    { "a", "b" },
    { "c", "d" },
};

*.ActionMenuItem(*, *, *, *, *, dict.ToArray());

A: You can't declare Dictionary<TKey, TValue> as parameter array using params keyword.
According to c# specification:

A parameter declared with a params modifier is a parameter array. If a
  formal parameter list includes a parameter array, it must be the last
  parameter in the list and it must be of a single-dimensional array
  type.

Dictionary is not a single-dimensional array.
You could create a class with two properties: Title and Action and change parameter type to MyClass[] instead of a dictionary.

A: Try something like this:
    @Html.ActionMenuItem(
        "All Reports",
        "index",
        "report",
        "icon-bar-chart",
        "last",
        new Dictionary<string, string>[]
        {
            new Dictionary<string, string>()
            {
                { "title", "Report 1" },
                { "action", "report1" }
            },
            new Dictionary<string, string>()
            {
                { "title",  "Report 2" },
                { "action", "report2" }
            }
        } )

    public static MvcHtmlString ActionMenuItem(
        this HtmlHelper htmlHelper,
        string linkText,
        string actionName,
        string controllerName,
        string iconType = null,
        string classCustom = null,
        params Dictionary<string, string>[] subMenu)


text:
Q: Multiple Threads in Xpages I have a problem and hoped somone could help me
I'm trying to start multiple threads from an XAgent (not rendered XPage)
public class ImportThread extends NotesThread {

Session currentSession;

public ImportThread(String maildb, String Server)
{

try{
   currentSession =DominoAccess.getCurrentSession();
   this.maildb = currentSession.getDatabase(Server, maildb);
}catch (Exception e) {
e.printStackTrace();
}

}

public void runNotes()
{
   View v = maildb.getView("$Calendar");
}

in this version I could not access the View I only get "null" back
Ive tryed a version with Java Threads not realy better.
thean i've found something on Openntf
http://www.openntf.org/internal/home.nsf/project.xsp?action=openDocument&name=Threads%20and%20Jobs
but there I got an "AccessControl Exception"
I have no more ideas, I hope that someone has an idea how to create
an XAgent with multiple thread

A: Afaik NotesObjects should not be shared between threads. So instead of using Database mailDB you should use String mailDBName and instantiate all NotesObjects inside their own thread. You also need to watch run time: if your XAgent waits for the treads to conclude, you should be fine, but if it is a 'fire-and-forget' approach you need to start it from something more persistent like a managed bean in the session scope.
Hope that helps

A: As Egor wrote you need the change the Java policy file if you run the Java code from an NSF. You don't have to do this if you deploy your Java code as OSGi plugin. See the documentation of that OpenNTF project.


text:
Q: Will a graphics card work on my motherboard? I would like to know if my motherboard can support a graphics/video card, I have an HP Mulberry motherboard but I don't know if the pci slot on this motherboard is compatible with a graphics card, let alone which kind of card I would need for the pci slot on this motherboard.

A: https://support.hp.com/us-en/document/c03955263
It has

Integrated AMD HD 8330 Graphics

and doesn't support additional graphics cards.


text:
Q: Can't get SymPy to numerically evaluate results of solving a system of equations ***** EDIT *****
Adding a simplified example to show the problem more clearly. Original post below the edit.
I'm trying to get the big mass of ugly code  in the original post to produce a simple numerical result.  In this reduced example, I have three equations, EqA, EqB, and EqC.  EqA and EqB both take numeric inputs.  EqC then takes the output from EqA and adds it to the output from EqB.  After doing a solve() and an evalf(), I expected to receive a value of 11 as the result, but it just gives me an expression.  How would I properly evaluate a system of equations like this?
from sympy import *
from sympy.printing.mathml import print_mathml
init_printing()

Fa,Fb,a,b,c,d,T = symbols('F_a F_b a b c d T')
EqA = Eq(a+b,Fa)
print(EqA)
EqB = Eq(c+d,Fb)
print(EqB)
EqC = Eq(Fa + Fb,T)
print(EqC)
results = (solve([EqA,EqB,EqC],T))
print(results)
print('printing results')
print(results[T].evalf(subs={a:1,b:3,c:3,d:4}))

This produces the following output:
-F_a + a + b
-F_b + c + d
F_a + F_b - T
{T: F_a + F_b}
printing results
F_a + F_b

The expected output for the evalf() statement is 11.
***** /EDIT *****
Can't seem to get this code to produce any numerical output.  I'm trying to build up a more complex equation by breaking it into smaller pieces, to make troubleshooting easier.  The desired output is to solve for T.  However, when I run the solver and then try to evalf() on the output, it just pumps the same expression back out at me.  The behavior is identical to when I fail to define all necessary numerical inputs, but I think I have all the relevant ones defined in the evalf() call. Any ideas as to what I'm doing wrong?
from sympy import *
init_printing()

periodOfInterest  = symbols('P') #constant
modDensity = symbols('D_m') # result of calculation
floorDensity = symbols('D_f') # result of calculation
distanceTraveledPerPickMod = symbols('x_m')  # result of calculation
distanceTraveledPerPickFloor  = symbols('x_f') # result of calculation
travelTimePerPickMod = symbols('t_modTravel') # result of calculation
travelTimePerPickFloor = symbols('t_floorTravel') # result of calculation
timePerPickMod = symbols('t_totalMod') # result of calculation
timePerPickFloor = symbols('t_totalFloor') # result of calculation
T = symbols('Total_picks') # result of calculation
unitsMod = symbols('U_m') #constant
zonesMod = symbols('Z_m') #constant
pathLengthMod = symbols('L_m') #constant
travelRate = symbols('R_p') #constant
pickTime = symbols('k_p') #constant
unitsFloor = symbols('U_f') #constant
zonesFloor = symbols('Z_f') #constant
pathLengthFloor = symbols('L_f') #constant
floorPickers = symbols('N_floor') #constant
modPickers = symbols('N_mod') #constant

modDensityEq = Eq(unitsMod/zonesMod , modDensity)
floorDensityEq = Eq(unitsFloor/zonesFloor , floorDensity)
distanceTraveledPerPickModEq = Eq(pathLengthMod/modDensity , distanceTraveledPerPickMod)
distanceTraveledPerPickFloorEq = Eq(pathLengthFloor/floorDensity , distanceTraveledPerPickFloor)
travelTimePerPickModEq = Eq(distanceTraveledPerPickMod/travelRate , travelTimePerPickMod)
travelTimePerPickFloorEq = Eq(distanceTraveledPerPickFloor/travelRate , travelTimePerPickFloor)
timePerPickModEq = Eq(travelTimePerPickMod+pickTime , timePerPickMod)
timePerPickFloorEq = Eq(travelTimePerPickFloor + pickTime , timePerPickFloor)
totalPicksEq = Eq(floorPickers*periodOfInterest/timePerPickFloor + modPickers*periodOfInterest/timePerPickMod, T)
results = (solve([totalPicksEq,timePerPickFloorEq,timePerPickModEq,travelTimePerPickFloorEq,
       travelTimePerPickModEq,distanceTraveledPerPickModEq,distanceTraveledPerPickFloorEq,
       floorDensityEq,modDensityEq],T))
(results)

results[T]

(results[T]).evalf(subs={
        periodOfInterest:60*60,
        unitsMod:5000*2/3,
        zonesMod:4,
        pathLengthMod:3000,
        travelRate:1.34,
        pickTime:10,
        unitsFloor:5000/3,
        zonesFloor:2,
        pathLengthFloor:3000,
        floorPickers:15,
        modPickers:35
    })

This produces the following output:
 N_floor*P/t_totalFloor + N_mod*P/t_totalMod

A: What you want is for SymPy to update all the pertinent variables and give you the result: you want the equations you have defined and the values for a - d to be simultaneously true. The way to do this is give the values as additional simultaneous equations which must be true:
>>> solve((EqA,EqB,EqC,Eq(a,1),Eq(b,3),Eq(c,3),Eq(d,4)))
{c: 3, F_a: 4, a: 1, d: 4, F_b: 7, b: 3, T: 11}

And this shows your T=11 value that you were seeking.

A: How about:
results[T].subs({floorPickers: 15, modPickers: 35, periodOfInterest: 60*60, timePerPickMod: 1.0, timePerPickFloor: 1.0})


text:
Q: BACKPACK CRUD fields from another table I got this tricky scenario, I have 2 tables:

*

*family table
[ id, bloc, ap ]

*user table
[ id, family_id, name ]

Note : A family has one or more users.

The result should be like this:
When creating the user I need to have 2 fields from the families table in order to hide the families table from the cms user. The family should only be edited from the users profile.
Is there a way to bind this 2 tables into a single form ?
The store method I have written it manually but on the edit form those two fields from families table don't autocomplete.


text:
Q: Property 'setCurrentUser' does not exist on type 'Object'.ts(2339) with useContext I was trying to pass useState properties through Context.Provider value={{theme, setTheme}} as it was written in tutorial, and after receive it with useContext(Context), but it keeps returning me an error:
const setCurrentUser: any
Property 'setCurrentUser' does not exist on type 'Object'.ts(2339)

Note: This code is fully copied from react docs with little type additions to see if it's me how's making such mistake, or I just don't know how to fix it
I checked usage useContext with TypeScript, but code there is the same as mine and doesn't provide me an answer
Full code:
import { createContext, useContext, useState, ReactNode, DetailedHTMLProps, ButtonHTMLAttributes, MouseEventHandler } from 'react';

const CurrentUserContext = createContext<Object>({});

export default function MyApp() {
      const [currentUser, setCurrentUser] = useState(null);
      return (
            <CurrentUserContext.Provider
                  value={{
                        currentUser,
                        setCurrentUser
                  }}
            >
                  <Form />
            </CurrentUserContext.Provider>
      );
}

function Form(): JSX.Element {
      return (
            <Panel title="Welcome">
                  <LoginButton />
            </Panel>
      );
}

function LoginButton(): JSX.Element {
      const {
         //\/\/\/\/\/\/\/\/
         // Error occurs here

            currentUser,
            setCurrentUser

         ///\/\/\/\/\/\/\/\
      } = useContext(CurrentUserContext);

      if (currentUser !== null) {
            return
You logged in as {currentUser.name}.
;
      }

      return (
            <Button onClick={() => {
                  setCurrentUser({ name: 'Advika' })
            }}>Log in as Advika</Button>
      );
}

interface PanelProps {
      title: string
      children: ReactNode
}

function Panel({ title, children }: PanelProps): JSX.Element {
      return (

{title}

                  {children}

      )
}

interface ButtonProps extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
      children: ReactNode
      onClick?: MouseEventHandler<HTMLButtonElement>
}

function Button({ children, onClick }: ButtonProps): JSX.Element {
      return (
            <button className="button" onClick={onClick}>
                  {children}
            </button>
      );
}

If this wording of the question is not correct, please let me know

A: at this line
const CurrentUserContext = createContext<Object>({});

adding initContextValue
const initContextValue = {
  currentUser: {name: 'abc'},
  setCurrentUser: ({name: 'abc'}) => {}
}
const CurrentUserContext = createContext<Object>(initContextValue);

y will see the TS can work

A: The type of CurrentUserContext is set to Object (L#3), where it's supposed to be explicit object structures (or any)
Take a look at the TS docs on object types
createContext<{
    currentUser: string,
    setCurrentUser: fn(_:any) => void
}>

Should be the approximate type you're looking for. I have no way to tell for sure.
But this gets messy, so consider instantiating as suggested by H294. Or using a type alias


text:
Q: I don't understand the error traceback gives me I'm currently trying to understand Pyth. I know Python quite well, but I don't get Pyth sometimes.
My code:
DhNKlNFzrKZaY@Nz;Y;hQ

It's just a basic script for reversing string, and traceback gives me ValueError,
ValueError: malformed node or string: <_ast.Name object at 0x7ff2fde45c18>

Despite my Python knowledge I have no idea what does this error mean. Can you show me where is this error coming from?

A: I assume you are getting an error like this one here:
Traceback (most recent call last):
  File "pyth.py", line 771, in <module>
  File "<string>", line 3, in <module>
  File "/app/macros.py", line 691, in eval_input
  File "/app/.heroku/python/lib/python3.4/ast.py", line 84, in literal_eval
  File "/app/.heroku/python/lib/python3.4/ast.py", line 83, in _convert
ValueError: malformed node or string: <_ast.Name object at 0x7fac26eb2b70>

First off, you use z and Q inconsistently. With your current code, input should have been taken like this instead:
"abcd"
abcd

When Q is used in a Pyth program, z implicitly jumps to the next line of input, it just skips whatever has been inputted before using Q. Instead, just use:
DhNKlNFzrKZaY@Nz;Y;hz

And the errors should go away.
I am not sure why you would want to perform string reversal that way, though. I use _z if the input is not quoted and _ alone otherwise, since Q is implicit at the end of any Pyth program.


text:
Q: AzureRmResourceGroupDeployment cmdlet works with _Templateparameterfile but not with -Templateparameteruri When I deploy with ARM template with both template and parameter file in local folder, it works with no issues. But, same file if in blob container, it prompts me for all parameters. Quite strange and confused. :(
This structure works!

Parameter Set: Deployment via template file and template parameters file

New-AzureRmResourceGroupDeployment -ResourceGroupName  -TemplateFile >> -TemplateParameterFile  [-Force] [-Mode  >>{Incremental | Complete} ] [-Name  ] [-StorageAccountName  ] [->>TemplateVersion  ] [ ]

My above trial is as below and it works:
$TemplateFile =        "F:\servicerequestsnippets\FW__Code\Orig\Orig\trial\azuredeploy.json"
$TemplateParameterFile = "F:\servicerequestsnippets\FW__Code\Orig\Orig\trial\azuredeploy.parameters.json"

.
.
.
                   Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
                                                        -TemplateFile $TemplateFile `
                                                        -TemplateParameterFile $TemplateParameterFile `
                                                        -Verbose

But, Parameter file uri approach as below do not work. :(
$TemplateFile =   "F:\servicerequestsnippets\FW__Code\Orig\Orig\trial\azuredeploy.json"
$TemplateParametersFile = "https://hbala.blob.core.windows.net/test-container/"

.
.
{
foreach ($blob in $blobs)
                {

                   $TemplateParameterFileLink = $TemplateParametersFile + $blob.Name
                   write-host $TemplateParameterFileLink
                   Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
                                                        -TemplateFile $TemplateFile `
                                                        -TemplateParameterFile $TemplateParameterFileLink `
                                                        -Verbose

                }
        }

Note:
a. I even tried TemplateParameterUri but got same Debugmessage as:
cmdlet Test-AzureRmResourceGroupDeployment at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
**administratorLogin:** << *

it is not saying of conflict , and paramfromTemplate.

*

*It would great to get some pointers or what you feel I am missing. Thanks in advance.
Regards,
H Bala


text:
Q: Bulletproof approach to tackle SQL transaction timeouts Recently we faced quite an interesting issue that has to do with SQL transactions timeout. The statement that timed out does not really matter for the sake of question, but it was single INSERT statement w/o explicit transaction with client generated GUID as a key:
INSERT MyTable
(id, ...)
VALUES (<client-app-generated-guid>, ...)

We also have a retry policies in-place, so that if command fails with SqlException, then it will be retried. SQL Server (Azure SQL) did not behave normally one day and we faced a lot of strange PK violation errors during retries. They were caused by retrying actually successfully committed on the SQL Server transaction (so that causes insert with already taken ID). I understand that SQL timeout it's purely client side concept, so if Client thinks that SqlCommand failed - it might or might not mean it.
I suspect that Client explicit transaction control via for instance wrapping statements with TransactionScope as shown bellow will fix 99% of such troubles -- because Commit is actually quite fast&cheap operation. However, I still see the caveat there -- the timeout also can happen on Committing stage. The application again can be in conditions where it's impossible to guess whether transaction really committed or not (to figure out necessity of retry).
The question is how to write code in bulletproof (to such kind of troubles) and generic fashion and do a retry only when it's positively clear that transaction was not committed.
using (var trx = new TransactionScope())
using (var con = GetOpenConnection(connectionString))
{
    con.Execute("<some-non-idempotent-query>");

    // what if Complete() times out?!
    // to retry or not to retry?!
    trx.Complete();
}

A: The problem is that the Exception does not mean that the transaction failed. For any compensating action (like retrying) you need to have a definite way of telling if it failed. There are scalability issues with what I will suggest, but its the technique that is the important thing, the scalability issues can be solved in other ways.
My solution;

*

*the last INSERT before COMMIT is to write a Guid to a tracking table.

*if an exception occurs, that indicates a network failure, SELECT @@TRANCOUNT. If it indicates you are still in a transaction (is greater than 0)(which probably should never happen, but its worth checking) then you can happily resubmit your COMMIT

*If @@TRANCOUNT returns 0 then you are no longer in a transaction. Selecting your Guid from the tracking table will tell you whether your COMMIT was successful.

*If your commit was not successful (@@TRANCOUNT ==0 and your Guid is not present in the tracking table) then resubmit your entire batch from the BEGIN TRANSACTION onwards.

A: The general approach is: try to read back what you just tried to insert.
If you can read back the ID that you tried to insert, then previous transaction committed successfully, no need to retry.
If you can't find the ID that you tried to insert, then you know that your attempt to insert has failed, so you should retry.

I'm afraid there is no way to have a completely generic pattern that would work for any SQL statement. Your "checking" code needs to know what to look for.
If it is INSERT with ID - then you are looking for that ID.
If it is some UPDATE, then the check would be custom and depend on the nature of that UPDATE.
If it is DELETE, then the check consists of trying to read what was meant to be deleted.

Actually, here is a generic pattern: any data modification batch that has one or multiple INSERT, UPDATE, DELETE statements should have one more INSERT statement within that transaction that inserts some GUID (some ID of the data modifying transaction itself) into a dedicated audit table. Then your checking code tries to read that same GUID from that dedicated audit table. If GUID is found, then you know that previous transaction committed successfully. If GUID is not found, then you know that previous transaction was rolled back and you can retry.
Having this dedicated audit table unifies/standardize the checks. The checks no longer depend on internals and details of your data changing code. Your data modification code and verification code depend on the same agreed interface - audit table.


text:
Q: Searching RLIKE mysql regex for two or no character How can I search in a mysql database for a pattern like this :
*foo??

Matching:
foo
bla foo
bla foob
bla bla foobc

Not matching:
foo bla foobcc
fooabcd

This is how I tried :
SELECT *
  FROM table
  WHERE name RLIKE "\\b.*foo.?.?"

A: You can use the SQL LIKE option:
SELECT * FROM table WHERE name LIKE "%foo__";

or
SELECT * FROM table WHERE name LIKE "%foo%";

% <- SQL Wildcard ( * ) ( no char / single char / many chars)
_ <- SQL Wildcard ( . ) ( single Char)

Edit:
For your special type:
select * from news WHERE text REGEXP '^(b.*)?(foo.{0,2})$';

The test case


text:
Q: ¿Como serializar los datos de una tabla HTML y enviarlos mediante Ajax? Buenas tardes colegas, tengo una duda de como podría serializar el contenido de una tabla HTML y posteriormente enviarlo mediante ajax al controlador de mi aplicación en MVC5

A: Se me ocurre que podrias recorrer los Tr de tu Table obteniendo cada Td y construyes un objeto con ellos.
var objeto = [];
$("#mitabla tr").each(function() {
    var tds = $("td", $(this));
    objeto.push({
       column1: tds[0].text(),
       column2: tds[1].text()
    });
});

Es un ejemplo muy simple pero es para darte un idea de como podrias hacerlo, intentalo y si necesitas ayuda pega el código que ya tengas y vemos que se puede hacer.

A: var json="";
$(document).ready(function () {
 $(".guardar").on("click",function () {
  $(".trjson").each(function () {
   json ="";
   $(this).find("th").each(function () {
    $this=$(this);
      json+=',"'+$this.attr("class")+'":"'+$this.html()+'"'
   });
   obj=JSON.parse('{'+json.substr(1)+'}');


text:
Q: How do i create dynamic product variant options on React I am creating a ecommerce project to learn react, and i guess thats the best way to learn a language by doing a complex project so that you get to know every aspect of it. but now i am stuck with something that i searched for everywhere but couldnt find.
Basically i want to create a section where the person can add product variants like color and sizes to it, like the example below
it doesnt have to be complicated but if i could add into an object depending on the values the user inputs is what all i need.
if someone could help me that would be great!
Thank you!!!

A: I think I have done similar project.
Flow was as follows:
const [words, setWords] = useState([]);

...

function handleWord(e) {
    if (e.key === "Enter") {
      let temp = words ? words : [];
      temp.push(value);
      setWords(temp);
      setValue("");
    }
  }

...

<input
          type="text"
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={handleWord}
          value={value}
          placeholder="Enter one keyword..."
/>

You can modify this depending on how you are constructing object.
Is that what you want?

A: Adding Variants of products in a catalogue

*

*Variants of a product are the products having different attributes.

Implementation

*

*To implement this feature you need 3 things

*

*you need to know all the unique hinges with their priority (Set of all unique possible attributes of a product in catalogue) e.g. here in you case hinges are

[{id:110, hingeName : "Color", priority: 1 }, {id:220, hingeName: "Size", priority:2}]

*You need to know the attribute of the current product which is on screen

productData = {
    id:12132,
    prodcutImg:'https://abc.img.in',
    productPrice:'$24',
    prodAttribute:[{id:110, value:'Black'},{id:220, value:"XL"}],
    variantMeta:
     {
        hinges:[
                  {id:110, hingeName : "Color", priority: 1 },
                  {id:220, hingeName: "Size", priority:2}
              ],
        hingesValues: [
                       {110: ["Black","Red","White"]},
                       {220: ['XS','S','L','XL','XXL']}
                      ],
        variantsOfCurrentProducts: [
                                     {variant_id:'12131', attributes: { 110:'Black',220:'S'}},
                                     {variant_id:'12132', attributes: { 110:'Red',220:'XL'}},
                                     {variant_id:'12133', attributes: { 110:'White',220:'XS'}},
                                     {variant_id:'12134', attributes: { 110:'Red',220:'XL'}}
                                    ]
      }
}]

*

*Now you need to render all the hinges as title and hinge values as values of those hinges.

*Let's suppose you want to render the variants in ascending order of priority

*So now your UI for the given example will look similar to the following:

Color :
        Red Black White
Size :
        XS S L XL XXL

*

*Now you should show current products attributes as selected in hinges as

Color :
        Red "Black" White
Size :
        XS S L "XL" XXL

NOTE: I have used "double_quote" for showing the attribute of current product. You can render it with different background and colour on UI.

*

*Now make sure that hinge at the top most priority should always be enabled so that user can be able to select that at any point of time

*If someone click on the hinge having 2nd highest priority then filter all those variants which have attribute with highest priority and the 2nd highest priority and render them as selectable values and all those variants which don't have these attributes disable them.


text:
Q: nd array to string and string to nd array I have the following problem:
I want to convert my nd_array to a string variable but I also want to restore the structure. For example my nd_array looks like
nd_array = [[array_best, float_best]] array_best is a numpy array with 2 entries and float_best is a float variable.

[[array([2.54974085, 5.45954157]), -0.741455078125], [array([2.55141016, 5.40955301]), -0.73046875], [array([2.55466028, 5.40582758]), -0.69287109375]]

I tried to split the nd_array into smaller arrays and then to string but I sort the nd_array so in case of multiple arrays I have to store the mapping. Any ideas how to fix it?

A: Depending on the problem statement, my solution would be:
import numpy as np

array_of_arrays = [[np.array([2.54974085, 5.45954157]), -0.741455078125], [np.array([2.55141016, 5.40955301]), -0.73046875], [np.array([2.55466028, 5.40582758]), -0.69287109375]]
my_string = ""
for an_array in array_of_arrays:
    for element in an_array:
        if isinstance(element, float):
            my_string = my_string + str(element) + ","
        else:
            for a_float in element:
                my_string = my_string + str(a_float) + ","

my_string = my_string[:-1]

If this not what you requested, please provide further information


text:
Q: Obtener objeto del arraylist.Java tengo este método para obtener el mayor.
public static void met(ArrayList lista) {
        int aux = 0;
        int a;
        for(int i = 0; i<lista.size();i++) {
            a = (int) lista.get(i);
            if(a>aux) {
                aux = a;//obtener el maximo de una lista
            }
        }
        System.out.print(aux);
    }

Y quiero hacer lo mismo pero ahora con objetos:
Pero no sé como hacerlo

A: Del mismo modo que tienes una variable int para almacenar el máximo y luego ir comparando, puedes declarar un objeto para almacenar la referencia al objeto que cumplió la condición.
public static void metodoVoraz(ArrayList<Objeto> becas) {
    ArrayList<Objeto> nuevaLista = new ArrayList<Objeto>();
    int aux = 0;
    Objeto obj;

    for(int i = 0; i < becas.size(); i++) {
        Objeto tmp = (Objeto) becas.get(i);
        int a = obj.getDiferencia();

        if(a > aux) {
            aux = a;
            obj = tmp;
        }
    }

    // Aquí, el objeto obj es el máximo
}

Por cierto, ahora se hace el get(i) de la lista por parámetro, no del objeto que declarabas sin instanciar.
Posible solución alternativa
Puedes ordenar la lista por ese valor de mayor a menor y devolver el primer objeto de la lista.
public static Objeto getMax(ArrayList<Objeto> list) {

    if (list.size() == 0) return null;

    Collections.sort(list, new ObjetoComparator());
    return list.get(0);
}

La clase ObjetoComparator implementa la interfaz Comparator<T> de tipo Objeto y sirve para comparar dos objetos de tipo Objeto, en nuestro caso.
class ObjetoComparator implements Comparator<Objeto> {
    public int compare(Objeto a, Objeto b)
    {
        return b.getDiferencia() - a.getDiferencia();
    }
}

Compara según el valor de retorno del método #getDiferencia y, en este caso, ordena de mayor a menor.

También se podría hacer que Object implementara la interfaz Comparable<T>, siempre y cuando querramos siempre ordenar del mismo modo. A la hora de llamar Collections.sort(list) no necesitaríamos pasar ningún otro argumento, ya que internamente se llamará al método #compareTo de la clase Objeto que implementa de la interfaz Comparable<T>.

Más información aquí.
Edit
El mismo ejemplo del sorting se puede implementar con lambdas, como apunta @MrDave1999.
Aquí va el ejemplo
public static Objeto getMax(ArrayList<Objeto> list) {

    if (list.size() == 0) return null;

    Collections.sort(list, Comparator.comparing(Objeto::getDiferencia)
                                     .reversed());
    return list.get(0);
}

Crea un Comparator anónimo que apunta al método #getDiferencia de la clase Objeto. Como por defecto, los Comparator numéricos son ascendentes, se llama al método #reversed para invertir el orden del sorting.
Usar lambdas es una buena manera de tener un código más modular y limpio.
Hay que tener en cuenta, por otra parte, que las lambdas sirven procisamente para crear funciones y clases anónimas, por lo que no son reutilizables.


text:
Q: Accessing elements inside map How would I access elements from the following map:
map<int, string[4]> * my_map;

I used to do it through the at() operator
string * val_ptr = my_map->at(key);

Recently, I have discovered that this is a non standard feature of my compiler and the correct way of doing it is through operator[]. Unfortunately, the compiler keeps trying to convert my key to string [4]:
string * val_ptr = my_map->operator[](key);

error: conversion from 'int' to non-scalar type 'std::string [4]' requested

I have looked online, but there don't seem to be any examples with a map of string arrays. Am I doing something invalid? Should I be using a vector instead, and if so, would it be slower to create and access?

A: Use of .at() function is not non-Standard anymore. It is in the Standard C+11 (see doc).
Now, this,
string * val_ptr = my_map->operator[](key);

which is correct, but it should be written as:
string * val_ptr = (*my_map)[key];

as it is more succinct.
As for the compiler error, it is somewhere else.

In fact, I believe, the problem is coming from somewhere, and caused by pointer declaration of the map. Why don't you declare the map as:
map<int, string[4]> my_map; //no pointer

and then use
string * val_ptr = my_map[key];

Even better if you use std::vector:
std::map<int, std::vector<std::string> > my_map; //no pointer

and then use
std::vector<std::string> & val = my_map[key];

A: You could use  std::map<int, std::array<std::string,4> > (or have your own class fourstring_t containing the four strings)  and use std::map<int,fourstring_t> and you can also use
 string second = (my_map->at(key))[1];

to retrieve the second string (of rank 1) in your array of strings.
And the at method is standard, as Nawaz reminded it.
As UncleBens reminded, you need the fourstring_t type to be assignable.


text:
Q: Custom tab in file properties dialog I want to show some additional info in file properties dialog in Windows for some specified types. For example, add new tab "Summary" for *.txt files and show there number of words, number of lines, etc.
I can use C++ and C#. But file summary is collected by .NET library, so I'd prefer to delegate this task to .NET to the extent possible.

A: Michale Dunn has written a series of articles on shell extensions, Part V dealing with custom property pages.


text:
Q: attempting to assign weaker access privileges; was public I keep getting the following errors:
\AppDatabase_Impl.java:66: error: onCreate(SupportSQLiteDatabase) in <anonymous com.mgr.data.AppDatabase_Impl$1> cannot override onCreate(SupportSQLiteDatabase) in Delegate
      protected void onCreate(SupportSQLiteDatabase _db) {
                     ^
  attempting to assign weaker access privileges; was public

AND,
error: onValidateSchema(SupportSQLiteDatabase) in <anonymous com.mgr.data.AppDatabase_Impl$1> cannot override onValidateSchema(SupportSQLiteDatabase) in Delegate
      protected RoomOpenHelper.ValidationResult onValidateSchema(SupportSQLiteDatabase _db) {
                                                ^
  attempting to assign weaker access privileges; was public

I have no idea why this is happening all of the suddenly. I can share my build.gradle (app):
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
    id 'org.jetbrains.kotlin.plugin.serialization'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId ""
        minSdk 24
        targetSdk 32
        versionCode 1
        versionName "0.8.3"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += [
                        "room.schemaLocation":"$projectDir/schemas".toString(),
                        "room.incremental":"true",
                        "room.expandProjection":"true"
                ]
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        freeCompilerArgs += [
                "-opt-in=kotlin.RequiresOptIn"]
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
        viewBinding true
    }
    composeOptions {
        kotlinCompilerExtensionVersion "1.2.0"
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
            excludes += 'META-INF/gradle/incremental.annotation.processors'
        }
    }
    kapt {
        useBuildCache = true
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation "com.github.ireward:compose-html:1.0.2"
    implementation 'com.google.dagger:hilt-android:2.43.2'
    implementation "androidx.hilt:hilt-navigation-compose:1.0.0"
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation "androidx.compose.material:material:$compose_version"
    implementation 'org.chromium.net:cronet-embedded:76.3809.111'
    implementation 'com.google.dagger:hilt-compiler:2.43.2'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.43.2'

    implementation "androidx.datastore:datastore-preferences:$datastore"
    implementation "androidx.datastore:datastore-preferences-core:$datastore"

    implementation "androidx.datastore:datastore:1.0.0"
    implementation "org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.5"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2"

    // Coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines"

    // Work
    implementation "androidx.work:work-runtime-ktx:$work"
    implementation "androidx.work:work-gcm:$work" // optional - GCMNetworkManager support
    androidTestImplementation "androidx.work:work-testing:$work" // optional - Test helpers
    implementation "androidx.work:work-multiprocess:$work" // optional - Multiprocessor support

    // Navigation
    implementation "androidx.navigation:navigation-fragment-ktx:$navigation"
    implementation "androidx.navigation:navigation-ui-ktx:$navigation"

    implementation "androidx.navigation:navigation-dynamic-features-fragment:$navigation"

    // Testing Navigation
    androidTestImplementation "androidx.navigation:navigation-testing:$navigation"

    // Jetpack Compose Integration
    implementation "androidx.navigation:navigation-compose:$navigation"

    // status bar customization
    implementation "com.google.accompanist:accompanist-systemuicontroller:0.23.1"

    // Accompanist
    implementation "com.google.accompanist:accompanist-pager:$accompanist" // Pager
    implementation "com.google.accompanist:accompanist-pager-indicators:$accompanist" // Pager Indicators
    implementation "com.google.accompanist:accompanist-flowlayout:$accompanist"
    implementation "com.google.accompanist:accompanist-navigation-animation:$accompanist"
    implementation "com.google.accompanist:accompanist-swiperefresh:$accompanist"

    implementation "androidx.recyclerview:recyclerview:$rcview"
    // For control over item selection of both touch and mouse driven selection
    implementation "androidx.recyclerview:recyclerview-selection:$rcview_select"

    // Card view
    implementation "androidx.cardview:cardview:1.0.0"

    // Extensions = ViewModel + LiveData
    implementation "android.arch.lifecycle:extensions:1.1.1"
    kapt "android.arch.lifecycle:compiler:1.1.1"

    //Room
    implementation "androidx.room:room-runtime:$room"
    kapt "androidx.room:room-compiler:$room"
    implementation "androidx.room:room-ktx:$room"

    implementation "android.arch.persistence.room:runtime:1.1.1"
    kapt "android.arch.persistence.room:compiler:1.1.1"

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room")

    // optional - RxJava2 support for Room
    implementation("androidx.room:room-rxjava2:$room")

    // optional - RxJava3 support for Room
    implementation("androidx.room:room-rxjava3:$room")

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation("androidx.room:room-guava:$room")

    // optional - Test helpers
    testImplementation("androidx.room:room-testing:$room")

    //implementation "androidx.paging:paging-runtime:3.1.1"
    implementation 'androidx.paging:paging-compose:1.0.0-alpha15'

    // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:2.5.0-alpha02"

    // Google Sign In Integration
    implementation "com.google.android.gms:play-services-auth:20.2.0"

    implementation 'androidx.core:core-ktx:1.8.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.animation:animation-graphics:$compose_version"
    implementation "androidx.compose.material3:material3:$material3"
    implementation "androidx.compose.material3:material3-window-size-class:$material3"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle"
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle"
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle"
    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle"

    // optional - helpers for implementing LifecycleOwner in a Service
    implementation "androidx.lifecycle:lifecycle-service:$lifecycle"

    // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle"

    // optional - ReactiveStreams support for LiveData
    implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle"

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:2.1.0"

    // optional - Test helpers for Lifecycle runtime
    testImplementation "androidx.lifecycle:lifecycle-runtime-testing:$lifecycle"

    implementation "androidx.fragment:fragment-ktx:1.5.1"
    implementation "androidx.activity:activity-ktx:1.5.1"

    // https://github.com/Bryanx/themed-toggle-button-group
    implementation "nl.bryanderidder:themed-toggle-button-group:1.4.1"

    implementation 'androidx.activity:activity-compose:1.5.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"

    implementation "io.github.vanpra.compose-material-dialogs:datetime:0.7.2"
}

I sadly have no idea of what is causing this. Is this a potential permission issue? Do I need to edit the app manifest file? I am really stuck here. I am trying to use the Room database with my application and I am using Kotlin with Jetpack Compose. I read multiple threads so far, but non-helped me.

A: I just had this same issue while updating dependencies / adding compose.  Seems to be an issue with this dependency :
implementation "androidx.room:room-paging:2.5.0-alpha02"
Try changing to the latest stable version :
implementation "androidx.room:room-paging:2.4.3"
I have found that for Compose + Room + Hilt 1.6.10 is as high as I can go with the Kotlin version in my project currently.
So in the project level build.gradle:
buildscript { ext.kotlin_version = "1.6.10" }
and
dependencies { classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10 }'
Also add inside the "android" block in the app build.gradle (this is compatible with Kotlin 1.6.10):
 composeOptions { kotlinCompilerExtensionVersion '1.1.0' }


text:
Q: How to get azure webapp ip adress to whitelist in storage account I have a azure storage account with firewall setting enabled to allow only specific IP address.
now i have azure web app and web job and from these i am connecting to the storage account to create delete blobs using connection string.but since storage account needs IP address of the web app to access it am not able to do so .
i have tried using inbound and outbound IP address from web app properties those are not working?


text: Q: Google Charts GeoChart Markers Not Working I have been trying to follow along with the Google Charts documentation for GeoCharts. For some reason, whenever I try to run their code for markers on my local host it only returns a blank map of Italy. I have created my own Google Maps JS API key and am using that instead of the one provided but it still returns nothing. I'm very lost as I have not been able to find anything that can guide me to the right direction. Any help would be appreciated.


text:
Q: Nothing Launches From Main Method When I launch my program below from the 3 class files, nothing at all happens. It just displays an empty console. Am I missing some sort of implementation or something? It consists of the 3 class files and I have no error messages from the compiler. The program simply has to display each quiz question, the player answers and then gets their final score at the end. Thanks!
public class Question
{
   private String question, answer;

   //-----------------------------------------------------------------
   //  Constructor: Sets up the question with a default complexity.
   //-----------------------------------------------------------------
   public Question (String query, String result)
   {
      question = query;
      answer = result;

   }

   //-----------------------------------------------------------------
   //  Returns the question.
   //-----------------------------------------------------------------
   public String getQuestion()
   {
      return question;
   }

   //-----------------------------------------------------------------
   //  Returns the answer to this question.
   //-----------------------------------------------------------------
   public String getAnswer()
   {
      return answer;
   }

   //-----------------------------------------------------------------
   //  Returns true if the candidate answer matches the answer.
   //-----------------------------------------------------------------
   public boolean answerCorrect (String candidateAnswer)
   {
      return answer.equals(candidateAnswer);
   }

   //-----------------------------------------------------------------
   //  Returns this question (and its answer) as a string.
   //-----------------------------------------------------------------
   public String toString()
   {
      return question + "\n" + answer;
   }
}

import java.util.Scanner;
public class Quiz

{
private int score;
private Question[] questionHolder = new Question[25];
private int numQuestions;

public Quiz()
{
this.score = 0;
this.numQuestions = 0;

}

public void addQuestion (Question Q)
{
this.questionHolder[numQuestions++] = Q;
}

public int giveQuiz()

{

Scanner scan = new Scanner (System.in);

String candidateAnswer;

scan.nextInt();
scan.nextLine();

for (int i = 0; i < numQuestions; i++)
{

candidateAnswer = scan.nextLine();
if (questionHolder.answerCorrect(candidateAnswer))
score++;
}
return getscore();
}
public int getscore()
{
return score;
}
public String toString()
{
return getscore() + "\n";
}

}

public class QuizTime

{
public static void main (String[] args)

{
//--------------------------------------------------------------------------
//Initializes the variables.
//--------------------------------------------------------------------------
Question Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q17, Q18, Q19,
Q20, Q21, Q22, Q23, Q24, Q25;

Quiz T1;

//--------------------------------------------------------------------------
//Creates the question and answer and also sets its complexity value.
//--------------------------------------------------------------------------
Q1 = new Question ("What is the capital of Virginia?", "Richmond");

Q2 = new Question ("Is an apple a Fruit or a vegetable?", "Fruit");

Q3 = new Question ("What continent is China in?", "Asia");

Q4 = new Question ("Is Germany in Europe or South America?", "Europe");

Q5 = new Question ("What color is a black bear?", "Black");

Q6 = new Question ("What is the capital of Arizona?", "Phoenix");

Q7 = new Question ("What do cows produce??", "Milk");

Q8 = new Question ("What ocean is closest to New York City?", "Atlantic");

Q9 = new Question ("What ocean surrounds Japan?", "Pacific");

Q10 = new Question ("What is the largest state in America?", "Alaska");

Q11 = new Question ("What is the smallest state?", "Deleware");

Q12 = new Question ("What is the most populated state?", "California");

Q13 = new Question ("What is instrument did Jascha Heifetz play?", "Violin");

Q14 = new Question ("Was Mozart a composer or a computer?", "Composer");

Q15 = new Question ("What is the largest country by area?", "Russia");

Q16 = new Question ("What is the most populated country?", "China");

Q17 = new Question ("What country did Pizza originate in?", "Italy");

Q18 = new Question ("What is the last name of the first American President?", "Washington");

Q19 = new Question ("What country borders America to the south?", "Mexico");

Q20 = new Question ("What island is 700 miles off the coast of NYC?", "Bermuda");

Q21 = new Question ("What city contains the Eiffel Tower?", "Paris");

Q22 = new Question ("Who wrote Romeo and Juliet?", "Shakespeare");

Q23 = new Question ("What swims in the ocean?", "Fish");

Q24 = new Question ("What is man's best friend?", "Dog");

Q25 = new Question ("What is another name for coffee and the language of this program?", "Java");

//--------------------------------------------------------------
//Adds the questions into quiz.
//--------------------------------------------------------------
T1= new Quiz();
T1.addQuestion(Q1);
T1.addQuestion(Q2);
T1.addQuestion(Q3);
T1.addQuestion(Q4);
T1.addQuestion(Q5);
T1.addQuestion(Q6);
T1.addQuestion(Q7);
T1.addQuestion(Q8);
T1.addQuestion(Q9);
T1.addQuestion(Q10);
T1.addQuestion(Q11);
T1.addQuestion(Q12);
T1.addQuestion(Q13);
T1.addQuestion(Q14);
T1.addQuestion(Q15);
T1.addQuestion(Q16);
T1.addQuestion(Q17);
T1.addQuestion(Q18);
T1.addQuestion(Q19);
T1.addQuestion(Q20);
T1.addQuestion(Q21);
T1.addQuestion(Q22);
T1.addQuestion(Q23);
T1.addQuestion(Q24);
T1.addQuestion(Q25);

//--------------------------------------------------------------
//Prints out the quizes.
//--------------------------------------------------------------
System.out.print(T1.giveQuiz());

}
}

A: There is an error in this line
if (questionHolder.answerCorrect(candidateAnswer)) // questionHolder is an array

Since questionHolder is an array, you need to provide the index in the loop.
if (questionHolder[i].answerCorrect(candidateAnswer)) // like this, [i] - index

Also, the program starts, but waits for an input from the user. There is no SOP to indicate the user to input a value, thus making you think that it does nothing.
// Waiting for the user to input an integer value, but there is no SOP to intimate the
// user about it, thus making it seem like doing nothing.
scan.nextInt();
scan.nextLine();

To ask the question to the user, print it in the for loop.
for (int i = 0; i < numQuestions; i++) {
    System.out.println(questionHolder[i].getQuestion()); // Question is displayed to the user now. Answer accordingly.
    candidateAnswer = scan.nextLine();
    if (questionHolder[i].answerCorrect(candidateAnswer))
        score++;
}

Keeping this in mind, I feel that these 2 lines before the for loop in giveQuiz() are unnecessary.
// scan.nextInt();
// scan.nextLine();

A: It gives you an empty console because when you call the following line
System.out.print(T1.giveQuiz());

it first executes giveQuizz() witch awaits input from Scanner.
scan.nextInt();
scan.nextLine();

This means you first have to type an int, then something ending with newline and then the answers.
And I hope it's just a copy-paste error but the correct version way to access questionHolder is
questionHolder[i].answerCorrect(candidateAnswer)

not
questionHolder.answerCorrect(candidateAnswer)

A: The first thing Quiz.giveQuiz() does is waiting for your input. So it won't output anything until you type something into your terminal and hit return.
May be you want to add something like
 System.out.println("Please type a string and and integer and hit return");

This way the user (you ;-) ) knows what to do.

A: The above code does not compile because of the following statement:
    if (questionHolder.answerCorrect(candidateAnswer))
it should be
    if (questionHolder[i].answerCorrect(candidateAnswer))
and execution begins at
 System.out.print(T1.giveQuiz());

when the execution begins you have to enter value
You are not getting any display because you are neither prompting anywhere to accept the answer nor might be entering that many number of values after which loop terminates and you get the score.


text:
Q: Using Frames or changing visibility I'm new to UWP (windows 10), working on an app for windows phone, I wanted to know what is the difference between:

*

*Using multiple frames and navigate from one to other.

*Using a single xaml with no frames but with multiple grids (or other patterns), and instead of navigate-  just change visibility so only the desired grid will be visible.

which option is better? and why?

A: The system keeps track of the Page you are currently on. So even when your App exists and even if it's removed from memory the OS can tell the App to reopen on that page.
Similarily when your App provides other Apps with the capability of calling into it to open certain file types of to perform certain actions (e.g. start navigation, etc.) pages will be used.
Lastly if you put everything on a single page and just manipulate visibility this will increase memory consumption of your App (as everything needs to be loaded even if it's not visible) and it also might increase load times.
Of course how much that impacts you is up to the type of App you are building. In general however I'd advice you to start building using separate pages in case your App grows. Also you get a lot of stuff out of the box if you do so (e.g. animated transitions, etc.)


text:
Q: How to read xls file return by Content-Disposition: attachment with PHP When I access a link, eg: https://demo.com/report?transType=xls it will return a xls to I download. It's response header:
HTTP/1.1 200 OK
Date: Thu, 16 Mar 2017 19:18:37 GMT
Server: IIS/4.0 (Windows XP)
Content-Disposition: attachment; filename*="utf-8''demo.xls
Vary: Accept-Encoding,User-Agent
Content-Length: 14848
Keep-Alive: timeout=10, max=1000
Connection: Keep-Alive

Content-Type: text/html
How can I download this file to my server use PHP (CURL, Socket...)? I tried CURL but it don't work. The saved file cannot read :( It's my code:
$op = curl_init();
curl_setopt ($op, CURLOPT_URL, 'https://demo.com/report?transType=xls');
curl_setopt ($op, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($op, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($op, CURLOPT_TIMEOUT, 60);
curl_setopt ($op, CURLOPT_POST, 1);
curl_setopt ($op, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($op, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($op, CURLOPT_BINARYTRANSFER, 1);

$response = curl_exec($op);
@file_put_contents('saved.xls', $response);

Please help me :(

A: To download a file using curl in php you have to use code which is like so:
<?php
//File to save the contents to
$fp = fopen ('theFile.xls', 'w+');
$url = "https://demo.com/report?transType=xls";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);//get curl response
//done
curl_close($ch);
fclose($fp);
?>


text:
Q: Error when trying to remove or install a package It's me again.
I'm trying to run this command: sudo apt-get remove bitcoind
But I'm getting this response:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 linux-image-generic-hwe-16.04 : Depends: linux-image-4.15.0-46-generic but it is not going to be installed
 linux-modules-extra-4.15.0-33-generic : Depends: linux-image-4.15.0-33-generic but it is not going to be installed or
                                                  linux-image-unsigned-4.15.0-33-generic but it is not going to be installed
 linux-modules-extra-4.15.0-38-generic : Depends: linux-image-4.15.0-38-generic but it is not going to be installed or
                                                  linux-image-unsigned-4.15.0-38-generic but it is not going to be installed
 linux-modules-extra-4.15.0-42-generic : Depends: linux-image-4.15.0-42-generic but it is not going to be installed or
                                                  linux-image-unsigned-4.15.0-42-generic but it is not going to be installed
 linux-modules-extra-4.15.0-45-generic : Depends: linux-image-4.15.0-45-generic but it is not going to be installed or
                                                  linux-image-unsigned-4.15.0-45-generic but it is not going to be installed
 linux-modules-extra-4.15.0-46-generic : Depends: linux-image-4.15.0-46-generic but it is not going to be installed or
                                                  linux-image-unsigned-4.15.0-46-generic but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Then when apt-get -f install:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  libdb4.8++ libllvm5.0 linux-headers-4.13.0-41
  linux-headers-4.13.0-41-generic linux-headers-4.13.0-43
  linux-headers-4.13.0-43-generic linux-headers-4.15.0-24
  linux-headers-4.15.0-24-generic linux-headers-4.15.0-29
  linux-headers-4.15.0-29-generic linux-headers-4.15.0-33
  linux-headers-4.15.0-33-generic linux-headers-4.15.0-38
  linux-headers-4.15.0-38-generic linux-headers-4.15.0-42
  linux-headers-4.15.0-42-generic linux-headers-4.15.0-45
  linux-headers-4.15.0-45-generic linux-image-4.13.0-41-generic
  linux-image-4.13.0-43-generic linux-image-4.15.0-24-generic
  linux-image-4.15.0-29-generic linux-image-4.15.0-33-generic
  linux-image-4.15.0-38-generic linux-image-4.15.0-42-generic
  linux-image-4.15.0-45-generic linux-image-extra-4.13.0-41-generic
  linux-image-extra-4.13.0-43-generic linux-image-extra-4.13.0-45-generic
  linux-modules-4.15.0-24-generic linux-modules-4.15.0-29-generic
  linux-modules-4.15.0-33-generic linux-modules-4.15.0-38-generic
  linux-modules-4.15.0-42-generic linux-modules-4.15.0-45-generic
  linux-modules-extra-4.15.0-24-generic linux-modules-extra-4.15.0-29-generic
  linux-modules-extra-4.15.0-33-generic linux-modules-extra-4.15.0-38-generic
  linux-modules-extra-4.15.0-42-generic linux-modules-extra-4.15.0-45-generic
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  linux-image-4.15.0-33-generic linux-image-4.15.0-38-generic
  linux-image-4.15.0-42-generic linux-image-4.15.0-45-generic
  linux-image-4.15.0-46-generic linux-modules-4.15.0-42-generic
  linux-modules-4.15.0-45-generic linux-modules-4.15.0-46-generic
Suggested packages:
  fdutils linux-hwe-tools
The following NEW packages will be installed:
  linux-image-4.15.0-33-generic linux-image-4.15.0-38-generic
  linux-image-4.15.0-42-generic linux-image-4.15.0-45-generic
  linux-image-4.15.0-46-generic linux-modules-4.15.0-42-generic
  linux-modules-4.15.0-45-generic linux-modules-4.15.0-46-generic
0 upgraded, 8 newly installed, 0 to remove and 281 not upgraded.
75 not fully installed or removed.
Need to get 0 B/78,2 MB of archives.
After this operation, 237 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
(Reading database ... 593097 files and directories currently installed.)
Preparing to unpack .../linux-modules-4.15.0-46-generic_4.15.0-46.49~16.04.1_amd64.deb ...
Unpacking linux-modules-4.15.0-46-generic (4.15.0-46.49~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-modules-4.15.0-46-generic_4.15.0-46.49~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/System.map-4.15.0-46-generic' to '/boot/System.map-4.15.0-46-generic.dpkg-new': failed to write (No space left on device)
No apport report written because the error message indicates a disk full error
                                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-image-4.15.0-46-generic_4.15.0-46.49~16.04.1_amd64.deb ...
Unpacking linux-image-4.15.0-46-generic (4.15.0-46.49~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-4.15.0-46-generic_4.15.0-46.49~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-4.15.0-46-generic' to '/boot/vmlinuz-4.15.0-46-generic.dpkg-new': failed to write (No space left on device)
No apport report written because the error message indicates a disk full error
                                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-image-4.15.0-33-generic_4.15.0-33.36~16.04.1_amd64.deb ...
Unpacking linux-image-4.15.0-33-generic (4.15.0-33.36~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-4.15.0-33-generic_4.15.0-33.36~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-4.15.0-33-generic' to '/boot/vmlinuz-4.15.0-33-generic.dpkg-new': failed to write (No space left on device)
No apport report written because the error message indicates a disk full error
                                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-image-4.15.0-38-generic_4.15.0-38.41~16.04.1_amd64.deb ...
Unpacking linux-image-4.15.0-38-generic (4.15.0-38.41~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-4.15.0-38-generic_4.15.0-38.41~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-4.15.0-38-generic' to '/boot/vmlinuz-4.15.0-38-generic.dpkg-new': failed to write (No space left on device)
No apport report written because MaxReports is reached already
                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-modules-4.15.0-42-generic_4.15.0-42.45~16.04.1_amd64.deb ...
Unpacking linux-modules-4.15.0-42-generic (4.15.0-42.45~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-modules-4.15.0-42-generic_4.15.0-42.45~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/System.map-4.15.0-42-generic' to '/boot/System.map-4.15.0-42-generic.dpkg-new': failed to write (No space left on device)
No apport report written because MaxReports is reached already
                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-image-4.15.0-42-generic_4.15.0-42.45~16.04.1_amd64.deb ...
Unpacking linux-image-4.15.0-42-generic (4.15.0-42.45~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-4.15.0-42-generic_4.15.0-42.45~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-4.15.0-42-generic' to '/boot/vmlinuz-4.15.0-42-generic.dpkg-new': failed to write (No space left on device)
No apport report written because MaxReports is reached already
                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-modules-4.15.0-45-generic_4.15.0-45.48~16.04.1_amd64.deb ...
Unpacking linux-modules-4.15.0-45-generic (4.15.0-45.48~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-modules-4.15.0-45-generic_4.15.0-45.48~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/System.map-4.15.0-45-generic' to '/boot/System.map-4.15.0-45-generic.dpkg-new': failed to write (No space left on device)
No apport report written because MaxReports is reached already
                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Preparing to unpack .../linux-image-4.15.0-45-generic_4.15.0-45.48~16.04.1_amd64.deb ...
Unpacking linux-image-4.15.0-45-generic (4.15.0-45.48~16.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-4.15.0-45-generic_4.15.0-45.48~16.04.1_amd64.deb (--unpack):
 cannot copy extracted data for './boot/vmlinuz-4.15.0-45-generic' to '/boot/vmlinuz-4.15.0-45-generic.dpkg-new': failed to write (No space left on device)
No apport report written because MaxReports is reached already
                                                              dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/linux-modules-4.15.0-46-generic_4.15.0-46.49~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-image-4.15.0-46-generic_4.15.0-46.49~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-image-4.15.0-33-generic_4.15.0-33.36~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-image-4.15.0-38-generic_4.15.0-38.41~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-modules-4.15.0-42-generic_4.15.0-42.45~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-image-4.15.0-42-generic_4.15.0-42.45~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-modules-4.15.0-45-generic_4.15.0-45.48~16.04.1_amd64.deb
 /var/cache/apt/archives/linux-image-4.15.0-45-generic_4.15.0-45.48~16.04.1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Hope you can help me to figure it out as you always do. Thanks again!
root@gear:/# df -h
Filesystem                   Size  Used Avail Use% Mounted on
udev                         3,9G     0  3,9G   0% /dev
tmpfs                        798M   74M  724M  10% /run
/dev/mapper/ubuntu--vg-root 1019G  359G  618G  37% /
tmpfs                        3,9G  337M  3,6G   9% /dev/shm
tmpfs                        5,0M  4,0K  5,0M   1% /run/lock
tmpfs                        3,9G     0  3,9G   0% /sys/fs/cgroup
/dev/loop0                   138M  138M     0 100% /snap/skype/33
/dev/loop1                    87M   87M     0 100% /snap/core/4650
/dev/sda1                    472M  471M     0 100% /boot
tmpfs

              798M  144K  798M   1% /run/user/1000

A: The error message suggests:
<list of packages>...
Use 'sudo apt autoremove' to remove them.

This will remove no-longer needed packages, and free the space they used on /boot, which is 100% full.


text:
Q: Autoincrementing value for object array I am trying to implement a file revisioning for my projects, where a sample entry would look like this:
{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : ISODate("2017-07-02T03:27:45.502Z"),
    "created_at" : ISODate("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "Demo project",
    "uploaded_files" :
     [{
         _id : ObjectId("xy"),
         display_name : 'demofile.txt',
         history: [{
             revision: 0,
             file: ObjectId("xy")
         },
         {
             revision: 1,
             file: ObjectId("xy")
         }]
     }]
}

My problem:
I am not sure how I can implement the auto incrementing for the revision number inside of my history's object array. The revision number should start at 0 for each new document inside of uplodaed_files. What would be a decent way to achieve this behaviour?
My mongoose schema (simplified):
var projectSchema = mongoose.Schema({
    name: {
        type: String,
        trim: true,
        required: [true, 'Project name is required'],
        validate: projectNameValidator,
        index: true
    },
    website: {
        type: String,
        trim: true,
        validate: websiteValidator
    },
    visibility: {
        type: Number,
        required: [true, 'Visiblity must be specified'],
        min: 0,
        max: 1
    },
    source_language: {
        type: String,
        trim: true,
        required: [true, 'Source language must be specified'],
        validate: sourceLanguageValidator
    },
    uploaded_files: [{
        _id: {
            type: Schema.Types.ObjectId
        },
        display_name: {
            type: String,
            trim: true,
            required: [true, 'Display name must be specified'],
        },
        history: [{
            revision: {
                type: Number,
                required: [true, 'Revision number must be specified']
            },
            file: {
                type: Schema.Types.ObjectId,
                ref: 'File'
            }
        }]
    }]
}


text:
Q: Quantization aware training in tensorflow makes my model predict allways the same class I'm using tensorflow_model_optimization..quantization.keras.quantize_model on a VGG16 model pretrained on imagenet, to test transfer learning over cifar10. When trained normally for 5 epochs, accuracy reaches 60%, but when quantized it directly drops to 10% (random guessing), as it always predicts the same class. I also noticed that both evaluation and training are significantly lower with the quantized model.
This is the code:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.datasets import cifar10
from keras.applications.vgg16 import VGG16
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout, GlobalAveragePooling2D
from keras.models import Model
import tensorflow_model_optimization as tfmot

# Load the CIFAR10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# Input image dimensions and classes
input_shape = x_train.shape[1:]
num_classes = 10

# Target one-hot vectorization
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Normalize data
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# Import pre-trained layers and freeze them
base_model = keras.applications.vgg16.VGG16(include_top=False, input_shape=(32,32,3), weights="imagenet")
for layer in base_model.layers:
    layer.trainable = False

# Establish new fully connected block
x = base_model.output
x = Flatten()(x)  # flatten from convolution tensor output
x = Dense(4096, activation='relu')(x) # number of layers and units are hyperparameters, as usual
x = Dense(4096, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(num_classes, activation='softmax')(x) # should match # of classes predicted

# This is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=['accuracy', 'Precision', 'Recall'])

model.fit(x_train, y_train, batch_size=32, epochs = 5, verbose = 1, validation_data = (x_test, y_test))

# Quantize the model
model_quant = tfmot.quantization.keras.quantize_model(model)
model_quant.compile(optimizer="adam", loss="categorical_crossentropy", metrics=['accuracy', 'Precision', 'Recall'])

# Evaluate both models
print(model.evaluate(x_test, y_test))
print(model_quant.evaluate(x_test, y_test))

This is the result:
313/313 [==============================] - 4s 12ms/step - loss: 1.1593 - accuracy: 0.6008 - precision: 0.7149 - recall: 0.4872
[1.1592937707901, 0.6007999777793884, 0.714893639087677, 0.487199991941452]
313/313 [==============================] - 16s 48ms/step - loss: 6.6550 - accuracy: 0.1000 - precision: 0.1000 - recall: 0.1000
[6.654963493347168, 0.10000000149011612, 0.10000000149011612, 0.10000000149011612]

As you see, evaluation is x4 slower and doesn't work at all. When trying to see the predictions with model_quant.predict(x_test), the output is:
[[0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 ...
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]
 [0.00061506 0.00061506 0.00061506 ... 0.00061506 0.00061506 0.00061506]]

Training the quantized model doesn't seem to improve accuracy, and each epoch lasts like 5 minutes when in previosly lasted less than 30 seconds.
I have based my code on the official page, but I fail to find what is going wrong in here.


text:
Q: Cannot connect to video session in vidyo? I cant connect to video session in vidyo getting following errors in the log:

Blockquote
  2018-02-12 08:34:37.297 +00:00: ERROR: LmiTransport: [System thread]: LmiTcpTransport.c:1422: LmiTcpTransportConstructAddressFromString: Error resolving address http://127.0.0.1:8888: Undefined
  2018-02-12 08:34:37.297 +00:00: ERROR: LmiCsWebProxy: [System thread]: LmiCsWebProxyTransport.c:303: LmiCsWebProxyTransportConstruct: ProxyTransportConstruct: TransportAddressConstructFromString failed.
  2018-02-12 08:34:37.298 +00:00: ERROR: VidyoConnector: Execute Async-0: ..\VidyoConnector.c:2925: VidyoConnectorRunOnAsyncLoginFailureCallback_: VidyoConnectorConnectFailed VIDYO_CONNECTORFAILREASON_ConnectionFailed
  onfailure called ConnectorfailreasonConnectionFailed

How can I solve this issue ?

A: I have finally solved the problem. I was running fiddler in the background so it causes WPAD to discover wrong web proxy server.
I solved it by calling SetWebProxyTransport on vidyo io connector and passing it false or by just closing the fiddler that has solved the issue.


text:
Q: Responsive CSS relative to default CSS I am not sure if this is entirely possible. Want to check here.
Basically what I am trying here is to have a default font size (say 40px). when a media query kicks in I want to change it to reduce to 80% of default font size. Is that possible?
.text p span{
      font-size:40px;
}
@media screen and (max-width: 640px){
   .text p span{
      font-size: <0.8*40px>;
   }
}
@media screen and (min-width: 641px) and (max-width: 1024px){
   .text p span{
      font-size: <0.6*40px>;
   }
}

The reason I am not setting px values is because .text p span gets different class names which will have different font sizes. But they need to scale down in the same ratio. Am I trying that's not achievable?

A: You could use em, like this, where you set a default on the body, or on any parent you want to inherit font-size from, and adjust from there
Also rem and % is possible alternatives, it all comes down to markup structure etc.
em is relative to its direct or nearest parent, rem is relative to the html (root) - their font-size.

body {
  font-size: 20px;
}
.text p span {
  font-size: 2em;
}
@media screen and (max-width: 640px) {
  .text p span {
    font-size: 1.6em;
  }
}
@media screen and (min-width: 641px) and (max-width: 1024px) {
  .text p span {
    font-size: 1.2em;
  }
}

      Hey there ...

With rem one can do like this

html {
  font-size: 40px;
}

.sampleClass {
  font-size: 20px;
}

@media screen and (min-width: 641px) and (max-width: 1024px){
  .sampleClass span {
   font-size: 0.8rem;
  }
}
@media screen and (max-width: 640px){
  .sampleClass span{
   font-size: 0.6rem;
  }
}

    This is 20px
    This is relative to the html element when @media kicks in

A: I'm not the biggest fan of ems but if you only want to reduce to 80% use .8em as your strong override of the .text p span size you have set.
@media screen and (max-width: 640px){
   .text p span{
      font-size: .8em;
   }
}

A: It might be worth looking into Sass/Scss for setting variables and having operators applied to them.  You can set your variables at the start of your stylesheet, and when you compile your .sass or .scss file, it outputs the correct number in your .css file
http://sass-lang.com/guide#topic-8

A: It is entirely possible and as you can probably tell there is a number of ways to achieve this. The technique I use is very simple:

*

*Set the font-size on the body and html elements in px, as well as any media query to step the font size up or down, in px.

*Use rem units to set the font-size where you need. rem stands for root em, where root is the topmost element in the DOM, usually html or body.
Example:
html, body {
  font-size: 18px;
}

@media screen and (max-width: 320px) {
  html, body {
    font-size: 15px;
  }
}

/*
The rem values use 18px or 15px as the base unit
depending on matching query.

In this case there is no need to use 1rem unless you need to reset
a previously changed value.
*/
.heading { font-size: 1.2rem; }
.small { font-size: 0.8rem; }

Using rem makes it very easy (for me at least) to reason about relative sizes.
em on the other hand is very useful if want a value to be affected by the font-size of the closest parent element.
For example if you wanted to have a padding that scales proportionally to the text size of a .heading, then you'd use em:
html, body {
  font-size: 18px;
}

@media screen and (max-width: 320px) {
  html, body {
    font-size: 15px;
  }
}

.heading { font-size: 1.2rem; }
.small { font-size: 0.8rem; }

/*
Now you define a padding that is always 80% of the element's
font-size.
And since .heading is set at 1.2rem, the padding will be
80% of 1.2rem.
*/
.heading { padding: 0.8em; }


text:
Q: How make Yesod.Auth.Email display an error when an email is already registered? I found out when I try to register an email on RegisterR which already exists, instead of displaying an error message, that the user already exists, it sends an an email confirmation request to the given email address, just like if I asked for a password reset.
After going through the sources, I found out that registerHelper checks if the email exists, and if it does, it sends a verify email even if it's already verified.
-- [...]
    mecreds <- lift $ getEmailCreds identifier
        registerCreds <-
            case mecreds of
                Just (EmailCreds lid _ _ (Just key) email) -> return $ Just (lid, key, email)
                Just (EmailCreds lid _ _ Nothing email) -> do
                    key <- liftIO $ randomKey y
                    lift $ setVerifyKey lid key
                    return $ Just (lid, key, email)
                Nothing
                    | allowUsername -> return Nothing
                    | otherwise -> do
                        key <- liftIO $ randomKey y
                        lid <- lift $ addUnverified identifier key
                        return $ Just (lid, key, identifier)

        case registerCreds of
            Nothing -> loginErrorMessageI dest (Msg.IdentifierNotFound identifier)
            Just (lid, verKey, email) -> do
                render <- getUrlRender
                let verUrl = render $ verify (toPathPiece lid) verKey
                lift $ sendVerifyEmail email verKey verUrl
                lift $ confirmationEmailSentResponse identifier
-- [...]

Source: https://hackage.haskell.org/package/yesod-auth-1.4.3.1/docs/src/Yesod-Auth-Email.html#registerHelper
Since registerCreds is a Just when the email exists and it has a key, it sends the verify email again to the user, whiche he/she can use as a password reset link.
My questions are:

*

*Why does it work this way? This basically makes registering an already existing email address equal requesting password reset. I'm sure it has a good reason, and it makes me wonder if I'm using Auth.Email correctly.

*Yesod.Auth.Email.postRegisterR gets called immediately when the request arrives - where do I have a chance to check that the email address already exists, and inform the user?

EDIT: It turned out I was looking at the source of a much older version: I updated the question. In yesod-auth-1.4.3, this code is in registerHelper, not in postRegisterR.

A: After discussing it on #yesod, this is probably a bug, so I filed an issue on it:
https://github.com/yesodweb/yesod/issues/948


text:
Q: Use environment variable in Spring beans.xml I have a peculiar requirement of setting the value of some bean from system environment variable , is this thing possible in spring ?
Pseudo code
<bean id="connectionFactory"
    class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg value="testhost" />
        <property name="username" value="$SystemEnv.RabbitUserName" />
        <property name="password" value="$SystemEnv.RabbitPassword" />
    </bean>

Now these RabbitUserName and RabbitPassword are externalized in some environmental variable which is outside .war file .
Is there any elegant way to achieve the same in spring ?

A: To get the System Environment Variable you can use this for the value:
#{ systemEnvironment['RabbitUserName'] }

The #{ systemProperties['RabbitUserName'] } mentioned in another answer won't give you a System Environment Variable, rather it will read a Java system property ie, those things you can set on the command line when starting the JVM, eg:
java -DRabbitUserName="reisen" etc...

However, this is probably a better choice of place for a connection credential than an environment variable, as, for example, you can then configure it differently for different launch configurations and it is also slightly less exposed than an environment value - which all the other applications also have full visibility on.
For more information on the difference between environent variables and system properties see Java system properties and environment variables
These are examples of the Spring Expression Language (SpEL), and you can also use it with annotation metadata, for example
@Value("#{ systemEnvironment['RabbitUserName'] }")

For more information on SpEL you can take a look at the Spring reference here: https://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/expressions.html

A: This should work.
<bean id="connectionFactory"
    class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg value="testhost" />
        <property name="username" value="#{systemProperties['RabbitUserName']}" />
        <property name="password" value="#{systemProperties['RabbitPassword']}" />
    </bean>


text:
Q: How to use Automapper in ASP.NET Core to create mapping configuration for the following type of hierarchy I would like to map the following hierarchy of entities to the TestViewModel class. I have TestViewModel class with the same member names and perhaps I will add more members to the view model. I am using AutoMapper.
public class TestProfile : Profile
{
    public TestProfile ()
    {
        CreateMap ??????
    }
}

public class Test
{
    public List<Test1> Tests1 { get; set; }
    public int TestId { get; set; }
}

public class Test1
{
    public int Test1Id { get; set; }
    public string Name { get; set; }
    public List<Document> Documents { get; set; }
}

public class Document
{
    public int DocumentId { get; set; }
    public DateTimeOffset? ChangeDate { get; set; }
    public List<Payload> Payloads { get; set; }
}

public class Payload
{
    public string PayloadName { get; set; }
}

A: You didn't tell us what your TestViewModel class looks like, and whether you also have DocumentViewModel, PayloadViewModel, etc.  Typically if you are mapping to a another set of classes that have the same naming and structure, like a set of ViewModels, you will want to have a configuration like this:
    public class TestProfile : Profile
    {
        public TestProfile()
        {
            CreateMap<Test, TestViewModel>();
            CreateMap<Test1, Test1ViewModel>();
            CreateMap<Document, DocumentViewModel>();
            CreateMap<Payload, PayloadViewModel>();
        }
    }

This will map all like-named properties between the two sets of classes.  If your TestViewModel shares the same child entities, then you only need the first line.


text:
Q: Keyword var required in front of struct value type when used as a parameter in a function Why is the keyword var required in front of a struct's value type parameter when used in a function?
struct MyValueType {
    var name:String
    var assignment:String
    var grade:Int
}

class MyReferenceType{
    var name:String
    var assignment:String
    var grade:Int
    init(name:String,assignment:String,grade:Int){
        self.name = name
        self.assignment = assignment
        self.grade = grade
    }
}

var myRef = MyReferenceType(name:"Jon",assignment:"Math Test 1",grade:90)

print(myRef.assignment)
func extraCreditReferenceType(ref:MyReferenceType,extraCredit:Int){
    ref.grade += extraCredit
}

func extraCreditValueType(var val:MyValueType,extraCredit:Int){
    val.grade += extraCredit
}

var ref = MyReferenceType(name:"Jon",assignment:"Math Test 1",grade:90)

print(ref.grade)
extraCreditReferenceType(ref,extraCredit:5)
print("Reference: \(ref.name) - \(ref.grade)")

var val = MyValueType(name:"Jon",assignment:"Math Test 1",grade:90)
extraCreditValueType(val,extraCredit:5)
print("Value: \(val.name) - \(val.grade)")

The line in question is the following function:
func extraCreditValueType(var val:MyValueType,extraCredit:Int){
    val.grade += extraCredit
}

By removing the keyword var, the code won't compile.

A: Because structs as parameters are let types by default, and because you are making changes to the struct in the function, it would have to be a var
It seems the var in the parameter is not going to be allowed in swift 3.0, so will have to remove it anyway eventually
Also your extraCreditValueType func is not going to do what you think it does, since structs are pass by value, the parameter val is not the same as the val on the outside of the function, therefore making changes to it in the function will not have an effect outside the function. you should either make MyValueType a class (and prob change the name) or return the val from the function to be used outside of the function


text:
Q: How to assign model form field to a current logged in user in Django's class based views I am trying to save a form with the current logged in user's username, but the error "Cannot assign "'Neshno_Games2'": "League.host" must be a "Manager" instance." occurs
Views.py
class CreateLeaguesView(generic.CreateView):
    model = League
    template_name = "leagues/create-league.html"
    form_class = LeaguesCreationForm
    success_url = "/leagues/leagues"

    def get_context_data(self, **kwargs):
        context = super().get_context_data( **kwargs)
        context['leagues'] = League.objects.all()
        return context

    def form_valid(self, form):
        manager = self.request.user.username
        League.objects.create(
            host = manager,
        )
        return super(CreateLeaguesView, self).form_valid(form)

Model.py
class League(models.Model):
    name = models.CharField(max_length=30)
    no_players = models.IntegerField(default=20)
    start_date = models.DateField(blank=False, null=False)
    end_date = models.DateField(blank=False, null=False)
    prize = models.CharField(max_length=300)
    host = models.ForeignKey(Manager, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

forms.py
class LeaguesCreationForm(forms.ModelForm):
    class Meta:
        model = League
        fields = (
            "name",
            "no_players",
            "start_date",
            "end_date",
            "prize",
        )

A: You can try like this:
class CreateLeaguesView(generic.CreateView):
    model = League

    def form_valid(self, form):
        form.instance.host= self.request.user.manager  # accessing one to one data
        return super().form_valid(form)

More information can be found here in this documentation: https://docs.djangoproject.com/en/4.0/topics/db/examples/one_to_one/


text:
Q: Using Angular in OOP I'm currently trying out how to implement angular in OOP.
My testsite looks like this:
class userData {

    catchDropDownSelection(){
        this.dropDownSelection = $('#xDropDown option:selected').text();
        console.log("dropDownSelection is ", this.dropDownSelection)
    }
}

class sendData{
    constructor(userData){
        this.userDataClone = userData;

    }

    sendDropDownSelection(){
        //this.userDataClone.catchDropDownSelection();
        console.log("this.userDataClone.dropDownSelection inside sendDropDownSelection is ", this.userDataClone.dropDownSelection)
        $.post("MyFirstPhP.php", {
            userSelection : this.userDataClone.dropDownSelection
        }, function (data){
            //this.testFunction()
            $('#testOutput').html(data);
            //document.getElementById("testOutput").innerHTML = "data"
        }).fail(function(){
            console.log("$.post failed!");
        })
    }

    testFunction(){
        //document.getElementById("testOutput").innerHTML = "data"
        $('#testOutput').html("data");
    }
}

class angularApps {
  constructor(sendData, userData){
    this.sendDataClone = sendData;
    this.userDataClone = userData;
  }

  xMyApp(){
    this.myApp = angular.module('xMyApp', []);
    this.myApp.controller("xMyCtrl", function($scope){
      $scope.data1 = "test1";
      $scope.data2 = "test2";
    })

  }
}

class setEvents {

  constructor(sendData, userData){
    this.sendDataClone = sendData;
    this.userDataClone = userData;
  }

  onClickEvents(){
    $('#sendDataButton').click(function(){
      this.userDataClone.catchDropDownSelection()
      //console.log("index catched is ", this.sendDataClone.userDataClone.dropDownSelection)
    }.bind(this))
    $('#sendDataButton').click(function(){
      this.sendDataClone.sendDropDownSelection()
    }.bind(this))
  }

  addAllEvents(){
    this.onClickEvents()
  }
}

var userDataInstance = new userData;
var sendDataInstance = new sendData(userDataInstance);
var angularAppsInstance =  new angularApps(sendDataInstance, userDataInstance);
var setEventsInstance = new setEvents(sendDataInstance, userDataInstance);

/*y
var myApp = angular.module('xMyApp', []);
myApp.controller("xMyCtrl", function($scope){
  $scope.data1 = "test1";
  $scope.data2 = "test2";
})*/

<!DOCTYPE html>

        <title>PHP is Awesome!</title>

        <link rel = "stylesheet" type = "text/css" href = "MyFirstPhP.css">

            {{data1 + " " + data2}}

              <select id = "xDropDown">
                  <option value = "test1">test1</option>
                  <option value = "test2">test2</option>
              </select>

            <button id="sendDataButton">ClickMe!</button>

not yet

<?php
session_start();
$dropDownSelection = $_POST['userSelection'];
echo $dropDownSelection
//$dropDownSelection = $dropDownSelection . "wurde verarbeitet!";

?>

The code sections which are the most important are those:
class angularApps {
  constructor(sendData, userData){
    this.sendDataClone = sendData;
    this.userDataClone = userData;
  }

  xMyApp(){
    this.myApp = angular.module('xMyApp', []);
    this.myApp.controller("xMyCtrl", function($scope){
      $scope.data1 = "test1";
      $scope.data2 = "test2";
    })

  }
}

and

            {{data1 + " " + data2}}

So, when I'm running the site, using OOP the div associated with angular first displays the whole angular expression string {{data1 + " " + data2}}  and then immediately switches to the resolved results after the page has completely loaded (see the onload functions inside the bodytag).
When I'm not using OOP, this cosmetical issue vanishes. First I thought I could solve this issue by simply calling the xMyApp() method from inside the script, which looks like this:
[full scriptcode]
angularAppsInstance.xMyApp()

I thought this would help because it would be similar to non-OOP, where any functionality not specifically excluded from onloadexecution is executed ASAP.
But actually, it doesn't change anything.
So, is there any elegant way to solve this issue without dropping the OOP-approach entirely? Or is it a "bad" idea to use angular inside OOP code anyway?
I've never used angular before, so I would be glad if someone could give me a tip.
EDIT: If you want to try out yourself how the OOP/non-OOP approach differ, simply comment out:
var angularAppsInstance =  new angularApps(sendDataInstance, userDataInstance);

and
angularAppsInstance.xMyApp()

and comment in this part:
var myApp = angular.module('xMyApp', []);
myApp.controller("xMyCtrl", function($scope){
$scope.data1 = "test1";
$scope.data2 = "test2";
})

A: It probably doesn't have anything to do with your style of coding. AngularJS displays moustaches if it haven't finished loading. To prevent it use ng-cloak directive.
Add this to your styles:

And for now add ng-cloak directive to your body and then go read about it on docs!


text:
Q: What is the difference between root node, root element and document element in XML? I am reading W3C XML Path Language (XPath)
Version 1.0 Section 5.1 Root Node,

The root node is the root of the tree. A root node does not occur except as the root of the tree. The element node for the document element is a child of the root node. The root node also has as children processing instruction and comment nodes for processing instructions and comments that occur in the prolog and after the end of the document element.

and I'm confused about the root node, document element terminologies, as well as root element that sometimes people use.
If I have a simple XML doc like this:
<a>
    <b1>
        <c></c>
    </b1>

    <b2></b2>
</a>

What is the root node, root element and document element? Are those all <a>?

A: In your XML:

*

*a is the document element, sometimes called the root element, which is selected via /a.

*The parent of a is the document's root node, which is selected via /.