text:
Q: Add contact in OpportunityContactRole whenever a new contact relationship is added to AccountContactRole I am new to salesforce and I am developing below functionality:
I want to add a contact in OpportunityContactRole when a new contact is added to AccountContactRole.
I have created below code:
trigger OpportunityTrigger on Opportunity (after insert, after update) {
    if(Trigger.isAfter){
        if (Trigger.isInsert) {
               AddContactRoleHandler.AddOpportunityContactRole(Trigger.new);
        } else if (Trigger.isUpdate) {

        }
    }
}

public class AddContactRoleHandler {
    public static void AddOpportunityContactRole(List<Opportunity> newOpportunities){
        Set<Id> accountIds = new Set<Id>();
        for(Opportunity oppObj : newOpportunities){
            accountIds.add(oppObj.AccountId);
        }

        Map<Id, List<Contact>> mapOfContacts = new Map<Id, List<Contact>>();

        for(Contact conObj : [SELECT Id, AccountId, Name
                                    FROM Contact
                                  WHERE AccountId IN :accountIds]){
            // mapOfContacts.put(conObj.AccountId, new List<Contact>());
            if (!mapOfContacts.containsKey(conObj.AccountId)) {
                mapOfContacts.put(conObj.AccountId, new List<Contact>());
            }

            mapOfContacts.get(conObj.AccountId).add(conObj);
        }

        List<OpportunityContactRole> listOfOCR = new List<OpportunityContactRole>();

        for(Opportunity opp : newOpportunities){
            if(mapOfContacts.containsKey(opp.AccountId) && mapOfContacts.get(opp.AccountId)!= Null)
                for(Contact con : mapOfContacts.get(opp.AccountId)){
                    OpportunityContactRole ocr = new OpportunityContactRole();
                    ocr.ContactId = con.Id;
                    ocr.OpportunityId = opp.Id;
                    ocr.Role = 'Business User';
                    listOfOCR.add(ocr);
                    System.debug('List of OCR: ' + listOfOCR);
                }
            }

            if(!listOfOCR.isEmpty()){
                insert listOfOCR;
            }
        }
    }
}

Please let me know how can I achieve this?


text:
Q: File I/O logic with a while statement, how would this code be expected to behave? I'm trying to understand some differences in file i/o techniques.  Suppose I have the following code:
FILE *work_fp;
char record[500] = {0};
while(!feof(work_fp))
{
    static int first = 1;
    fgets(record, 200, work_fp);

    if (first)
    {
        var1 = 2;
        length += var1;
    }
    first = 0;

    if (feof(work_fp))
    {
        continue;
    }
    if((int)strlen(record) < length)
    {
        fclose(work_fp);
        std::ostringstream err;
        err << "ERROR -> Found a record with fewer bytes than required in file."
            << std::endl;
        throw std::runtime_error(err.str());
    }
    const int var2 = 1;
    if(memcmp(argv[1], record + var2, 3) == 0)
    {
        load_count_struct(record, var1);
    }
}

I'm not seeing how the second if argument can be true.
if (feof(work_fp))
{
    continue;
}

If feof(work_fp) is true wouldn't the while argument be false?  Then the continue could never get called?
FOLLOW UP QUESTION:
Ok, I see how fgets can cause work_fp to reach eof conditions.
Suppose I want to try and implement this another way.  Using getline(), for example.
std::string data(file);
std::ifstream in(data.c_str());

if (!in.is_open())
{
    std::ostringstream err;
    err << "Cannot open file: " << file << std::endl;
    throw std::runtime_error(err.str());
}

std::string buffer = "";
std::string record = "";
while (getline(in, buffer))
{
    static int first = 1;

    if (first)
    {
        var1 = 2;
        length += var1;
    }
    first = 0;

    if (//What should go here?!?)
    {
        break;
    }
    // etc...
}

Any suggestions?  I'm thinking
if (buffer == std::string::npos)

no?

A: The line:
fgets(record, 200, work_fp);

can advance to read/write head to the end of the file, thus changing the return value on feof.

A: First of all, your code invokes undefined behaviour, because you've not initialized work_fp, yet you're using it, passing it to feof(), first in while(!feof(work_fp))
, and elsewhere in the code.

Anyway, supposing you initialize it by opening some file, then I would answer your question as follows:
The following code reads some data from the file using work_fp, that means, it is possible that feof(work_fp) will return true in the second if condition, because after reading data using fgets(), the file pointer work_fp may reach end of file.
fgets(record, 200, work_fp);

A: In the while loop fgets() is called and the file pointer is advanced. Then if(feof(work_fp)) checks if the end of the file is reached. If so then continue the while loop. The while loop then continues if the end of the file is NOT reached, which in this case will be false. Hence the logic works.

A: That is a weird statement, and I think it should be
if (feof(work_fp)){
    break;
}

The continue; can get called, since it occurs after an fgets, but calling continue is pointless since that brings execution to the next iteration of the loop which is guaranteed to be false and quit the loop. It makes more sense, and is more readable/understable to put break; there.

A: Since you have a fgets within the while before your check on feof, the feof status of work_fp may have changed during that read, in which case, it may evaluate to true.

A: There is a read operation on work_fp between the while and if conditions, so that feof() could be true.

A: The eof can have been reached at the following line:
 fgets(record, 200, work_fp);

So right after having been evaluated to false in the while statement.
This would make the
 if (feof(work_fp))

evaluated to true.
But this code can be simplified.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't rename MSI afterwards I am facing the following problem scenario:

*

*build an MSI the normal way ex: MyTest.msi

*rename it, leaving the msi extension. ex: MyTest_V1.0.0.msi

*Test it, it works. install success.

*Again repeat process. this time rename to ex: MyTest_V2.0.0.msi

*Test it, and it fails with a 'network error', while the file is on a local disk.

"A network error occurred while attempting to read from the file MyTest_V1.0.0.msi"
What gives, can't we simply rename an MSI file? Is there some issue that prevents this?
Now i stuck in this. please guide.
Highest Regards,
Muhammad Mubashir.

A: When you rename a MSI file and do not want it to have issues with any installations using the original MSI file, I recommend that you change some summary information and properties IN the renamed file.  I normally modify:

*

*The Package Code, a GUID, it needs a new GUID

*The ProductName Property needs a different name

*The ProductCode, another GUID, needs a new GUID

You can use Microsoft's Orca database editor to modify these properties, if you can find it.
Here is an article covering how to use the Orca database editor to edit Windows Installer files: https://support.microsoft.com/en-us/kb/255905
Here are some additional details: https://msdn.microsoft.com/en-us/library/windows/desktop/aa370557(v=vs.85).aspx

*

*Some systems (that have had an older version of the Windows SDK will have Orca at \Program Files (x86)\Microsoft SDKs\Windows\v7.0\Bin\Orca.msi

*2010 or earlier Windows SDKs should have it.

A: There is no limit in renaming MSI files.
But there are other traps, for example with updating MSIs, and some of the even include renaming.
If you want to update an MSI file with a socalled "Small Update" or "Minor Upgrade", it is no good idea to rename the MSI file !
You write

•Test it, it works. install success.
  •Again repeat process.

I read nothing if you have uninstalled the old MSI in between (that would be a solution) or what type of update you V2.0 MSI shall be.
If you are not aware of the MSI upgrade details, first inform about the update types, the two mentioned and additionally "Major Upgrades". The latter have a little bit less traps than the first two :-)
(Patch upgrades I would leave out until you are really experienced.)
You can do a number of things wrong with updates. Be sure to have someone on board who is really experienced with MSI, otherwise there will be trouble, sooner or later.
Generally, if you are looking for a problem like yours, put out a logfile. You will find the described error there but often more information around.

A:  I found solution my self. This is just like tutorial for WebSite Installer Setup. **
Steps:
For WebSites setup you have to install webDeployemnt setup and then from VS Add WebDeployemnt Project and this webProject ADD as referrence in etup project.
example: Precomiled Web Putputs from WebDeploy Project.
Difference b/w WebSite and Web App.
Websites have morethan one assemblies and not have .sln file.
WebApp have .sln file so all assemblies merge in one.
1- Set Setup Properties:

*

*RemovePreviousVersion True.

*DetectNewerVersionInstalled False.

2- Using vbScript or c# code in postbuild event of Setup Project;

*

*Change Product Version of your MSI.

*Change Product Code of your MSI. New Guid 32 char.

*Set MaxVersion to your New Version. this is available in Upgrade table of MSI.

*Makesure UpgradeCode must be same in all cases. means beware Not change it.

below i post both VbScript PBE.vbs and C# code.
Help webLinks from here i got an idea to overcome my problem:
https://www.simple-talk.com/dotnet/visual-studio/updates-to-setup-projects/
PBE.vbs calling from PostbuildEvent of MSIProject. cscript //nologo "$(ProjectDir)PBE.vbs" "$(BuiltOuputPath)"
Dim pInstaller
    Set pInstaller = CreateObject("WindowsInstaller.Installer")
    Dim pDatabase
    Set pDatabase = pInstaller.OpenDatabase(WScript.Arguments(0), 2)

    Dim pView1
    Set pView1 = pDatabase.OpenView("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'")
    pView1.Execute
    Dim pRecord1
    Set pRecord1 = pView1.Fetch
    If (Not pRecord1 Is Nothing) Then
        pRecord1.StringData(1) = "1.0.5"
    Else
        MsgBox "Error during ProductVersion."
    End If
    pView1.Modify 4, pRecord1
    pView1.Close
    'MsgBox "Product Version is: " + pRecord1.StringData(1)

    Dim pView3
    Set pView3 = pDatabase.OpenView("SELECT VersionMax FROM Upgrade")
    pView3.Execute
    Dim pRecord3
    Set pRecord3 = pView3.Fetch
    If (Not pRecord3 Is Nothing) Then
        pRecord3.StringData(1) = pRecord1.StringData(1)
    Else
        MsgBox "Error during VersionMax."
    End If
    pView3.Modify 4, pRecord3
    pView3.Close
    MsgBox "VersionMax is: " + pRecord3.StringData(1)

    Dim pView2
    Set pView2 = pDatabase.OpenView("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductCode'")
    pView2.Execute
    Dim pRecord2
    Set pRecord2 = pView2.Fetch
    If (Not pRecord2 Is Nothing) Then
        pRecord2.StringData(1) = CreateGUID()
    Else
        MsgBox "Error during ProductCode."
    End If
    pView2.Modify 4, pRecord2
    pView2.Close

    'MsgBox "Product Code is: " + pRecord2.StringData(1)

    pDatabase.Commit

Function CreateGUID
  Dim TypeLib
  Set TypeLib = CreateObject("Scriptlet.TypeLib")
  CreateGUID = Left(TypeLib.Guid, 38)
End Function

C# Console App code to do Rename msi file.

First you have to Add referrence in New Console app. That's a .NET
  wrapper generated by tlbimp.exe, wrapping the ActiveX component
  c:\windows\system32\msi.dll.   You can let the IDE make one for you
  with Project + Add Reference, COM tab,  select "Microsoft Windows
  Installer Object Library".

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;
using System.Diagnostics;

// cscript //nologo "$(ProjectDir)WiRunSql.vbs" "$(BuiltOuputPath)" "UPDATE `Property` SET `Property`.`Value`='4.0.0.1' WHERE `Property`='ProductVersion'"
// "SELECT `Property`.`ProductVersion` FROM `Property` WHERE `Property`.`Property` = 'ProductVersion'"

/*
 * That's a .NET wrapper generated by tlbimp.exe, wrapping the ActiveX component c:\windows\system32\msi.dll.
 * You can let the IDE make one for you with Project + Add Reference, COM tab,
 * select "Microsoft Windows Installer Object Library".
 */
namespace RenameMSI
{
    [System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
    class Installer { }
    class Program
    {
        static void Main(string[] args)
        {
            #region New code.

            string msiFilePath = string.Empty;

            if (args.Length == 0)
            {
                Console.WriteLine("Enter MSI file complete path:");
                //msiFilePath = Console.ReadLine();
                 msiFilePath = @"D:\TEST Projects\TestWebsites\MsiSetupForAsp.netApp\TestWebApplicationSetup\Debug\TestWebApplicationSetup.msi";
            }
            else
            {
                Console.WriteLine("Argument Received args[0]: " + args[0]);
                msiFilePath = args[0];
            }

            ////Debugger.Launch();
            StringBuilder sb = new StringBuilder();
            string[] words = msiFilePath.Split('\\');
            foreach (string word in words)
            {
                sb.Append(word + '\\');

                if (word.Contains("Debug") || word.Contains("Release"))
                {
                    break;
                }
                else
                {

                }
            }

            Program p = new Program();
            string VersionMax = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
            string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");

            p.SetMsiProperty(msiFilePath, "ProductVersion", "mub.sni");
            p.SetMsiProperty(msiFilePath, "ProductName", "mub.sni");
            //p.setMaxVersion(msiFilePath, );

            //p.RenameMSI(msiFilePath);

            #endregion

            #region old code.
            //String inputFile = @"C:\\Install1.msi";
            //// Get the type of the Windows Installer object
            //Type installerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");

            //// Create the Windows Installer object
            //Installer installer = (Installer)Activator.CreateInstance(installerType);

            //WindowsInstaller.Installer ins = (WindowsInstaller.Installer)new Installer();

            //string MSIpath = @"";

            //Database db = ins.OpenDatabase(MSIpath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file

            //// Open a view on the Property table for the Label property
            //View vw = db.OpenView(@"SELECT * FROM Property WHERE Property = 'ProductVersion'");  // I'd like to pull from other tables besides Property as well

            //vw.Execute(null); // Execute the view query

            //Record record = vw.Fetch(); // Get the record from the view

            ////// Get the Label from the data
            //string Label = record.get_StringData(2);
            //String[] a = Label.Split('.');

            //string MajorNumber = a[0];
            //string MinorNumber = a[1];

            //int RevisionNumber = 0;
            //int.TryParse(a[a.Length - 1], out RevisionNumber);
            //RevisionNumber++;

            //Console.WriteLine("Before " + record.get_StringData(1) + ": " + record.get_StringData(2));
            //record.set_StringData(a.Length - 1, String.Concat(MajorNumber, ".", MinorNumber, ".",  RevisionNumber.ToString()));

            //Console.WriteLine("After " + record.get_StringData(1) + ": " + record.get_StringData(2));
            //while (record != null)
            //{
            //    Console.WriteLine(record.get_StringData(1));
            //    record.set_StringData(1, RevisionNumber.ToString());

            //    record = vw.Fetch();
            //}

            //vw.Modify(MsiViewModify.msiViewModifyMerge, record);

            //vw.Close();
            //db.Commit();
            #endregion

            //Console.Read();
        }
        private void setMaxVersion()
        {
        }
        private void RenameMSI(string msiFilePath)
        {
            StringBuilder sb = new StringBuilder();
            string[] words = msiFilePath.Split('\\');
            foreach (string word in words)
            {
                sb.Append(word + '\\');

                if (word.Contains("Debug") || word.Contains("Release"))
                {
                    break;
                }
                else
                {

                }
            }

            Program p = new Program();
            string VersionMax = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
            string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");

            string newMSIpath = sb.ToString() + string.Format("{0}_{1}.msi", productName, VersionMax);
            Console.WriteLine("Original MSI File Path: " + msiFilePath);
            Console.WriteLine("New MSI File Path: " + newMSIpath);

            System.IO.File.Move(msiFilePath, newMSIpath);
        }
        private string GetMsiVersionProperty(string msiFilePath, string property)
        {
            string retVal = string.Empty;

            // Create an Installer instance
            WindowsInstaller.Installer installer = (WindowsInstaller.Installer)new Installer();

            // Open the msi file for reading
            // 0 - Read, 1 - Read/Write
            Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file

            // Fetch the requested property
            string sql = String.Format("SELECT Value FROM Property WHERE Property='{0}'", property);
            //string sql = "SELECT * FROM Upgrade"; // "SELECT VersionMax FROM Upgrade"

            View view = db.OpenView(sql);
            //View view = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
            view.Execute(null);

            // Read in the fetched record
            Record record = view.Fetch();
            if (record != null)
            {
                retVal = record.get_StringData(1);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
            }
            view.Close();

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);

            return retVal;
        }
        private string SetMsiProperty(string msiFilePath, string property, string value)
        {
            string retVal = string.Empty;

            // Create an Installer instance
            WindowsInstaller.Installer installer = (WindowsInstaller.Installer)new Installer();

            // Open the msi file for reading
            // 0 - Read, 1 - Read/Write
            Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeTransact); //// Open the MSI database in the input file

            // Fetch the requested property
            string sql = String.Format("SELECT Value FROM Property WHERE Property='{0}'", property);

            View view = db.OpenView(sql); //View vw = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
            view.Execute(null);

            // Read in the fetched record
            Record record = view.Fetch();
            if (record != null)
            {
                record.set_StringData(1, value);

            }

            view.Modify(MsiViewModify.msiViewModifyReplace, record);
            view.Close();
            db.Commit();

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);

            return retVal;
        }
        static string GetMsiProperty(string msiFile, string property)
        {
            string retVal = string.Empty;
            return retVal;
        }
    }
}


text:
Q: MySQL get pairs of rows from same set of foreign table My issue is the next one.
I have 3 tables: People, Cars and Driven:
People:
Id     Name
1   |   Tom
2   |   James
3   |   Charles
4   |   Eric
5   |   Thomas
6   |   Robert
7   |   Kim
8   |   Ellias

Cars:
Id      Name
1   |   Ford
2   |   Nissan
3   |   Hyundai

Driven:
PID    CID (People ID & Car ID)
1    |   1
2    |   1
5    |   1
5    |   2
6    |   1
6    |   2
7    |   1
7    |   2
7    |   3
8    |   1

I Want to retrieve pairs of people that driven the SAME SET OF CARS.
I mean: if Tom driven only Ford and James driven also ONLY Ford, i want to return this pair Tom/James as result. Also i want to include pairs of people that didn't driven any car (ie. Charles/Eric (0 cars driven both)).
The query result with the example above should return two columns per result, for example:
Name       Name
Tom     |  James     (Only Ford)
Tom     |  Ellias    (Only Ford)
James   |  Ellias    (Only Ford)
Charles |  Eric      (None BOTH)
Thomas  |  Robert    (Ford and Nissan BOTH)

Also notice that Kim has driven Ford, Nissan and Hyundai. So Kim is not going to be pair with anybody. Tom James and Ellias all are driven Ford, so they are pair with themselves.
I'm tried with cartesian product and relational division, but I didn't find a solution. If someone can help me at least with a tip i will be really grateful. Thanks!

A: You can use the following query:
SELECT p.Id, p.Name,
          COALESCE(GROUP_CONCAT(c.Name ORDER BY c.Name), 'None') AS cars_driven
FROM People AS p
LEFT JOIN Driven AS d ON p.Id = d.PID
LEFT JOIN Cars AS c ON c.Id = d.CID
GROUP BY p.Id, p.Name;

to get the list of cars driven per person.
Output:
Id Name    cars_driven
-----------------------
1  Tom     Ford
2  James   Ford
3  Charles None
4  Eric    None
5  Thomas  Ford,Nissan
6  Robert  Ford,Nissan
7  Kim     Ford,Hyundai,Nissan
8  Ellias  Ford

Using the above query twice as a derived table you can get the required result:
SELECT t1.Name, t2.Name, t1.cars_driven
FROM (
   SELECT p.Id, p.Name,
          COALESCE(GROUP_CONCAT(c.Name ORDER BY c.Name), 'None') AS cars_driven
   FROM People AS p
   LEFT JOIN Driven AS d ON p.Id = d.PID
   LEFT JOIN Cars AS c ON c.Id = d.CID
   GROUP BY p.Id, p.Name) AS t1
JOIN (
   SELECT p.Id, p.Name,
          COALESCE(GROUP_CONCAT(c.Name ORDER BY c.Name), 'None') AS cars_driven
   FROM People AS p
   LEFT JOIN Driven AS d ON p.Id = d.PID
   LEFT JOIN Cars AS c ON c.Id = d.CID
   GROUP BY p.Id, p.Name
) AS t2 ON t1.Id < t2.Id AND t1.cars_driven = t2.cars_driven;

Output:
Name    Name    cars_driven
----------------------------
Tom     James    Ford
Charles Eric     None
Thomas  Robert   Ford,Nissan
Tom     Ellias   Ford
James   Ellias   Ford

Demo here


text:
Q: Should log4.properties be on the classpath? I'm having some problems putting my log4j.properties file on classpath. I can use it when I'm developing (Eclipse Indigo) but, when I export my app as a JAR, I can't.
I've made by hand a MANIFEST.MF file for the exported JAR:
Manifest-Version: 1.0
Main-Class: main.Program
Class-Path: lib/log4j.properties lib/log4j-1.2.15.jar

And then with put the JAR on this file organization:
folder
  |-------- app.jar
  |-------- lib
             |--------- log4j.properties
             |--------- log4j-1.2.15.jar

When I try to run app.jar, they find log4j.jar but not log4j.properties:
log4j:WARN No appenders could be found for logger (main.Program).
log4j:WARN Please initialize the log4j system properly.

My log4j.properties file it's like this:
log4j.rootLogger=INFO, stdout, file

PATTERN=[%d] [%p] [%c{1}]: %m%n

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=${PATTERN}

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.File=${logger_file_path}
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=${PATTERN}

A: one more way to do this:
    -Dlog4j.configuration=file:"./log4j.properties"

A: There are three ways l know.

*

*Add log4j.properties to app.jar

*Put the log4j.properties to the "folder" (where the JAR exists) and change the class-path to .lib/log4j-1.2.15.jar.

*Put the log4j.properties to the folder named "conf" for example, and change the class-path to ./conf/.

I have tried, it works.

A: Do not put the log4j.properties itself in the classpath, but the directory that contains that file.
Class-Path: lib lib/log4j-1.2.15.jar

A: Add log4j.properties to app.jar.

A: I tried the answer of Jesper, and at first it didn't work. Then I tried with
Class-Path: lib/ lib/log4j-1.2.15.jar

And it worked after that.

A: try to execute:
javar -jar -Dlog4j.configuration=file:"./log4j.properties" app.jar


text:
Q: How to properly index Sitecore 7 content in Solr with partial language fallback? I have a Sitecore 7.5 site that uses Solr 4.7 as the search engine.  It works great.  This is a multi-language site.  I am also using the Partial Language Fallback module written by Alex Shyba.  I have adapted it to work with Sitecore 7.5 and it works well.  The last part that I can't figure out is how to get the Solr search to work with partial language fallback.  I am guessing that what I need to do is somehow at indexing time I need to index the content for all languages and pull field values from the fallback language as necessary.  So let's say that I have the following:

*

*The site has 4 languages (English, Spanish, French, German)

*a Contact Us Page with 3 fields (Title, Subtitle, Content)

*There is an English version of the Contact Us page

*There is a Spanish version of the Contact Us page with all 3 fields filled out in Spanish

*There is a French version of the Contact Us page that only has the Content field filled out in French

*There is no German version of the Contact Us page

The Partial Language Fallback module handles this scenario perfectly.  No matter what language is the current context language, I still see the Contact Us page and all of the fields on the page.
But I'm not sure how I should have Solr index this content.  My guess is that somehow I need to tell Solr when it indexes to create a full index of the Contact Us page in all 4 languages and use the English content for each field if there is no content in that language.  I found a blog post online that showed how to do this for Lucene.  But I'm not sure how I would do this with Solr.  Does anyone know how to handle this in Solr?


text:
Q: Docker: create database schema on image build is not working Here's what I'm trying to do:
I'm building a simple Flask app connected to SQLite.
I want to create the SQLite database schema during the image build time.
Since SQLite is based on regular files instead of sockets, I need to do some checks to see if the file doesn't exist and so on.
I also want the path to the database file to be set in an enviroment variable, which will be later used by the application to actually run the queries.
My .env file:
SQLITE_DB_FILE=/data/search_history_new.db

My Dockerfile:
FROM python:3.7-alpine
ARG sqlite_db_file
WORKDIR /app
RUN apk add --no-cache gcc musl-dev linux-headers sqlite
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
RUN ./setup.sh ${sqlite_db_file}
CMD ["flask", "run"]

The setup.sh file:
#!/bin/sh
DB_FILE=${1:-'./.data/search_history.db'}
echo "Checking for the existence of database file: ${DB_FILE}"
if [ ! -f "$DB_FILE" -o ! -s "$DB_FILE" ]; then
  echo "Database not initialized yet..."

  echo "Creating database file..."
  mkdir -p $(dirname "$DB_FILE")
  touch "$DB_FILE"

  echo "Done."
fi

echo "Executing database schema..."
sqlite3 "$DB_FILE" < ./search_history/database/schema.sql

echo "All set."

My schema.sql file:
DROP TABLE IF EXIStS search_history;

CREATE TABLE search_history(
  id VARCHAR(30) NOT NULL PRIMARY KEY,
  created_at INTEGER NOT NULL DEFAULT CURRENT_TIMESTAMP,
  full_address TEXT NOT NULL,
  postal_code TEXT NOT NULL,
  country_code TEXT NOT NULL,
  latitude DECIMAL(10,7) NOT NULL,
  longitude DECIMAL(10,7) NOT NULL,
  temperature DECIMAL(6,2)
);

CREATE INDEX idx_postal_code_country_code on
  search_history(postal_code, country_code);

CREATE INDEX idx_created_at on
  search_history(created_at DESC);

My docker-compose.yml file:
version: '3'
services:
  server:
    build:
      context: .
      args:
      - sqlite_db_file=${SQLITE_DB_FILE}
    env_file: .env
    environment:
      FLASK_APP: app.py
      FLASK_RUN_HOST: 0.0.0.0
    ports:
    - "5000:5000"
    volumes:
    - ./.data:/app/.data

The problem is that during the build time (docker-compose build) the database file is not being created, even though the command that creates is being executed.
When I start the server, I notice that the DB file is created, but it's completely empty.
Then of I try to run a query, I get the following error:
{
    "message": "no such table: search_history"
}

What am I missing?
Edit
I noticed the following pattern:

*

*When I run docker-compose build, the host .data directory is not created.

*When I run docker-compose run, the .data directory is created with the search_history.db file being empty.

Edit #2
I also noticed that the .data directory created is owned by root.
If I stop the container and change its owner to my user and start it again, everything works as expected.


text:
Q: How do you experimentally distinguish $\psi_1 \otimes \psi_2$ and $\psi_2 \otimes \psi_1$? What I am asking is that $\psi_1 \otimes  \psi_2$ and $\psi_2 \otimes  \psi_1$ are obviously different states.
However, theoretically a measurement can be done that these to states will give two different eigenvalues.

A: Staying within single-particle QM for the moment, if $\psi_1$ and $\psi_2$ are different states, then there exists an operator $\hat A$ that has at least some nonzero probability of producing different eigenvalues for the two, and which can be used to discriminate between them.
This is a broad area, because of the various ways in which you might want to go about this: does the measurement need to be unambiguous? can you accept a finite probability of failure? are your states orthogonal? and so on. The general problem is known as quantum state discrimination, and this paper and this one look like good reviews. The details of the interpretation do matter, but the take-home message is that there exists an operator $\hat A$ for which (possibly repeated) measurements can be used to distinguish between $\psi_1$ and $\psi_2$.
Now, if you have a two-particle system and you want to distinguish between $\psi_1\otimes \psi_2$ and $\psi_2\otimes \psi_1$, simply perform those same measurements on $\hat A \otimes \hat A$. (Or, heck, just use those same quantum-state-discrimination tools on the pair $\phi_1=\psi_1\otimes \psi_2$ and $\phi_2=\psi_2\otimes \psi_1$.)
You're correct that this isn't broadly discussed in textbooks. That's generally because it's too trivial to be worth the space, I should think.

A: Assuming we're talking about states of two particles, the answer crucially depends on whether the particle are identical (i.e. of the same type or not).
Say we have two different particles: for example, an electron and a proton. Then the two tensor products can be distinguished by looking at which state a specific particle is in. For example, if $\psi_1$ is peaked at a position $\mathbf{r}_1$ and $\psi_2$ at $\mathbf{r}_2$, you simply look near $\mathbf{r}_1$ and see what particle you find there.
But if the particles are identical, this doesn't work! If you have two electrons (or two protons, or two whatevers), then the states $\psi_1 \otimes \psi_2$ and $\psi_2 \otimes \psi_1$ are completely indistinguishable. This means that we shouldn't even use them as states! I'm not going to write down the whole theory of identical particles here, but the upshot is this: we should use states that are the same if we rearrange the order of the particles. "The same" means equal up to a phase, and it can be shown that this phase can be at most a minus sign, so in principle we could have two states:
$$\psi_S = \frac{1}{\sqrt{2}}(\psi_1 \otimes \psi_2 + \psi_2 \otimes \psi_1)$$
$$\psi_A = \frac{1}{\sqrt{2}}(\psi_1 \otimes \psi_2 - \psi_2 \otimes \psi_1)$$
And as it turns out, we are not free to choose. The type of particle determines which one we have to use. Bosons, which have integer spin (so spin 0, spin 1, etc.) use symmetric states. Fermiones, which have half-integer spin, use antisymmetric states.


text:
Q: Validation rule on lead object Requirement:
When New Lead is created with Course Type as online, phone no cannot be blank
The below validation rule which i tried.
AND(
ISNEW(ISPICKVAL(CourseType__c,'online'))),
ISNULL(Phone)

A: AND( ISNEW(),ISPICKVAL(CourseType__c,'online'),ISBLANK(Phone))

A: The ISNEW function does not take any parameters.
AND(
    ISNEW(),
    ISPICKVAL(CourseType__c, 'online'),
    ISNULL(Phone)
)

A: I think this one also works well.
Please use this formula:
IF(ISNEW() && Phone==null && ISPICKVAL(CourseType__c ,'online'),true, false)
As Adrian is saying we also need to add the ISNEW() in the formula to target new records only..so, I added the ISNEW() in the formula and it works fine.


text:
Q: MVC3 How to check if HttpPostedFileBase is an image I have a controller like this:
public ActionResult Upload (int id, HttpPostedFileBase uploadFile)
{
....
}

How can I make sure that uploadFile is an image (jpg, png etc.)
I have tried with
using (var bitmapImage = new Bitmap (uploadFile.InputStream)) {..}

which throws an ArgumentException if bitmapImage can not be created.
Is there a better way for example by looking at uploadFile.FileName?

A: You can check the HttpPostedFileBase object's properties for this

*

*ContentType

*FileName (check the file extensions, which you already know about :) )

Also here is a small method, I have prepared which you can use/extend...
private bool IsImage(HttpPostedFileBase file)
{
    if (file.ContentType.Contains("image"))
    {
        return true;
    }

    string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more if u like...

    // linq from Henrik Stenbæk
    return formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
}

I have also written an article on this here

A: Or you can check it on client side thru html attribute 'accept' to filter the file asap:
@Html.TextBoxFor(x => x.HomeDeviceImage, new { @type = "file", @accept = "image/x-png, image/gif, image/jpeg" })

this will only show filetypes defined in your accept attribute as default. Beware, user can still change filetye to "All files", with this in mind, better check this:
Solved concern
, a javascript snippet to check extension, and then do some editing to disable button like:
            $('input:submit').attr('disabled', true);

until file extension is correct. nevertheless have it checked on server side. :)

A: You could check the file name and extension and MIME type but that might not be reliable because the user could simply rename the file before uploading. Here's a reliable way to achieve that by looking at the contents of the file: https://stackoverflow.com/a/6388927/29407
You could of course extend this to other known image type formats than PNG, like this:
public class ValidateFileAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }

        if (file.ContentLength > 1 * 1024 * 1024)
        {
            return false;
        }

        try
        {
            var allowedFormats = new[]
            {
                ImageFormat.Jpeg,
                ImageFormat.Png,
                ImageFormat.Gif,
                ImageFormat.Bmp
            };

            using (var img = Image.FromStream(file.InputStream))
            {
                return allowedFormats.Contains(img.RawFormat);
            }
        }
        catch { }
        return false;
    }
}


text:
Q: how to get rows in google spreadsheets I Want To Get All The Rows And Columns In Google Spreadsheet so i can iterate over them horizontally but everytime i am trying to fetch the rows it is giving me an error please help
here is my code:
const GoogleSpreadSheet = require('google-spreadsheet');
const creds = require('./client_secret.json');
const { promisify } = require('util');
const app = require('express')()

async function accessSpreadSheet() {
    const doc = new GoogleSpreadSheet('1UkcGReVvw5Ea1IbamdFc45PWZBKXEUJI6paxO_AWwMk');
    await promisify(doc.useServiceAccountAuth)(creds);
    const info = await promisify(doc.getInfo)()
    console.log(`Title: ${info.title}`)
    const rows = await promisify(info.worksheets.getRows({
        offset: 1
    }))
    console.log(rows)
}

app.get('/', async (req, res) => {
    const info = await accessSpreadSheet()
    res.send(info)
})

app.listen(3000, () => {
    console.log('served')
})

A: As you can see in the documentation here, the getRows method is called from a singular sheet.
So in order to solve this, you will have to loop through all the sheets from the spreadsheet and later call the getRows method or just use a single sheet.
Example
const sheet = doc.worksheets[0]; // the first sheet
const rows = await sheet.getRows();
console.log(rows[0].PROPERTY1);

You can also start by taking a look at the examples from the Sheets API documentation.
Reference

*

*Sheets API Reading & Writing Cell Values.

A: I noticed you are using javascript API. I usually use Python, yet the Google Sheet API is the same.
I guess you trying to loop through all the rows in the sheet which contains data. In such case why don't you use getDataRange(), then loop through the resultant range?
The official reference has an example on how this works:
https://developers.google.com/apps-script/reference/spreadsheet/sheet#getDataRange()


text:
Q: Gatsbyjs image with Webp and fallback to jpg using picture tag not working I'm using Gatsbyjs image in my react website I tried adding fallback to jpg using the picture tag but its not working, it's just loading the jpg file here is the code
                     <Box {...portfolioImage}>
                        <picture>
                          <source
                            srcset={
                              (portfolioItem.image !== null) | undefined
                                ? portfolioItem.image.childImageSharp.fluid
                                : {}
                            }
                            type="image/webp"
                            alt={`PortfolioImage-${index + 1}`}
                          />
                          <Image
                            fluid={
                              (portfolioItem.imageFallback !== null) |
                              undefined
                                ? portfolioItem.imageFallback
                                    .childImageSharp.fluid
                                : {}
                            }
                            alt={`PortfolioImage-${index + 1}`}
                          />
                        </picture>
                      </Box>

The data
image {
              childImageSharp {
                fluid(quality: 100) {
                  ...GatsbyImageSharpFluid_withWebp
                }
              }
            }
            imageFallback {
              childImageSharp {
                fluid(quality: 100) {
                  ...GatsbyImageSharpFluid
                }
              }
            }

A: The Gatsby image is a component itself, not a data to be placed inside a srcSet attribute. In your case, you should render one component or another based on the portfolioItem.image.childImageSharp.fluid data, depending on if exist or not. In addition, those ternary conditions seem odd to me.
Assuming that your GraphQL queries work as expected and are retrieving the data. I would suggest simplier like:
{portfolioItem.imageFallback.childImageSharp.fluid
  ? <Image fluid={portfolioItem.imageFallback.childImageSharp.fluid} alt={`PortfolioImage-${index + 1}`} />
  : <picture><source srcSet={portfolioItem.imageFallback} alt={`PortfolioImage-${index + 1}`} /></picture>
}

With the snippet above you simply render the <Image> (from Gatsby image) if the data exist or the <picture> fallback image if not.
Wrapping the Gatsby Image inside a <picture> tag is not as useful as you may think since inside the image component will be a bunch of nested <div>s with the own JavaScripts fallbacks and blurs. This will change the default children of your <picture> tag causing potential issues or layout bugs.

Check for data is not the point, I set the data I need to check if the
browser supports webp image format which is what the picture tag is
supposed to do but it seems not to be working with dynamic images or
images that are loaded from JSON/grahql

Gatsby Image handles it automatically. From their documentation:

If you want to automatically use WebP images when the browser supports
the file format, use the withWebp fragments. If the browser doesn't
support WebP, gatsby-image will fall back to the default image format.

need to test this again but pretty it did not work on safari

There's a known bug in Safari (or MacOS devices) with triggering of the intersection observer. To polyfill it:
yarn add intersection-observer

In your gatsby-browser.js:
export const onClientEntry = async () => {
  if (typeof IntersectionObserver === "undefined") {
    await import("intersection-observer");
    console.log("IntersectionObserver polyfilled ;)");
  }
};


text:
Q: Syntax error in css code border: 1px solid rgba(0, 0, 0, 0.5);
background: rgba(255, 255, 255, 0.3);

Aptana 3.0.6 gives me the following error "too many values or values are not recognized" for both the above line. What is the correct syntax

A: Searching on Aptana's website revealed the following known bug:
"color: rgba(...);" causes a CSS validation error
It also states that it has been fixed in the latest version of the software (3.0.7).


text:
Q: How do I select a JSONB field into a declared variable. I'm getting a null value When I use a select into I'm getting a null value
SELECT ((payload->>'99')::jsonb)->>'BATCH_ID' into in_batch_id
  from history where id = table.ID;

When I check the value of in_batch_id it is null. I need the value of the jsonb field put into the in_batch_id varible. I'm using postgresql.
{
  "1": {
    "seq": null,
    "doc_id": null,
    "batch_id": "91"
  },
  "2": {
    "seq": null,
    "doc_id": null,
    "batch_id": "91"

  },
  "99": {
    "seq": null,
    "doc_id": null,
    "emp_id": null,
    "batch_id": 91
   }
}

A: The property value at key 99 is not a string with JSON syntax, but rather simply an object. Do not use (payload->>'99')::jsonb to access it, but simply payload->'99'.
Also …->>'BATCH_ID' is wrong when the property is actually named batch_id - case is significant in JSON. So use …->>'batch_id' instead.
SELECT payload->'99'->>'batch_id' INTO in_batch_id
FROM history
WHERE id = table.ID;


text:
Q: mod_wsgi + cherrypy = 404 - The path '/index.wsgi/' was not found The .htaccess :
AddHandler wsgi-script .wsgi
RewriteEngine On
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.wsgi/$1 [QSA,L,PT]

The index.wsgi :
import atexit
import threading
import cherrypy

cherrypy.config.update({'environment': 'embedded'})

if cherrypy.engine.state == 0:
        cherrypy.engine.start(blocking=False)
        atexit.register(cherrypy.engine.stop)

class Root:
        def index(self):
            return "..."
            index.exposed = True

    def default(self):
            return "default"
                index.exposed = True

application = cherrypy.tree.mount(Root(), "/")

*

*It is a shared host, i don't have access to apache

*I'm not allowed to use WSGIScriptAlias
The 404 error comes from cherrypy(powered by cherrypy on the botton), so i conclude apache is calling the .wsgi file correctly, it seems that its also passing /index.wsgi/, and cherrypy does not know what to do with it.
Can anyone help me with this?
I never deployed a cherrypy app before, is this the best/only/recommended way to do it?
Thanks in advance.

A: If setting RewriteBase to '/' in .htaccess, likely that you need to use:
RewriteRule ^(.*)$ /index.wsgi$1 [QSA,L,PT]


text:
Q: PHP SQL updating product in multiple category I want to add product in multiple categories in php. After lot of search/research on this I am able to add products in multiple categories but its not working while updating/changing product categories on update page . MY DB structure is as:
PRODUCTTABLE
 _____________________________________________
|    pid    |      pname   | price | pdetails |
-----------+---------------+-------+----------+

CATEGORYTABLE
 ______________________________________
|    id    |      catname   | catslug |
-----------+---------------+----------+

PRODUCT2CAT
 ____________________________
|  product_id   |   cat_id  |
-----------+----------------+

Code used on ADD PRODUCT page:(only relevent to question)
<form method="post">
...........
echo "<input type=\"checkbox\" name=\"pcateg[]\" value=\"$catid\" /> $catnm
";
...........

if(isset($_POST["submit"])) {
.........
.............
$pc2=$_POST["pcateg"];

$query1 = "insert into producttable(pname,price,image,pdetails) values('$pn','$p','$img','$pd')";
mysql_query($query1);
$prdid = mysql_insert_id();

foreach($pc2 as $key=>$values)
{
$query2 = "INSERT INTO product2cat(product_id,cat_id) VALUES('$prdid','$values') ";
$result2 = mysql_query($query2);
}

}

When I Add Product, code is working well and insert selected categories ID in PRODUCT2CAT table.
Code used on UPDATE PRODUCT Page is:
<form method="post">
...........
    while($ans=mysql_fetch_array($cresult))
    {
        $selected = "";
        $catId = $ans['id'];
        $catNm = $ans['catname'];

        if ($catId == $categ) {
        $selected = "checked";
        }

    echo "<input type=\"checkbox\" name=\"pcateg[]\" value=\"$catId\" $selected /> $catNm
";
    }
........
    if(isset($_POST["submit"])) {
    .........
    .............
    $query1="UPDATE producttable SET pname='$pn', price='$p', image='$img', pdetails='$pd' WHERE pid=$prid";
    mysql_query($query1);

    foreach($pc2 as $key=>$values)
    {
    $query2 = "UPDATE product2cat SET cat_id='$values' WHERE product_id=$prid";
    $result2 = mysql_query($query2);
    }
  }

Update $query2 is not working. Or I have to use 2 queries 1st to delete old records and then insert new record. How to use query in such situation so as to del/update selected categories on product update.

I also want to display old categories as preselected checkbox on update page. $selected = "checked" It works on single category But how to do this in multiple check.

A: *

*Do not use mysql_* it is deprecated

*INSERT INTO table_name ('col1', 'col2') VALUES (1, 2), (2, 3), (3, 4)
would insert 3 rows

Something like that might work:
$queryu = "INSERT INTO product2cat(product_id,cat_id) VALUES ";
$insertValues = array();
foreach($pc2 as $key=>$values) {
    $insertValues[]= "('$prid','$values')";
}

$queryu .= implode(',', $insertValues);


text:
Q: What will activating the web console (cockpit) do? I just installed CentOS GNU/Linux (version 8 build 1905) on a machine; this wasn't my choice of distro - I'm a Debian man myself.
Anyway, when I SSH into this machine (as a non-root user), it tells me:

Activate the web console with: systemctl enable --now cockpit.socket

What will this web console have? On which port will it listen, and for whom? Can non-root users simply activate it when they want to? I'm somewhat baffled by this, as I'm not used to CentOS.

A: See the fine manual at https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/managing_systems_using_the_rhel_8_web_console/getting-started-with-the-rhel-8-web-console_system-management-using-the-rhel-8-web-console

What will this web console have?

The RHEL web console enables you a wide range of administration tasks, including:
Managing services
Managing user accounts
Managing and monitoring system services
Configuring network interfaces and firewall
Reviewing system logs
Managing virtual machines
Creating diagnostic reports
Setting kernel dump configuration
Configuring SELinux
Updating software
Managing system subscriptions

On which port will it listen, and for whom?

Port 9090.  For all users.

Can non-root users simply activate it when they want to?

Root privs needed to activate it.  Such privs not needed to log onto it, once it's activated.
So, give it a whirl, I'd suggest, see if it's useful for you.

A: In brief generally we login to our account from CLI or GUI. After running following command
systemctl enable --now cockpit.socket

one can access their account from web browser.
Just need to type following for local run.
https://localhost:9090

A: *

*Note that you are seeing a message that is unconditionally emitted from /etc/motd.d/cockpit.  Most likely this socket is already enabled.

*You do not have to be privileged user to check if enabled with systemctl status cockpit.socket (where you can also see the port).

[nhed@nhed-ds2vm1 ~]$ systemctl status cockpit.socket
● cockpit.socket - Cockpit Web Service Socket
     Loaded: loaded (/usr/lib/systemd/system/cockpit.socket; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-02-11 10:24:48 EST; 15h ago
   Triggers: ● cockpit.service
       Docs: man:cockpit-ws(8)
     Listen: [::]:9090 (Stream)
      Tasks: 0 (limit: 2308)
     Memory: 904.0K
        CPU: 35ms
     CGroup: /system.slice/cockpit.socket

Feb 11 10:24:48 nhed-ds2vm1 systemd[1]: Starting Cockpit Web Service Socket...
Feb 11 10:24:48 nhed-ds2vm1 systemd[1]: Listening on Cockpit Web Service Socket.

I suspect the main driver for this is for either "headless" servers or perhaps for some support functionality.


text:
Q: Is the following true: if $X = Y$ in distribution, then $XI_{\{|X| < a\}} = YI_{\{|Y| < a\}}$ in distribution
Is the following true: if $X = Y$ in distribution, then $XI_{\{|X| <
 a\}} = YI_{\{|Y| < a\}}$ in distribution, where $I$ denotes the
  indicator function on the given set, and where $a$ is a fixed constant

I have to prove that $\mathbb{P}\{XI_{\{|X| < a\}} \in A\} = \mathbb{P}\{YI_{\{|Y| < a\}} \in A\}$ for any Borel set of the reals, but I honestly have no clue how to prove it. The statement seems intuitively true.

A: Assuming $X$ and $Y$ are real-valued, take any $b\in \mathbb{R}$; then it is enough to show that
$$
\mathbb{P}(X I_{|X|<a} \leq b) = \mathbb{P}(Y I_{|Y|<a} \leq b) .
$$
We have
$$
\mathbb{P}(X I_{|X|<a} \leq b)  = \mathbb{P}(-a \leq X \leq a, X \leq b ) + \mathbb{P}(|X| > a) \chi_{\{b\geq 0\}} = \\
\mathbb{P}(-a \leq X \leq \min\{a,b\})  + \mathbb{P}(|X| > a) \chi_{\{b\geq 0\}} = \\
\mathbb{P}(-a \leq Y \leq \min\{a,b\})  + \mathbb{P}(|Y| > a) \chi_{\{b\geq 0\}} = \\
\mathbb{P}(Y I_{|Y|<a} \leq b)
$$
since $X$ and $Y$ have the same distribution.


text:
Q: Select check boxes as user wish Selenium webdriver I want to click on checkboxes by getting user options. I have tried some code segments.How can I do it..It is better if it could get the list of check box labels and select options according to those options by the user.Can anyone please help.
Selenium 3.4
Chrome driver
I am new to test automation.I am using selenium web driver with java.
I have to do the automation by doing self learning.please help me
Thank you

A: I have checked the site and tried using getText(), but this approach is not working. We can use Map as a work around to key the number and checkbox values. Below codes might give you some idea.
public static void main(String[] args)
{
    System.setProperty("webdriver.chrome.driver", "");
    WebDriver driver = new ChromeDriver();

    //Add all the values as key value pait in Map
    HashMap<String, Integer> map = new HashMap<>();
    map.put("Automobile".toLowerCase(), 1);
    map.put("Baby & Toddler".toLowerCase(), 2);
    // Similary add for all 20 elements

    String toClick = "Automobile";
    WebElement element = findCheckBox(map,toClick,driver);

    //This clicks on the Automobile check box

}

private static WebElement findCheckBox(HashMap<String, Integer> map, String toClick, WebDriver driver)
{
    int number = map.get(toClick.toLowerCase());
    return driver.findElement(By.xpath("//div[@class='divleft50']["+number+"]/input"));

}

Hope this helps you. Thanks.


text:
Q: equivalent to R's `do.call` in python Is there an equivalent to R's do.call in python?
do.call(what = 'sum', args = list(1:10)) #[1] 55
do.call(what = 'mean', args = list(1:10)) #[1] 5.5

?do.call
# Description
# do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

A: There is no built-in for this, but it is easy enough to construct an equivalent.
You can look up any object from the built-ins namespace using the __builtin__ (Python 2) or builtins (Python 3) modules then apply arbitrary arguments to that with *args and **kwargs syntax:
try:
    # Python 2
    import __builtin__ as builtins
except ImportError:
    # Python 3
    import builtins

def do_call(what, *args, **kwargs):
    return getattr(builtins, what)(*args, **kwargs)

do_call('sum', range(1, 11))

Generally speaking, we don't do this in Python. If you must translate strings into function objects, it is generally preferred to build a custom dictionary:
functions = {
    'sum': sum,
    'mean': lambda v: sum(v) / len(v),
}

then look up functions from that dictionary instead:
functions['sum'](range(1, 11))

This lets you strictly control what names are available to dynamic code, preventing a user from making a nuisance of themselves by calling built-ins for their destructive or disruptive effects.

A: do.call is pretty much the equivalent of the splat operator in Python:
def mysum(a, b, c):
    return sum([a, b, c])

# normal call:
mysum(1, 2, 3)

# with a list of arguments:
mysum(*[1, 2, 3])

Note that I've had to define my own sum function since Python's sum already expects a list as an argument, so your original code would just be
sum(range(1, 11))

R has another peculiarity: do.call internally performs a function lookup of its first argument. This means that it finds the function even if it's a character string rather than an actual function. The Python equivalent above doesn't do this — see Martijn's answer for a solution to this.

A: Goes similar to previous answer, but why so complicated?
def do_call(what, args=[], kwargs = {}):
    return what(*args, **kwargs)

(Which is more elegant than my previously posted definition:)
def do_call(which, args=None, kwargs = None):
    if args is None and kwargs is not None:
        return which(**kwargs)
    elif args is not None and kwargs is None:
        return which(*args)
    else:
        return which(*args, **kwargs)

Python's sum is different than R's sum (1 argument a list expected vs.
arbitraily many arguments expected in R). So we define our own sum (mysum)
which behaves similarly to R's sum. In a similar way we define mymean.
def mysum(*args):
    return sum(args)

def mymean(*args):
    return sum(args)/len(args)

Now we can recreate your example in Python - as a reasonable 1:1 translation of the R function call.
do_call(what = mymean, args=[1, 2, 3])
## 2.0
do_call(what = mysum, args=[1, 2, 3])
## 6

For functions with argument names, we use a dict for kwargs, where the parameter
names are keys of the dictionary (as strings) and their values the values.
def myfunc(a, b, c):
    return a + b + c

do_call(what = myfunc, kwargs={"a": 1, "b": 2, "c": 3})
## 6

# we can even mix named and unnamed parts
do_call(what = myfunc, args = [1, 2], kwargs={"c": 3})
## 6


text:
Q: Calculating chart for YAxis Let's say I have a simple line chart with 5 values (a = 155, b = 200, c = 250, d = 300, e 0 345)
I need a way to calculate which values go on the Y-axis, in such a way that the values look nice. I also want to see the minor steps.
If I use a simple formula I would do this:
MaxValue - Minvalue = difference
300- 900 = 600

For 5 steps: 600/5 = 120 per step
That would lead to these values for the Y-axis:
Y0 = 200.0 (Rounding off to 200)
Y1 = 360.0 (Rounding off to 400)
Y2 = 520.0 (Rounding off to 600)
Y3 = 680.0 (Rounding off to 700)
Y4 = 840.0 (Rounding off to 900)
Y4 = 1000.0 (Rounding off to 1000)

What I actually would like is the values to be:
Y0 = 200
Y1 = 400
Y2 = 600
Y3 = 800
Y4 = 1000

But how do I calculate this?
Before calculation I don't know the magnitude of the values, it could be also like thousands, or tens.

A: Not exactly what you expect, but may give you an idea:
const int N = 6;
double vals[N] = {200.0, 360.0, 520.0, 680.0, 840.0, 1000.0};
for (int i = 0; i < N; i++) {
    double factor = pow(10.0, floor(log10(vals[i])));
    double v =  floor(vals[i] / factor + 0.5) * factor;
    std::cout << vals[i] << " " << v << std::endl;
}

P.S. Sorry, it's in C++ but you can easily translate it to Java.


text:
Q: How to acces to parent of "this" on JavaScript? I have a problem programming object-oriented in Javascript. I have the following:
class Foo{
    constructor(){...}
    ...
    a_needed_method(){...}
    ...
    a_method(){
        ...
        jsObject.on("click",function(params){
            this.a_needed_method();
        });
    }
}

The problem is, if I call the a_needed_method method using this there, then this is referencing the anonymous function that controls the onclick event. How I can call a_needed_method() from this anonymous function?

A: ES6
You can use an arrow function to preserve the lexical this:
jsObject.on("click", params => {
  this.a_needed_method();
});

ES5
You can use the good old that = this:
var that = this;
jsObject.on("click", function (params) {
  that.a_needed_method();
});

A: you can use bind:
    jsObject.on("click",function(params){
        this.a_needed_method();
    }.bind(this));

let jsObject = $(this);

class Foo {
  constructor() {

  }

  a_needed_method() {
    console.log('That works !');
  }

  a_method() {
    jsObject.on("click", function(params) {
      this.a_needed_method();
    }.bind(this));
  }
}

let x = new Foo();
x.a_method();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click anywhere

or arrow function from es6:
    jsObject.on("click",(params) => {
        this.a_needed_method();
    });

let jsObject = $(this);

class Foo {
  constructor() {

  }

  a_needed_method() {
    console.log('That works !');
  }

  a_method() {
    jsObject.on("click", (params) => {
      this.a_needed_method();
    });
  }
}

let x = new Foo();
x.a_method();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click anywhere

A: In your constructor you can say:
constructor(){
  this.a_needed_method = this.a_needed_method.bind(this);
}

A: Assuming this is the class inside a_method, and that it's called with that execution context, and assuming the event handler is using jQuery, you could simply use event.data to pass anything you'd like to the event handlers callback, that's what event.data was meant to do
a_method(){
    ...
    jsObject.on("click", {klass : this}, function(params){
        params.data.klass.a_needed_method();
    });
}

let jsObject = $(this);

class Foo{
    constructor(){

    }

    a_needed_method(){
      console.log('That works !');
    }

    a_method(){
        jsObject.on("click", {klass : this}, function(params){
            params.data.klass.a_needed_method();
        });
    }
}

let x = new Foo();
x.a_method();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click anywhere


text:
Q: Cant access WAMP over LAN I have read many posts here and many tutorials as well.. and for some reason..  I just cant get access to my WAMP install/pages/content from other machines on the network?
WAMP 2.4 (still) :)
Here is what I have tried so far:
WAMP install machine IP:  192.168.1.121

*

*I have enabled/disbaled Windows Firewall on the WAMP install machine (completely for testing)

*I have created a an INBOUND rule allowing  (TCP, on PORT 80, private option selected only, also tried to check public)

Apache httpd.config:

*

*Listen 192.168.1.121:80

*Listen 80

Then a bit below:

*

*Order Deny,Allow

*Allow from 127.0.0.1

*Allow from ::1

*Allow from localhost

*Allow from 192.168.1.101

*Allow from all

Complete:
    <Directory "c:/wamp/www">
    Options Indexes FollowSymLinks

    AllowOverride All

    # onlineoffline tag - don't remove
    Order Deny,Allow
    # Deny from all
    Allow from 127.0.0.1
    Allow from ::1
    Allow from localhost
    Allow from 192.168.1.101
    Allow from all

    </Directory>

I my Apache httpd-vhosts.conf file I have (outside of some other default and test entries) the following:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot "c:/wamp/www"
    ServerName localhost
    <Directory  "c:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@BarBot.com
    DocumentRoot "c:/wamp/www/barbot/"
    ServerName BarBot
    ErrorLog "logs/BarBot-error.log"
    CustomLog "logs/BarBot-access.log" common
    <directory "c:/wamp/www/barbot/">
        Options +Indexes +FollowSymLinks +MultiViews
    Require all granted

    #Deny from all
    #AllowOverride All
    #Allow from 127.0.0.1
    #Require all granted
    #Require ip 192.168.1
    #Require ip 192.168.1:80

    </directory>
</VirtualHost>

I grabbed a netbook I had laying around.. plugged it into my network..
loaded up browser and went to:
192.168.1.121
as well as
192.168.1.121:80
192.168.1.121:80/barbot
I will either get:

*

*timed out message on browser..
or more recently

*Not found: The requested URL /barbot was not found..etc..etc..
At this point I am lost..   I dont even have a direction to pursue or test with?
I have also tried to toggle putting WAMP online/offline..  neither state seemed to make a difference?
What am I missing here?  What things can I test out?  And is there a way to check on things?  Logs? Errors?  Something that will give me direction?  Or help get direction at least?)
Update:
Second PC -
IP:  192.168.1.101
I can PING the 192.168.1.121 machine just fine.. never misses a packet.

Final State:
Something is 'working', but must be configured somehow/somewhere?
When I attempt to open:  192.168.1.121:80/barbot (WAMP machine)  I get a NOT FOUND (404) page...
If I try to go to say... 192.168.1.121:8080  (I get Unable to Connect page/message)..


text:
Q: How can I use regex in python so that characters not included are disallowed? Here is the code:
import re
name = input("Enter a username: ")
y = len(name)
for i in range (0, y):
    valid = re.match("[A-Za-z0-9!£$%^&*]", name[i])
if valid:
    print("Username valid")
else:
    print("Username inavlid, try again")

When I enter a username containing the only the characters in the regex, it prints "Username valid", and when I enter one containing only characters not included, "Username invalid, try again" is printed.
However, when I enter a combination of allowed characters and characters that aren't allowed, the password is validated. How can I make it so that if even one of the entered characters is not in the regex, the program says that the username is invalid?
Thanks in advance.

A: The semantic error is that you keep overwriting the content of valid even when there has been no match on the character before.
Avoid the for loop altogether and change the regex to "[A-Za-z0-9!£$%^&*]+$"


text:
Q: What is reason of time difference in same hashing algorithms? i have read this article in Codeproject:
Salted-Password-Hashing-Doing-it-Right.
and i understand that the best hash algorithm for asp.net webforms is PBKDF2-HMAC-SHA512. and then this github implementation:
My implementations of PBKDF2 in PHP, C#, Java, and Ruby.
it's based on PBKDF2-HMAC-SHA1.
i googled to find something that help me to make a hash based on PBKDF2-HMAC-SHA512.
and i've found this library on github:
therealmagicmike/PBKDF2.NET.
in this library i can define my hash algorithm like HMACSHA1, HMACSHA256, HMACSHA384 or HMACSHA512.
and as you know HMACSHA1 is faster than HMACSHA512. and it's not good in security reasons.
But i've found something that i don't know it's true or not! i've implemented both algorithms in same page and understand that adriancs's algorithm takes longer time than the mike's. and it's not logical as for adriancs's article.
So, i want to know which algorithm is slowest and also which is better?
any help will be appreciated.
Thanks a lot.

A: Sorry to find this so late. I'm the author of PBKDF2.NET. The speed difference is due to the equality comparison. The library by Defuse implements a slow-compare function, where I chose to leave any custom comparisons up to the consumer. My reasoning is that I didn't want to create a library with additional non-essential utility functions but rather to provide a proper implementation of the algorithm. Whether or not a particular application requires a slow compare really depends on the application so I excluded this.


text:
Q: c# to c++ large data error I'm passing data from c# to c++, and I'm having an issue. At a certain point I get an error (either AccessViolation or SEHException).  My C++ code is essentially just making pointers to a bunch of data.  Whenever I get to a decently large number, it crashes.
Here's the c++ code:
Header
#define proto(args) args
#define DllImport     _declspec(dllimport)
#define DllExport     _declspec(dllexport)
#define  Dll16Exp
#define  Dll16Far

class Main
{
public:
    Main();
    ~Main();
};

int cpgIOSetNewClosedProfile(int, int);
int cpgIOInitPofileList proto((int));
extern "C" {
    DllExport int   Dll16Exp NSetInitProfileList(int);
    DllExport int  NSetNewClosedProfile(int cnt, int totProfile);
}

class ent2d_des_cpg {
public:
    int         type;
    ent2d_des_cpg();
    ~ent2d_des_cpg() {}

};

class CPartProfile
{

public:
    ent2d_des_cpg       *closedProfile; /* List of primitives. */
    CPartProfile();
    CPartProfile(long totalEntities);
    ~CPartProfile() { if (closedProfile != NULL) { delete[] closedProfile; } }

};

class CPartProfileList
{

public:
    CPartProfile * cpgPartProfileList;

    CPartProfileList();
    CPartProfileList(long totalPartProfiles);
    ~CPartProfileList() { if (cpgPartProfileList != NULL) { delete[]         cpgPartProfileList; cpgPartProfileList = NULL; } }

};

Main C++ file:
#include "stdafx.h"
#include "Main.h"

CPartProfileList    *ProfileList;

Main::Main()
{
}

Main::~Main()
{
}

ent2d_des_cpg::ent2d_des_cpg()
{
    type = -1;
}

int cpgIOSetNewClosedProfile(int cnt, int TotProfile)
{
    ProfileList->cpgPartProfileList[cnt].closedProfile = new ent2d_des_cpg[TotProfile];
    return true;
}

int cpgIOInitPofileList proto((int TotProfiles))
{
    ProfileList = new CPartProfileList(TotProfiles);
    return true;
}

DllExport int Dll16Exp NSetInitProfileList(int TotProfiles)
{
    int retval = 0;
    retval = cpgIOInitPofileList(TotProfiles);
    return(retval);
}

DllExport int NSetNewClosedProfile(int cnt, int totProfile)
{
    int retval = 0;
    retval = cpgIOSetNewClosedProfile(cnt, totProfile);
    return(retval);
}

CPartProfileList::CPartProfileList()
{
}

CPartProfileList::CPartProfileList(long totalPartProfiles)
{
    cpgPartProfileList = new CPartProfile[totalPartProfiles];
}

CPartProfile::CPartProfile()
{
}

CPartProfile::CPartProfile(long totalEntities)
{
    closedProfile = new ent2d_des_cpg[totalEntities];
}

and last, the simple C# loop that i'm testing with:
[DllImport(@"TestInterop2.dll", EntryPoint = "NSetInitProfileList", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern int NSetInitProfileList(int TotProfiles);

[DllImport(@"TestInterop2.dll", EntryPoint = "NSetNewClosedProfile", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern int NSetNewClosedProfile(int cnt, int totProfile);

public void testRun()
    {
        for(int i = 0; i < 3000; i++)
        {
            NSetInitProfileList(3000);
            for(int j = 0; j < 3000; j++)
            {
                NSetNewClosedProfile(i, 300);
            }
        }
    }

I don't know much about how C++ operates. Am I just hitting a heap/memory max?  Other than writing to a file, is there another/better way to do this?


text:
Q: Python: Storing List Objects Externally I am currently running a project with a workflow in the following form:
An input goes through a slow (95% of programme runtime) process to form an output list (data). Fast operations are then performed on the list to create a final output.
Is there a sensible way I can store data externally to my python script so that I can run the slow process once and then trial the final stages (reading  data in rather than reassembling it)?
EDIT: Considered exporting to 'simple' formats (MS Excel / MySQL) which proved unhelpful as the strings were both too long and contained special characters.

A: So it appears pickle was what I was searching for (thanks to corn3lius and Two-Bit Alchemist for their comments).
A simple example (reproduced from https://wiki.python.org/moin/UsingPickle):
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.
import pickle

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }`


text:
Q: How to share video on Facebook I'm developing an IPhone app where I have added videos. I would like to share that videos on Facebook. I have added FbGraphAPI. I don't know how to should I share video.
I have added FbGraphAPI from here https://github.com/reallylongaddress/iPhone-Facebook-Graph-API
Thanks


text:
Q: Can't access my website using IP/~account, showing not supported I can't access my temporary URL, it just shows "Not Supported". I uploaded laravel files. i've configured the index.php and .envshowing not supported

A: *

*If your web root is the syksxyz directory then the public path will be syksxyz/public

*To make sure its working you can add an index.html file in the public folder to see whether the mapping is correct before debugging the php part of it.

A: Depending on what web server you are using, Apache or Nginx, you can follow official document to configure your web server. Web Server Configuration
To use laravel, you must configure your server properly. Just uploading code to server will not make your website work as expect. The must important part of configuration is directing all requests to the index.php.
And here is part of my config file of Nginx.
server {
    listen 80;
    server_name my-website.test;
    root "/path/to/my-laravel-project/public";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;

    }

    location ~ /\.ht {
        deny all;
    }
}

Remember that website root should point to ./laravel-project/public directory, because laravel-project/public/index.php file will handle all request for your website.


text:
Q: Why is this code printing a bunch of empty lists and then an IndexError? I am iterating through a list (it may look unorganized, but there is a  reason) that is organized by: Dish name, # of ingredients, owner, ingredient 1, Description of ingredient 1, ingredient 2, description of ingredient 2, ingredient 3... etc. Each dish might have a different amount of ingredients, but that number of ingredients is always on the index after the dish name. Below is the list called book:
['pbj', 3, 'Alex', 'peanutbutter', 'Nice and Creamy', 'jelly',
'Make sure it is refridgerated', 'bread', 'Whole wheat', 'Spaghetti',
2, 'Ryan', 'noodles', 'Spaghetti shaped', 'tomato sauce', 'Smooth, not chunky',
'Grilled Cheese', 2, 'Jason', 'Cheese', 'Any kind of cheese', 'bread',
'Any kind of bread']

I am getting an output of a couple lists and then an IndexError.
I have tried walking through step by step on what is happening in the process and I still do not understand the problem.
numDish = 3

m = 0
for i in range (numDish): # for each unique dish
    k = m + 3
    print(book[m: k]) #prints dish, # of ingredients, and owner

    for j in range(int(book[m + 1])): #run for each ingredient per dish
        print(book[k: k + 2]) #print ingredient and associated description
        k += 2
    print ('\n')
    m = k + 1 #Set m to the value after the last description

I want and expect the results to be printed as:
'pbj', 3, 'Alex'
'peanutbutter', 'Nice and Creamy',
'jelly', 'Make sure it is refridgerated',
'bread', 'Whole wheat',

'Spaghetti', 2, 'Ryan',
'noodles', 'Spaghetti shaped',
'tomato sauce', 'Smooth, not chunky',

'Grilled Cheese', 2, 'Jason',
'Cheese', 'Any kind of cheese',
'bread', 'Any kind of bread'

(Im not sure if it will have quotes or not but that doesn't matter to me.)
instead I get this:
['pbj', 3, 'Alex']
['peanutbutter', 'Nice and Creamy']
['jelly', 'Make sure it is refridgerated']
['bread', 'Whole wheat']
[2, 'Ryan', 'noodles']

Traceback (most recent call last):
File "", line 1, in
   runfile('C:/Users/CSANCH08/Desktop/untitled2.py', wdir='C:/Users/CSANCH08/Desktop')
File "C:\ProgramData\Anaconda3\lib\site- packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site- packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/CSANCH08/Desktop/untitled2.py", line 22, in
  for j in range(int(book[m + 1])): #run for each ingredient per dish
ValueError: invalid literal for int() with base 10: 'Ryan'

A: book = ['pbj', 3, 'Alex', 'peanutbutter', 'Nice and Creamy', 'jelly', 'Make sure >it is refridgerated', 'bread', 'Whole wheat', 'Spaghetti', 2, 'Ryan', 'noodles', 'Spaghetti shaped', 'tomato sauce', 'Smooth, not >chunky', 'Grilled Cheese', 2, 'Jason', 'Cheese', 'Any kind of >cheese', 'bread', 'Any kind of bread']
numDish = 3

m = 0
for i in range (numDish): # for each unique dish
    k = m + 3
    print(book[m: k]) #prints dish, # of ingredients, and owner

    for j in range(int(book[m + 1])): #run for each ingredient per dish
        print(book[k: k + 2]) #print ingredient and associated description
        k += 2
    print ('\n')
    m = k

in the last line change m=k+1 to m= k.


text:
Q: Mathematics formula expression of finding cliques I am actually trying to write a math expression of finding a clique with size x. I can tell it in English, but somehow it is hard for me to translate it into a math expression.
In a graph, G = (V(G), E(G)). If we need to find a clique with size x means to check if there exists x vertices, $V_1, V_2, ..., V_x$, such that .....
and then I do not know how to write a math expression to tell such that every node in $\{V_1, V_2, ..., V_x\}$ must have a link to every other node in $\{V_1, V_2, ..., V_x\}$ and all links must also belong to E(G).

A: If $E(G)$ is the set of unordered pairs $\{V_a,V_b\}$ of vertices $V_a,V_b\in V(G)$ that are connected by an edge, then you could finish your sentence as follows:

... such that $\{V_i,V_j\}\in E(G)$ for all $i,j\in\{1,\ldots,x\}$ with $i\neq j$.

You might also want to emphasize that the vertices $V_1$, ..., $V_x$ should be distinct. You could also check

... if there exists $C\subset V(G)$ with $|C|=x$ and $\{a,b\}\in E(G)$ for all distinct $a,b\in C$.


text:
Q: How to show all comments in foreach with article title within Laravel 5 Eloquent I am following a tutorial Articles and comments.
Below works fine, but how do i get all comments with the articlename in a foreach?
Model: Article
namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
public function comments() {
    return $this->hasMany('App\Http\Models\Comment');
}
protected $fillable = array('title','body');
}

Model: Comments
namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
public function article() {
    return $this->belongs('Article');
}
protected $fillable = array('body','article_id');

}

Example dump in ArticleController:
$items = Article::find(1)->comments()->get();
foreach ($items as $item) {
    print_r($item->body);
}

A: From the documentation on querying relations
$article = Article::find(1);

echo $article->name;

foreach ($article->comments as $comment) {
    //
}

A: In the CommentController i dumped for example:
foreach ( $comments as $comment) {
    echo $comment->body.' - '.$comment->article->title.'<br>';
}


text:
Q: Find the number of functions which satisfy given conditions If f :{1,2,3,4} → {1,2,3,4} and y = f(x) be a function defined such that |f(α) – α| ≤ 1, for α ∈ {1,2,3,4} and m be the number of such functions, then m/5 is equal

A: If we think a function as a permutation of $(1,2,3,4)$, the only functions that satisfy the condition are

$$(1,2,3,4,5),\quad(1,2,4,3)\quad(1,3,2,4)\quad(2,1,3,4)\quad(2,1,4,3)$$

Thus, $m=5$ and $m/5=1$.

A: Okay.
$|f(a) - a| \le 1$ so $-1 \le f(a)-a < 1$ so $a-1 \le f(a) \le a+1$.
so $f(a)4$ may be one of three values $f(a)$ could be $a-1$ if $a-1$ is in range; that is if $a-1\ge 1$ or $a \ge 2$.
Or $f(a)$ could be $a$.
Or $f(a)$ could be $a+1$ if $a+1$ is in range; that is if $a+1 \le 4$ of $a \le 3$.
So
For $a = 1$ there are $2$ things $f(1)$ could be.  $f(1)=1$ is a possibility and $f(1) =2$ are a possiblity.
Of $ a= 2,3$ there are three things $f(a)$ could be.  $a-1, a, a+1$ are the three possibilities.
And for $ a=4$ there are $2$ things for $f(4)$ to be.
So there there are $2$ things $f(1)$ can be and $3$ things $f(2)$ can be and $3$ things $f(3)$ can be and $2$ things $f(4)$ can be.
So how many combinations of ways can $(f(1),f(2),f(3),f(4))$ can be?

 $2\times 3\times 3 \times 2= 36$ possible combinations of value so $f(1),f(2),f(3),f(4)$ so $36$ possible functions.

Um..... why does anyone care what $\frac m5$ is?


text:
Q: Replace multiple values over multiple columns of a data frame in R I am trying to replace certain numbers with others over multiple columns of a data set.
1=1
2=1
3=2
4=3
5=3

So if I have:

id      age        A1       weight     Var1       A2

3       5          2         50         1         4
7       23         1         67         5         3
9       78         4         90         3         2
12      14         1         17         2         3

I want to replace those numbers in columns A1, Var1, and A2

id      age        A1       weight     Var1       A2

3       5          1         50         1         3
7       23         1         67         3         2
9       78         3         90         2         1
12      14         1         17         1         2

I think I can do something with mutate_across but I'm not sure

A: df1 %>%
   mutate(across(c(A1, Var1, A2), recode, "1" = 1,
                 "2" = 1, `3` = 2, `4` = 3, `5` = 3))

  id age A1 weight Var1 A2
1  3   5  1     50    1  3
2  7  23  1     67    3  2
3  9  78  3     90    2  1
4 12  14  1     17    1  2


text:
Q: Highcharts rangeselector navigation - start on the lowest date / value On this official Highcharts demo https://www.highcharts.com/demo/gantt/with-navigation
the display starts at the end

What do I need to change, so the navigation range starts at the beginning like so?

A: You can use setExtremes method in load event:
    chart: {
        events: {
            load: function() {
                const xAxis = this.xAxis[0];
                xAxis.setExtremes(xAxis.dataMin, xAxis.dataMin + xAxis.max - xAxis.min);
            }
        }
    }

Live demo: https://jsfiddle.net/BlackLabel/8tk52zdw/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes


text:
Q: Calling check internet connectivity class when clicking a button from another activity What i have is an android application , i have an activity which check if internet connectivity exist or not and here it is :
public class MainActivity extends Activity {

    private static final String LOG_TAG = "CheckNetworkStatus";
     private NetworkChangeReceiver receiver;
     private boolean isConnected = false;
     private TextView networkStatus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
          receiver = new NetworkChangeReceiver();
          registerReceiver(receiver, filter);

          networkStatus = (TextView) findViewById(R.id.networkStatus);
         }

         @Override
         protected void onDestroy() {
          Log.v(LOG_TAG, "onDestory");
          super.onDestroy();

          unregisterReceiver(receiver);

         }

         public class NetworkChangeReceiver extends BroadcastReceiver {

          @Override
          public void onReceive(final Context context, final Intent intent) {

           Log.v(LOG_TAG, "Receieved notification about network status");
           isNetworkAvailable(context);

          }

          private boolean isNetworkAvailable(Context context) {
           ConnectivityManager connectivity = (ConnectivityManager)
             context.getSystemService(Context.CONNECTIVITY_SERVICE);
           if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
             for (int i = 0; i < info.length; i++) {
              if (info[i].getState() == NetworkInfo.State.CONNECTED) {
               if(!isConnected){
                Log.v(LOG_TAG, "Now you are connected to Internet!");
                networkStatus.setText("Now you are connected to Internet!");
                isConnected = true;
                //do your processing here ---
                //if you need to post any data to the server or get status
                //update from the server
               }
               return true;
              }
             }
            }
           }
           Log.v(LOG_TAG, "You are not connected to Internet!");
           networkStatus.setText("You are not connected to Internet!");
           isConnected = false;
           return false;
          }
         }

        }

And i have another Activity which has a button , and i want when i click the button to check if internet connectivity exist it will make a toast in this activity without opening the internet activity , here is my button :
  Submit.setOnClickListener(new OnClickListener() {

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

            }
        });

How can i make the other Activity work start on a click without make it visible on the application?
Am new At android .. please help :(

A: You need to create separate class for checking internet connection and you can access that class from any other class by calling it through its object here is the example.
save below code with ConnectionDetector.java
package com.yourpackagename;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}

in activity where you want to use to check connectivity use below code
first create object of above ConnectionDetector class
ConnectionDetector cd;

then intialise it by
cd = new ConnectionDetector(this);

then use below code anywhere you want in that activity like on button click event.
if (!cd.isConnectingToInternet()) {
    //no internet present
} else {
    //internet present
}

A: See this Git Will help for you.
https://github.com/shabbir-dhangot/Checking-Internet-connection
Try This Git Created By me.


text:
Q: Scroll Fade using Javascript - auto-scrolls to the end of section too fast I'm working on a fullpage.js with three sections.
I've set the scrollOverflow to true because the content of the third section is a bit long. First element on the third section must fade out as the user scrolls down, and the second element must fade in before the first element fades out.
Still working on the fading out part but I'm having issues because it auto-scrolls down too fast.
Not sure if I have problems in the javascript code alone (I'm a total beginner) or it's having problem with the fullpage.js.

index.html

Header

                Eu nec ferri molestie consequat, vel at alia dolore putant. Labore philosophia ut vix. In vis nostrud interesset appellantur, vis et tation feugiat scripserit. Te nec noster suavitate persecuti. Diceret erroribus cu vix, alii omnes ei sit. Sea an corrumpit patrioque, virtute accumsan nominavi et usu, ex mei dolore vocibus incorrupte.

                Duo ea saperet tacimates. Sed possim prodesset no, per novum putent doctus ea. Eu mea magna aliquip graecis, pri corpora officiis complectitur ei, lorem saepe consetetur his ad. Meis consulatu ei vis, an altera ocurreret interesset qui.

                Eu ponderum comprehensam his, case antiopam pri te. Mel ne partem consequat instructior. Ad dicunt malorum sea, ex qui omnes invenire gubergren. Ius cu autem aliquando, pri vide ornatus perpetua an, no has epicuri verterem. Nam at animal pertinax efficiantur.

                Per alienum torquatos eu. Sed saepe quodsi et, ullum choro definitionem sed et. Ullum elitr comprehensam sed at, sint illum propriae per eu. Eu enim laudem reformidans vel. Pro clita quando ad. Usu te virtute quaestio, ut eruditi tacimates volutpat per.

                Affert accusamus duo ex, ea pri habeo graece, cu magna dolorum sea. Quas dictas assueverit ad qui, cu duo harum fabulas apeirian, ullum gubergren et sit. Ne cetero recusabo adipiscing quo, cu harum quaestio neglegentur cum. Has tation aliquip ad, virtute volumus definitionem mel ne. Nobis audiam civibus ius at.

                Ei eum hinc mutat inciderint. Cu maluisset assentior per, graecis ponderum no mel. Eum eu vitae quando gloriatur, cum graece percipitur no, sed errem maiestatis te. Sed porro epicuri te, ad nam malorum verterem. Ea zril aliquip euismod sed.

                Eu ponderum comprehensam his, case antiopam pri te. Mel ne partem consequat instructior. Ad dicunt malorum sea, ex qui omnes invenire gubergren. Ius cu autem aliquando, pri vide ornatus perpetua an, no has epicuri verterem. Nam at animal pertinax efficiantur.

                Per alienum torquatos eu. Sed saepe quodsi et, ullum choro definitionem sed et. Ullum elitr comprehensam sed at, sint illum propriae per eu. Eu enim laudem reformidans vel. Pro clita quando ad. Usu te virtute quaestio, ut eruditi tacimates volutpat per.

                Affert accusamus duo ex, ea pri habeo graece, cu magna dolorum sea. Quas dictas assueverit ad qui, cu duo harum fabulas apeirian, ullum gubergren et sit. Ne cetero recusabo adipiscing quo, cu harum quaestio neglegentur cum. Has tation aliquip ad, virtute volumus definitionem mel ne. Nobis audiam civibus ius at.

                Ei eum hinc mutat inciderint. Cu maluisset assentior per, graecis ponderum no mel. Eum eu vitae quando gloriatur, cum graece percipitur no, sed errem maiestatis te. Sed porro epicuri te, ad nam malorum verterem. Ea zril aliquip euismod sed.

Fade Me Away

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse odio velit, condimentum vel pulvinar sed, mollis at tortor. Nam congue turpis mi, in ultricies dolor mattis non. Donec molestie ante arcu, eget congue quam tincidunt in. Nullam et dignissim felis. Proin iaculis lectus eget dui tincidunt, laoreet pharetra diam varius. Aliquam ullamcorper volutpat gravida. Sed pharetra ac risus a tristique. Vestibulum et blandit orci, non sollicitudin nunc. Sed ut nulla massa. Fusce nec erat eu neque egestas maximus. Proin sit amet ultrices elit, vitae tempor felis. Vivamus egestas efficitur metus, in elementum odio aliquet et. Vestibulum semper eros orci, non accumsan turpis convallis sit amet. Donec rutrum efficitur velit quis auctor.

Lorem ipsum

Lorem ipsum dolor sit amet

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum

Lorem ipsum dolor sit amet

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

                    Eu nec ferri molestie consequat, vel at alia dolore putant. Labore philosophia ut vix. In vis nostrud interesset appellantur, vis et tation feugiat scripserit. Te nec noster suavitate persecuti. Diceret erroribus cu vix, alii omnes ei sit. Sea an corrumpit patrioque, virtute accumsan nominavi et usu, ex mei dolore vocibus incorrupte.Duo ea saperet tacimates. Sed possim prodesset no, per novum putent doctus ea. Eu mea magna aliquip graecis, pri corpora officiis complectitur ei, lorem saepe consetetur his ad. Meis consulatu ei vis, an altera ocurreret interesset qui.

                    Eu ponderum comprehensam his, case antiopam pri te. Mel ne partem consequat instructior. Ad dicunt malorum sea, ex qui omnes invenire gubergren. Ius cu autem aliquando, pri vide ornatus perpetua an, no has epicuri verterem. Nam at animal pertinax efficiantur.

                    Per alienum torquatos eu. Sed saepe quodsi et, ullum choro definitionem sed et. Ullum elitr comprehensam sed at, sint illum propriae per eu. Eu enim laudem reformidans vel. Pro clita quando ad. Usu te virtute quaestio, ut eruditi tacimates volutpat per.

                    Affert accusamus duo ex, ea pri habeo graece, cu magna dolorum sea. Quas dictas assueverit ad qui, cu duo harum fabulas apeirian, ullum gubergren et sit. Ne cetero recusabo adipiscing quo, cu harum quaestio neglegentur cum. Has tation aliquip ad, virtute volumus definitionem mel ne. Nobis audiam civibus ius at.

                    Ei eum hinc mutat inciderint. Cu maluisset assentior per, graecis ponderum no mel. Eum eu vitae quando gloriatur, cum graece percipitur no, sed errem maiestatis te. Sed porro epicuri te, ad nam malorum verterem. Ea zril aliquip euismod sed.

                    Eu nec ferri molestie consequat, vel at alia dolore putant. Labore philosophia ut vix. In vis nostrud interesset appellantur, vis et tation feugiat scripserit. Te nec noster suavitate persecuti. Diceret erroribus cu vix, alii omnes ei sit. Sea an corrumpit patrioque, virtute accumsan nominavi et usu, ex mei dolore vocibus incorrupte. Duo ea saperet tacimates. Sed possim prodesset no, per novum putent doctus ea. Eu mea magna aliquip graecis, pri corpora officiis complectitur ei, lorem saepe consetetur his ad. Meis consulatu ei vis, an altera ocurreret interesset qui.

                    Eu ponderum comprehensam his, case antiopam pri te. Mel ne partem consequat instructior. Ad dicunt malorum sea, ex qui omnes invenire gubergren. Ius cu autem aliquando, pri vide ornatus perpetua an, no has epicuri verterem. Nam at animal pertinax efficiantur.

                    Per alienum torquatos eu. Sed saepe quodsi et, ullum choro definitionem sed et. Ullum elitr comprehensam sed at, sint illum propriae per eu. Eu enim laudem reformidans vel. Pro clita quando ad. Usu te virtute quaestio, ut eruditi tacimates volutpat per.

                    Affert accusamus duo ex, ea pri habeo graece, cu magna dolorum sea. Quas dictas assueverit ad qui, cu duo harum fabulas apeirian, ullum gubergren et sit. Ne cetero recusabo adipiscing quo, cu harum quaestio neglegentur cum. Has tation aliquip ad, virtute volumus definitionem mel ne. Nobis audiam civibus ius at.

                    Ei eum hinc mutat inciderint. Cu maluisset assentior per, graecis ponderum no mel. Eum eu vitae quando gloriatur, cum graece percipitur no, sed errem maiestatis te. Sed porro epicuri te, ad nam malorum verterem. Ea zril aliquip euismod sed.

                    Eu nec ferri molestie consequat, vel at alia dolore putant. Labore philosophia ut vix. In vis nostrud interesset appellantur, vis et tation feugiat scripserit. Te nec noster suavitate persecuti. Diceret erroribus cu vix, alii omnes ei sit. Sea an corrumpit patrioque, virtute accumsan nominavi et usu, ex mei dolore vocibus incorrupte. Duo ea saperet tacimates. Sed possim prodesset no, per novum putent doctus ea. Eu mea magna aliquip graecis, pri corpora officiis complectitur ei, lorem saepe consetetur his ad. Meis consulatu ei vis, an altera ocurreret interesset qui.

                    Eu ponderum comprehensam his, case antiopam pri te. Mel ne partem consequat instructior. Ad dicunt malorum sea, ex qui omnes invenire gubergren. Ius cu autem aliquando, pri vide ornatus perpetua an, no has epicuri verterem. Nam at animal pertinax efficiantur.

                    Per alienum torquatos eu. Sed saepe quodsi et, ullum choro definitionem sed et. Ullum elitr comprehensam sed at, sint illum propriae per eu. Eu enim laudem reformidans vel. Pro clita quando ad. Usu te virtute quaestio, ut eruditi tacimates volutpat per.

                    Affert accusamus duo ex, ea pri habeo graece, cu magna dolorum sea. Quas dictas assueverit ad qui, cu duo harum fabulas apeirian, ullum gubergren et sit. Ne cetero recusabo adipiscing quo, cu harum quaestio neglegentur cum. Has tation aliquip ad, virtute volumus definitionem mel ne. Nobis audiam civibus ius at.

                    Ei eum hinc mutat inciderint. Cu maluisset assentior per, graecis ponderum no mel. Eum eu vitae quando gloriatur, cum graece percipitur no, sed errem maiestatis te. Sed porro epicuri te, ad nam malorum verterem. Ea zril aliquip euismod sed.

js

$(document).ready(function() {
                $('#fullpage').fullpage({
                    /*  anchors: ['firstPage', 'secondPage', '3rdPage'],  */
                    lockAnchors: true,
                    sectionsColor: ['#C63D0F', '#1BBC9B', '#7E8F7C'],
                    css3: true,
                    navigation: true,
                    navigationPosition: 'right',
                    fadingEffect: true,
                    scrollOverflow: true
                });
                $(function() {
                    var documentEl = $(document),
                        fadeElem = $('.fade-scroll');
                        documentEl.on('scroll', function() {
                        var currScrollPos = documentEl.scrollTop();
                        fadeElem.each(function() {
                            var $this = $(this),
                                elemOffsetTop = $this.offset().top;
                            if (currScrollPos > elemOffsetTop) $this.css('opacity', 1 - (currScrollPos-elemOffsetTop)/400);
                        });
                    });
                });

            });

style

/* Centered texts in each section
* --------------------------------------- */
.section{
    text-align:center;
}

/* Fixed header and footer.
* --------------------------------------- */
#header {
    position:sticky;
    height: 50px;
    display:block;
    width: 100%;
    background: #333;
    z-index:9;
    text-align:center;
    color: #f2f2f2;
    padding: 20px 0 0 0;
    top:0px;
}

* {
    margin: 0;
    padding: 0;
}
h1 {
    font-weight: 300;
    font-size: 4em;
    color: #fff;
    background-color: #071d36;
    padding: 300px 0 50px 100px;
    margin-bottom: 150px;
}
p {
    width: 30%;
    margin: 0 auto 500px auto;
    font-size: 1.4em;
    color: #555;
    font-weight: 300;
}

A: FullPage.js  won't let you to attach an event listener to the scroll unless you have the parameter autoScrolling in false.
A way could be, set in your options :
afterLoad: function(anchorLink, index){
   if(index === 3{ //When you are scrolling in the third section disable autoscrolling
      $.fn.fullpage.setAutoScrolling(false);
   }else{ //enable when you are scrolling in the other sections
      $.fn.fullpage.setAutoScrolling(true);
   }
},


text:
Q: Material Ui, MUI, Dialog, ScrollTop I was messing around alot with scrollTop and the Dialog component(A fullscreen fixed modal) from Material-Ui for some time... and I couldn't quite get scrollTop to work. When i click the go down button, It would always give me undefined or it wouldn't work at all in the scrollable container.

A: All that was needed was needed
Make sure the div within the Dialog has overflow
<Dialog fullScreen open={open} onClose={handleClose}>
        <div ref={ref}
//MOST IMPORTANT
 style={{ backgroundColor: 'red', overflowY: 'auto', height: '100%' }}>

**And an onClick **
<Button
autoFocus
color="inherit"
//HERE
onClick={() => {
const div = ref.current;
div.scrollTop = 800;
}}
>GO DOWN
</Button>

Here's an example
https://codesandbox.io/s/fullscreendialog-material-demo-forked-cf8u6?file=/demo.js:2201-2434