text:
Q: Use oauth2 to retrieve Google Places client_id Is it possible to retrieve the Google Places client_id using oauth2? I am able to retrieve Google+ information including the id and Google+ profile url, but I need a way to tie the oauth2 user to the Google Places "client_id".
I have been able to include the Places scope which is listed in the oauth2 popup and asks the user for permission to access the resources, but cannot figure out how to retrieve the authenticated user's client_id.
Scopes:
var scopes = 'https://www.googleapis.com/auth/plus.me https://maps.google.com/maps/feeds/ https://www.googleapis.com/auth/places';

Google+ API Load
Although I can successfully retrieve plus data, the places api does not seem to expose any data. Here is what I have tried:
function makeApiCall() {
    /* the plus api does retrieve data, but a similar call to places does not
    gapi.client.load('plus', 'v1', function () {
        var request = gapi.client.plus.people.get({
            'userId': 'me'
        });
        request.execute(function (resp) {
            $(".google-signin").find("img").attr('src', resp.image.url).css('height', '32').css('width', '32');
            $("#login-msg").text('Welcome: ' + resp.displayName);
            $("img.vote").css('visibility', 'visible');
        });
    });
    */
    gapi.client.load('places', 'v1', function () {
        debugger
        // the gapi.client does not contain a "places" object
        var request = gapi.client.places.get({
            'userId': 'me'
        });
        request.execute(function (resp) {
            debugger
        });
    });
}

Any clarity on this issue is appreciated.
CLARIFICATION EDIT
Perhaps I did not make myself clear. The Google Places API encourages the creation of Events, which are associated with specific Places (of business). We are generating lists based on Google Places API search and details responses (prototype at top-60.bunkerhill.com follow one or more links)  We would like businesses to be able to add Events to their associated listing, but cannot allow this without first somehow associating the Places Detail response data with a Google Sign-On; or am I missing something important here?
So the question is "Can a user sign-in to any available Google OAuth API that provides some data which can be used to associate the user with a Places Details entry?

A: The Google Places API is not the same as the G+ API.
Check out https://developers.google.com/places/documentation/ for instructions on accessing Places data (note that you do not use OAuth for this API - you just include the key from developers.google.com/console in your http request).

A: Regarding the clarified question: No, the Places API authentication and authorization for creating Events is only via the developer (and your API key), and never the end user who may interact with your application.
For this specific example, you (the developer) can create Events that are associated with a Place, but it would be incumbent on you to make a further association of which end user you wanted to associate with the creation of that Event, and store that metadata within your application if you cared to do so.
Is there a reason having the Places API itself understand this relationship that would be a benefit to your application?


text:
Q: Could not find template file flash/hxml when installing haxe lime I recently tried to develop in haxe/lime and I have two things that freaked me out.
1. I tried to install Lime by this command:
> haxelib install lime
haxelib run lime setup

and it automatically installed Lime in "c:/" and I need to move the files to "lib" to haxe folder.
2.when i open Lime project in FD i get this error:
> Called from ? line 1
Called from CommandLineTools.hx line 995
Called from CommandLineTools.hx line 23
Called from CommandLineTools.hx line 108
Called from CommandLineTools.hx line 190
Called from platforms/FlashPlatform.hx line 91
Called from /usr/lib/haxe/std/neko/_std/sys/io/File.hx line 30
Uncaught exception - Invalid field access : __s

end when i try to build the project i get this error:
> Warning: Could not find template file: flash/hxml
Warning: Could not find template file: flash/haxe
Fatal error: exception Failure("File not found bin/flash/haxe/release.hxml")
Build halted with errors (haxelib.exe).

A: for your first problem, it's looks like you don't configure haxelib path.
You can set up the path for your libraries with :
haxelib setup
Here yo put the path where you wants your lib to be store.
And don't forget after you install lime to do :
haxelib run lime setup like it's asked.
For your problem with FD I suppose that's can come with the fact you moved your lime folder to another folder. Generally you never have to move a lib to another folder or haxe will not know is location.
If it's not sorry, I don't use FD but hide or sublime text.

A: The accepted answer did not make sense to me so I decided to post a solution that worked on my system. It's worth noting that I'm on Ubuntu 14.04, not Windows. I could install neither lime nor openfl. I decided to include openfl details here as I could not find a solution for that either. The openfl error I received was Uncaught exception - Invalid field access: split.
Many forums recommend checking that the HAXEPATH environment variable is not set. In my case, it wasn't set, but I received a similar lime error to the one posted here. Contrary to what those forums advised, manually exporting the HAXEPATH variable allowed me to run both lime and openfl setups successfully.
One site also mentioned that the format lib is necessary, although I'm not sure how true this is. Please leave a comment if you can confirm or deny this.
Here's what I did:
Install openfl, lime, and format
haxelib install openfl
haxelib install lime
haxelib install format
Get the haxelib path, and export it
Running haxelib config will return the haxelib repository path as is currently defined. If you have not defined a haxelib repo path, you can do so by running haxelib setup. On my system the path was /usr/share/haxe/lib.
Export the haxelib path:
export HAXEPATH="`haxelib config`"
Complete the setup
haxelib run lime setup
haxelib run openfl setup
Confirm all is working
Run lime or openfl. You should receive a terminal splash welcome from both.
I added the above export entry to my bashrc file as these tools always require that the variable exists in my environment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: gmake environment variables missing I am writing a Makefile and need to access the HOSTNAME environment variable.
None of the environment variables are available.  Here's the Makefile:
all:
    echo $(HOSTNAME) "b"

The output is:
echo  "b"
b

I am running on ubuntu 14.04 in a VM.  gmake version:
make -v
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for x86_64-pc-linux-gnu

And yes, the HOSTNAME environment variable is set:
/tmp$ echo $HOSTNAME
ubuntu
/tmp$

This Makefile works in cygwin.
Do you know why this is not working?

A: HOSTNAME is set by Bash, but when Make runs a shell, it calls sh; even if this is a symlink to Bash on your system, it runs in POSIX mode, which disables many Bash-specific behaviors.
Workaround 0; always call make with Bash with HOSTNAME exported.
alias make='export HOSTNAME; make'

Workaround 1; use Bash instead of sh explicitly.
SHELL=/bin/bash
HOSTNAME=$(shell echo "$$HOSTNAME")

Workaround 2; call Bash explicitly.
HOSTNAME=$(shell bash -c 'echo $$HOSTNAME')

Workaround 3; run an external command.
HOSTNAME=$(shell uname -n)

Out of these, the last one is probably the least obscure as well as the most efficient.


text:
Q: Salesforce Commerce cloud B2C Import catalog issue I am facing issue while importing product csv sheet through catalog import in merchant tools
Products are being added but with only few field
ISSUE:
WARN Import CSV File validation warning. Attribute ID 'Description' does not exist. Skipping column.
File validation warning. Attribute ID 'name' is missing site or locale suffix. Skipping column.
So are the product attribute names not correct or missing a essential attribute?
And are there other ways to import catalog in salesforce ecommerce cloud using tool or url..please let me know.
Thank you!!


text:
Q: .net core 3 web api controller - code execution after sending response I have a .net core 3.1 webapi project. In some controllers, I need to execute some code that doesn't impact the response to the client.
In particular, I have a method that returns a json with a profile's information, which is called when user visits that profile's page. After get profile's information, I need to log that a user visits this page, but, for a faster response, I want to return response before this log operation.
[Route("[controller]")]
[ApiController]
public class ProfilesController : ControllerBase
    {
        [HttpGet("{id}")]
        public async Task<ActionResult<Profile>> GetProfileById([FromRoute] int id)
        {
             Profile profile = await _profileService.GetByIDAsync(id);

             // DO THIS OPERATION IN BACKGROUND AND DON'T WAIT TO RETURN RESPONSE
              await _logService.LogProfileVisit(id);

             return Ok(profile);
        }
}

How can I do it?
Thanks.

A: Remove await keyword before _logService.LogProfileVisit(id);
This will prevent you from waiting for response
[Route("[controller]")]
[ApiController]
public class ProfilesController : ControllerBase
{
    [HttpGet("{id}")]
    public async Task<ActionResult<Profile>> GetProfileById([FromRoute] int id)
    {
        _logService.LogProfileVisit(id);
        Profile profile = await _profileService.GetByIDAsync(id);
        return Ok(profile);
    }
}

A: You can do this with filter for example. Read here

A: You can use many approach but there is no single line solution for that. You can use background workers to achive that. "Bakcground service with hosted Service in .NET Core" may suit your needs. You can also use a library like Hangfire for easily configurable complicated solutions.

A: You can use HangFire or Quartz Scheduler to run task in background without waiting response.
Example using HangFire :
var jobId = BackgroundJob.Enqueue(
    () => _logService.LogProfileVisit(id));

A: There are 2 possible solutions:

*

*Use a framework such as HangFire or Quartz Scheduler that brings this functionality. This might make sense if you'll be needing to use this feature in more than a few places. Otherwise, they're rather heavy.

*Use Task.Run() in conjuction with ScopeFactory.

For the second option, the basic code would look like this:
[HttpGet("{id}")]
public async Task<ActionResult<Profile>> GetProfileById([FromRoute] int id)
{
     Profile profile = await _profileService.GetByIDAsync(id);

     Task.Run(async () =>
     {
         await _logService.LogProfileVisit(id);
     }

     return Ok(profile);
}

This will crash. As soon as the controller returns it will dispose of all the services, including _logService' leading to an error.
The solution is to use IServiceScopeFactory to create a scoped service that will be disposed when the task ends:
[HttpGet("{id}")]
public async Task<ActionResult<Profile>> GetProfileById([FromRoute] int id)
{
     Profile profile = await _profileService.GetByIDAsync(id);

     Task.Run(async () =>
     {
         using var scope = _serviceScopeFactory.CreateScope();
         var _logService = scope.ServiceProvider.GetService<LogService>();
         await _logService.LogProfileVisit(id);
     }

     return Ok(profile);
}

For a complete example of this implementation see this post.


text:
Q: Singleton script to download images from web download and Malformed URL issue Hi I have written a singleton script called DownloadImage which can be used by any class to download images from web. There is a scene with several images with an attached script WebImage. Webimage internally calls this DownloadImage Singleton to download the image and update its image.
Webimage has url field in which we can pass in the image link.
This system works fine if url is fixed. However if if I change url for ecah image component in scene images are not downloaded properly or I get error saying Malfoemed url. What might be the issue here and how to solve this?
Below is singleton Download script, and this script is attached to empty gameobject component.
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using UnityEngine.UI;

public class DownloadImage : MonoBehaviour
{
    public static DownloadImage instance;

    [SerializeField] public string url;
    [SerializeField] public Texture2D texture;
    [SerializeField] public bool isCached;

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(this.gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(this.gameObject);
    }

    void Start()
    {
        StartCoroutine(GetImageFromWeb(url));
    }

    public IEnumerator GetImageFromWeb(string refURL)
    {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(refURL);
        yield return request.SendWebRequest();

        if (request.isNetworkError || request.isHttpError ||
            File.Exists(Application.persistentDataPath + "Image.jpg"))
        {
            Debug.Log("-------------------------"  + request.error);

            byte[] byteArray = File.ReadAllBytes(Application.persistentDataPath + "Image.jpg");
            Texture2D tempText = new Texture2D(60, 90);
            tempText.LoadImage(byteArray);
            texture = tempText;
        }

        else
        {
            texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
            if (isCached)
            {
                SaveDownloadedTexture(texture);
            }
        }

    }

    public void SaveDownloadedTexture(Texture2D refTexture)
    {
        bool clearCache;
        byte[] byteArr = refTexture.EncodeToJPG();
        File.WriteAllBytes(Application.persistentDataPath + "Image.jpg", byteArr);
        clearCache = Caching.ClearCache();
        if (clearCache)
        {
            Debug.Log("Image deleted");
        }
    }
}

Below is script WebImage script which is attache on each of image component in scene that takes url and passes it to singleton.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class WebImage : MonoBehaviour
{
    [SerializeField] public string imageURL;
    [SerializeField] public bool cacheData;

    void Start()
    {
        this.gameObject.AddComponent<RawImage>();
        DownloadImage.instance.url = imageURL;
        DownloadImage.instance.isCached = cacheData;
    }

    void Update()
    {
        this.gameObject.GetComponent<RawImage>().texture = DownloadImage.instance.texture;
    }

}

A: Besides the comments I made already timing can be a huge issue here!
You are starting the download right away in DownloadImage.Start.
But there is no guarantee that your WebImage.Start is actually executed before that => maybe the URL is even simply "".
Also check your local file path! By simply using + what you get is a path like e.g.
some/local/filePathImage.jpg

what you want would rather be
some/local/filePath/Image.jpg

So for system paths always use Path.Combine which inserts the correct path separator depending on the OS the app is running on.
And then you probably would also not want to again and again overwrite the very same local file Image.jpg but rather have unique names (for now I will assume based on the last part of the Url)
As said I would simply rather merge these to together into a single component and do something like
public class LoadedImage : MonoBehaviour
{
    [SerializeField] private Image image;
    [SerializeField] private string url;
    [SerializeField] private bool isCached;

    // Your path was also invalid!
    // by simply using + you end up with a path like e.g.
    //     some/local/filePathImage.jpg
    // what you rather want is
    //     some/local/filePath/Image.jpg
    // And then still - if you have multiple instancesthey will all overwrite the same local file
    // I would simply use the url again
    private string localPath = Path.Combine(Application.persistentDataPath, url.Split('/').Last());

    // Unity will automatically run this as a Coroutine
    private IEnumerator Start()
    {
        Texture2D texture;

        // First of all why is the local file an error?
        // I would rather expect it to be the default case and only trigger a download
        // if it DOESN'T exist

        // So as first option go for local cached file
        if(File.Exists(localPath))
        {
            byte[] byteArray = File.ReadAllBytes(localPath);
            texture = new Texture2D(1,1);
            texture.LoadImage(byteArray);
        }
        // as fallback download
        else
        {
            using(var request = UnityWebRequestTexture.GetTexture(refURL))
            {
                yield return request.SendWebRequest();

                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.LogError("-------------------------"  + request.error);
                    return;
                }

                texture = ((DownloadHandlerTexture)request.downloadHandler).texture;

                if (isCached)
                {
                    SaveDownloadedTexture(texture);
                }
            }
        }

        if(texture != null)
        {
            // Finally use Image which is way more performant than RawImage which adds DrawCalls to your UI
            image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
        }
    }

    public void SaveDownloadedTexture(Texture2D refTexture)
    {
        var byteArr = refTexture.EncodeToJPG();
        File.WriteAllBytes(localPath, byteArr);
        var clearCache = Caching.ClearCache();
        if (clearCache)
        {
            Debug.Log("Image deleted");
        }
    }
}

There is no need for a singleton. Just have this attached to your image components, configure them and you should be fine.


text:
Q: ComboBoxes in DataGridView resets to default after having been set individually I am working on an application with which a .mdb database can be edited. This database represents part of a network. All of these tables have lots of rules and links with other tables and other files.
I have a TabControl with a tab for each table, each tab has a DataGridView for a table. They are not linked to the database, but rather load the data once and export it back later. My current problem has to do with a table from a group of 3 tables.

*

*The first one contains entries of buildings.

*The next one contains records of "Frames" (cabinets) in this building. One of the columns in this table is "Location", which refers to the first table. So I made this column a ComboBoxColumn (in design) with the DataSource set to the DataGridView.Datasource of the first table (in code) and the DisplayMember and ValueMember to the correct column.

*The third table is for patchpanels in a frame. Two of the columns refer to the two previous tables. First is a "Location" column, which is equal to the Location column in the previous table. The second is a "Frame" column, which should refer to the previous table. I want this column to be a ComboBoxColumn as well, but this time they should not all be the same. If a patchpanel is in Location A, it can only be in a Frame that is also in Location A.

I made a class for each table and record, each table class contains a BindingList<Record>. I have a function UpdatePatchpanelFrames(int row) in the PatchpanelTable class that sets the ComboBox.DataSource of a certain row in the datagrid to a List<string>, which contains all frames in the location specified in the location column (see below). For now, I added this function to the records.ListChanged event of the binding list in the table's constructor. So this event causes an update of the ComboBox in the row with index e.NewIndex.
What I expect is that when the records are added from the .mdb database (in order, so first, the buildings are loaded, then frames, and then patchpanels), the UpdatePatchpanelFrames is called for each newly added record/row and that the ComboBox's DataSource is set correctly. If I print the ComboBox's items this indeed happens.
What I didn't expect is that the ComboBox will reset, at an for me unknown moment and unknown reason, to the column's default. The default list of items is empty, so it causes an error because the value in the cell is not part of the ComboBox's items.
What I tried is settings the ComboBoxes again using the DataGridView.VisibleChanged event, which works. By printing the items before and after calling UpdatePatchpanelFrames again, I confirmed that the ComboBoxes' lists of items are indeed reset to the default list of items. But this causes an update each time the datagrid becomes visible which would require an additional bool and check if it's the first time it's visible and I really dislike this workaround as it, imo, shouldn't be necessary. And I don't like having to change code in two places if want to change one column.
I also made my own DataGridViewCustomComboBoxColumn and -Cell. In the Cell I override the DataSource and only call base.set if the value is not equal to its OwningColumn DataSource which caused the base.set to be called exactly once for each row, but it still didn't work so it somehow reset without setting the Cell's DataSource.
In the program's constructor, InitializeComponent() is called first, then all table objects are constructed and after that, all data is loaded in order.
I'd like to know how I can either prevent the comboboxes from resetting or if a different approach would solve the problem.
Thanks in advance!
Here is the code of the UpdatePatchpanelFrames function(s):
private void UpdatePatchpanelFrames(object sender, ListChangedEventArgs e)
{
    if (e.NewIndex >= 0 && e.NewIndex < records.Count)
        UpdatePatchpanelFrames(e.NewIndex);
}

public void UpdatePatchpanelFrames(int row)
{
    List<string> data = new List<string>();
    PatchpanelRecord record = records[row];

    if (!string.IsNullOrWhiteSpace(record.LOCATION))
        data.AddRange(DatabaseController.Instance.FrameTable.Frames(record.LOCATION));

    if (!data.Contains(record.FRAME))
        record.FRAME = string.Empty;

    (dataGridView.Rows[row].Cells[2] as DataGridViewComboBoxCell).DataSource = data;
}

How I checked (and reset) the comboboxes with the VisibleChanged event:
private void DataGridViewPatchpanel_VisibleChanged(object sender, EventArgs e)
{
    if ((sender as DataGridView).Visible)
    {
        for (int i = 0; i < dataGridViewPatchpanel.RowCount - (dataGridViewPatchpanel.AllowUserToAddRows ? 1 : 0); ++i)
        {
            Debug.WriteLine("---");
            foreach (string item in (dataGridViewPatchpanel.Rows[i].Cells[2] as DataGridViewComboBoxCell).Items)
                Debug.WriteLine(item);
            Debug.WriteLine(" | ");

            DBC.PatchpanelTable.UpdatePatchpanelFrames(i);

            Debug.WriteLine(" v ");
            foreach (string item in (dataGridViewPatchpanel.Rows[i].Cells[2] as DataGridViewComboBoxCell).Items)
                Debug.WriteLine(item);
            Debug.WriteLine("---\n");
        }
    }
}


text:
Q: Use factory design pattern to create a specific object I am using this DTO class to pass object between web application layers
public class CreateProgressDTO
{
    public int Total { get; set; }
    public int Created { get; set; }
    public decimal Progress { get; set; }
}

In many places I had to do the following:
var createdNone = new CreateProgressDTO()
{
    Total = totalUnitsToCreate,
    Created = 0,
    Progress = 0m
}

In many places I had the same code as above. I thought it would be nice to create a class, that would derive me proper objects:
public static class CreateProgressFactory
{
    public static CreateProgressDTO CreatedAll(int total)
    {
        return new CreateProgressDTO()
        {
            Total = total,
            Created = total,
            Progress = 100m
        };
    }

    public static CreateProgressDTO CreatedNone(int total)
    {
        return new CreateProgressDTO()
        {
            Total = total,
            Created = 0,
            Progress = 0m
        };
    }

    public static CreateProgressDTO CreatedExactly(int total, int created)
    {
        if (total == 0)
            return CreatedNone(0);

        return new CreateProgressDTO()
        {
            Total = total,
            Created = created,
            Progress = Math.Round((decimal)created / total * 100, 2)
        };
    }
}

Is it ok to use a factory pattern like this?

A: There is nothing wrong with such a pattern, but I'm not sure I would call it a 'factory', since that might imply some level of abstraction. In this case you are in practice just writing some named constructors, there is not really any abstraction at all, just some convenient methods to avoid repeated code.
I would personally just add such convenience methods to the class itself, so you would write CreateProgressDTO.CreateAll(...). For generic classes (assuming c#) it is sometimes useful to add a non-generic class with the same name for such methods, since that also allow for type inference.


text:
Q: flutter youtube video inside container or box I follow the example of Flutter flutter_youtube 1.1.1 , but it only can click the button and start a page with youtube video. May I know how to put the youtube video in a container or box?
 void playYoutubeVideoEdit() {
    var youtube = new FlutterYoutube();

    youtube.onVideoEnded.listen((onData) {
      //perform your action when video playing is done
    });

    FlutterYoutube.playYoutubeVideoByUrl(
      apiKey: "fdsfsgfdsgf-Fp_KPafdsfdgfdgfdssdfsWVHCoiWCVwh8",
      videoUrl: "https://www.youtube.com/watch?v=D5jK8W4wlu8",
      autoPlay: true,
      fullScreen: false
    );
  }

A: also you wrote the right answer ;)
example here
if you want see thumbnail, you must use youtube data api


text:
Q: Using XSL transformation with XML to HTML - output is blank I am a novice to XML and XSL to convert to HTML. I have created my XML and XSL but my output is blank. I think it has something to do with the nodes not being matched? But I am not sure. Any help would be greatly appreciated!
Here is my XSL code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wci="http://www.jda.com/taglibs/wci" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fmt="http://java.sun.com/jsp/jstl/fmt">
<xsl:template match="Privacy">
<xsl:variable name="uppercase">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
<xsl:variable name="lowercase">abcdefghijklmnopqrstuvwxyz</xsl:variable>
<xsl:choose>
<xsl:when test="//ContentSettings/LenovoCodeBase">
<c:if><xsl:attribute name="test">
<xsl:text disable-output-escaping="yes">${empty LenovoCodeBase}</xsl:text>
</xsl:attribute>
<c:set var="LenovoCodeBase" scope="request">
<xsl:attribute name="value">
<xsl:value-of select="//ContentSettings/LenovoCodeBase"/>
</xsl:attribute>
</c:set>
</c:if>
</xsl:when>
<xsl:otherwise>
<c:if>
<xsl:attribute name="test">
<xsl:text disable-output-escaping="yes">${empty LenovoCodeBase}</xsl:text>
</xsl:attribute>
<c:set var="LenovoCodeBase" scope="request" value="OWv2"/>
</c:if>
</xsl:otherwise>
</xsl:choose>

<xsl:for-each select="Tab">

</xsl:for-each>

  <xsl:for-each select="ContentText">

<xsl:value-of select="PageTitle" disable-output-escaping="yes"/><xsl:attribute name="a-name"><xsl:value-of select="PageTitle"/></xsl:attribute><xsl:value-of select="PageTitle"/>

  <xsl:value-of select="Content" disable-output-escaping="yes"/>
  </xsl:for-each>

  <xsl:for-each select="ContentText">
  <xsl:value-of select="Content" disable-output-escaping="yes"/>
</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

Here is my XML:
<container name="Privacy" location="Privacy">
<tab name="Navigation">
    Navigation
    <container name="ContentText" location="ContentText" default="1" min="0" max="1">
            <item name="LinkLabel" pathid="LinkLabel">
                Link Label
                <text required="t" maxlength="" />
            </item>
            <item name="URLPath" pathid="URLPath">
                URL Path
                <text required="t" />
            </item>
        </container>
    </tab>
<tab name="Content">
Content
    <container name="Tab" location="Tab" min="0" max="40" default="1">
    Content Title
        <container name="PageTitle" location="PageTitle" default="0" min="1" max="1">
            <item name="PageTitle" pathid="PageTitle">
                Page Title
                <text required="f" maxlength=""/>
            </item>
        Content
        <container name="Content" location="Content" default="1" min="0" max="40">
            <item name="Content" pathid="Content">
                Content
                <textarea external-editor-config="rich-text-area" external-editor="tinymce" rows="4" cols="100"/>
            </item>
        </container>
        </container>
    </container>
    </tab>
<tab name="SidebarContent">
    <container name="Sidebar" location="Sidebar">
        Right Sidebar Area
        <container name="sidebarcontent" location="sidebarcontent" min="0" max="4" default="1">
            Content
            <item name="Content" pathid="Content">
                Content
                <description>Content Text</description>
                <textarea external-editor-config="rich-text-area" external-editor="tinymce" rows="4" cols="50"/>
            </item>
        </container>
    </container>
</tab>

A:
I think it has something to do with the nodes not being matched?

Well, starting from the very beginning:
<xsl:template match="Privacy">

matches nothing in your input, as there is no element named Privacy. I suspect you meant to refer to container[@name="Privacy"] ?
Similarly, later you refer to ContentText - but that too is an attribute of a container element.


text:
Q: Get or set values in post meta I've built this theme option, based on the following tutorial https://rudrastyh.com/gutenberg/plugin-sidebars.html#registerPlugin
but now I'm having trouble figuring out how to send the post/page data (including the colors that were chosen).
Could anyone give me a hand?
Cheers!
const PrimaryThemeColor = withState( {
    color: '#fff',
} )( ( { color, setState } ) => {
    console.log('PrimaryThemeColor', color)

    return (
        <ColorPicker
            color={ color }
            onChangeComplete={ ( value ) => setState({color: value.hex})}
            disableAlpha
        />
    )
} );

const SecondaryThemeColor = withState( {
    color: '#fff',
} )( ( { color, setState } ) => {
    console.log('SecondaryThemeColor', color)

    return (
        <ColorPicker
            color={ color }
            onChangeComplete={ ( value ) => setState({color: value.hex})}
            disableAlpha
        />
    )
} );

export const ThemeColorPalette = () => {
    return (
        <PluginSidebar
            name="theme-plugin-sidebar"
            title="Theme Plugin"
            icon='admin-appearance'
        >

Primary Colour

                <PrimaryThemeColor />

Secondary Colour

                <SecondaryThemeColor />

        </PluginSidebar>
    );
};
registerPlugin( 'brave-theme-plugin-sidebar', { render: ThemeColorPalette } );

A: In the end, I've managed to do in this way
(function( plugins, editPost, element, components, data, compose ) {

    const el = element.createElement;

    const { Fragment } = element;
    const { registerPlugin } = plugins;
    const { PluginSidebar, PluginSidebarMoreMenuItem } = editPost;
    const { PanelBody, ColorPicker } = components;
    const { withSelect, withDispatch } = data;

    const MetaThemeControl = compose.compose(
        withDispatch( function( dispatch, props ) {
            return {
                setMetaValue: function( metaValue ) {
                    dispatch( 'core/editor' ).editPost(
                        { meta: { [ props.metaKey ]: metaValue } }
                    );
                }
            }
        } ),
        withSelect( function( select, props ) {
            return {
                metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaKey ],
            }
        } ) )( function( props ) {
            return el( ColorPicker, {
                label: props.title,
                value: props.metaValue,
                onChangeComplete: function( content ) {
                    props.setMetaValue( content.hex );
                },
            });
        }
    );

    registerPlugin( 'b-theme-sidebar', {
        render: function() {
            return el( Fragment, {},
                el( PluginSidebarMoreMenuItem,
                    {
                        target: 'b-theme-sidebar',
                        icon: 'admin-appearance',
                    },
                    'B Theme'
                ),
                el( PluginSidebar,
                    {
                        name: "b-theme-sidebar",
                        title: "B Theme",
                        icon: 'admin-appearance',
                    },
                    el( PanelBody, {},
                        // primary color
                        el( MetaThemeControl,
                            {
                                metaKey: 'primary_theme',
                                title : 'Primary Theme',
                            }
                        ),
                        // secondary color
                        el( MetaThemeControl,
                            {
                                metaKey: 'secondary_theme',
                                title : 'Secondary Theme',
                            }
                        ),
                    )
                )
            );
        }
    } );
} )(
    window.wp.plugins,
    window.wp.editPost,
    window.wp.element,
    window.wp.components,
    window.wp.data,
    window.wp.compose
);

But I would like to find a solution for my first attempt, cause is much more readable.
EDIT: a tutorial that would resolve the first case:
https://css-tricks.com/managing-wordpress-metadata-in-gutenberg-using-a-sidebar-plugin/


text:
Q: Where can I find a specification for the Flash debugging protocol? Where can I find a specification for the Flash/ActionScript debugging protocol? I would imagine that the protocol is public, as there are plenty of open source debuggers; however, if it's not, a list of resources to reference would be greatly appreciated.
If you're curious, I'm implementing an ActionScript Bytecode (ABC) to CIL compiler, and I'd like to make the resulting assemblies debuggable via standard flash debuggers.

A: The Open Flash Debugger project might help you out.  You might still need to do some reverse engineering, but it describes many of the debugger messages sent back and forth between the debug player and the debugger.
http://osflash.org/ofd


text:
Q: JAR added to Gradle project but no entry in build.gradle I am new to the Java tools and stuff, so please be gentle.
I see that someone has added the Simple Logging Façade 4 Java (SLF4J) logging capability to a project I am looking at in IntelliJ IDEA. The project is a Gradle project and when I see the Project Structure -> Module -> Dependencies, I do see a dependency for the SLF4 jars.

I also see these listed in the External Libraries node in the treeview in the Project window.

However, when I open the build.gradle file, I see no entry for slfj. How is that? How would this library have been added to the project?

A: slf4j is a transitive dependency of some other library.
Use ./gradlew dependencies on the root folder of your project to see the dependencies graph.

A: slf4j ist most likely a transitive dependency of one of the declared dependencies.
To list the dependency tree, you can use gradlew dependencies.
To list the dependency tree for a specific configuration, you can use gradlew dependencies --configuration runtime.
In your situation you can also use the other way around and use dependencyInsight task instead like gradlew dependencyInsight --configuration runtime --dependency org.slf4j:slf4j-api to see which declared dependencies depen on the given dependency in the given configuration.


text:
Q: How are textual data files parsed in modern C++? I am (too) often confronted with the task of having to parse textual data files -- the kind of textual structured data representation you used before "everyone" used XML -- that are some kind of industry standard. (There are too many of these.)
Anyways, the basic task is always taking a text file and stuffing what's in there in some kind of datastructure so that our C++ code can do something with the info.
Now, I have implemented a few simple (and oh so buggy) parsers by hand, and there is little I despise more. :-)
So - I was wondering what the current state of the art is when I want to "parse" structured textual data into a in-memory representation (think: XML data binding for an arbitrary language).
What I found so far was "What parser generator do you recommend", but I'm not so sure I'm after a parser generator (like ANTLR).
Obvious candidates seem to be pegtl and Boost.Spirit but they both seem rather complicated (but at least they're in-language) and last time I tried Spirit, the compiler errors drove me nuts. (And pegtl needs a C++11 compatible compiler which is still a problem here (VC++ 2005).)
So am I missing a simpler solution for just getting something like
/begin COMPU_METHOD
  DEC "  Decimal value"
  RAT_FUNC
  "%3.0"
  "dec"
  COEFFS 0 1.000000 0.000000 0 0.000000 1.000000
/end COMPU_METHOD

into a C++ datastructure? (This is just an arbitrary example of how part of such a file may look. For this format I could (and probably should) buy a library to parse it, as it is widespread enough -- which is not the case for all formats I encounter.)
-- or should I just go for the complexity of, say Boost.Spirit?

A: I highly recommend biting the bullet and using Boost.Spirit.  Although the error messages can be enough to put one out of one's skull, it's been worth it for me.  I have used it to implement parsers for under- (or un-) documented custom file formats in a matter of hours, instead of days.
I found that the best way to approach it was to view it as an "std::istream on steroids", since it uses the same double-angle notation to denote separation.

A: *

*Boost Spirit
See

*

*my answer here for a demo that resembles your sample;

*a more advanced, shorter demo here that parses into a tree structure

*more samples search

*Coco/R (C++)
I have had good results with this very pragmatic parser generator that supports many lnaguages/platforms using a common grammar format. The speed of parsing is comparable to Boost Spirit (allthough the processing of parsed data may be more efficient using generic programming)
Edit To make things perfectly clear, there never has been a thing that I wasn't able to do with Coco/R.
However, I'm really addicted to the ease with which Spirit deduces attribute type (conversions) for me generically. That is the main timesaver. There is a cost involved though:

*

*learning curve, maintenance

*compile time (but parsers don't often change)

A: You do not mention how sophisticated were the parsers you created by hand. But I believe such simple files could be definitely parsed by hand crafted routines as long as you split your work to lexical and syntactic parsing performed by dedicated state machines. The first one recognizes tokens like in your example keywords, numbers and strings, and feeds them to the second trying to recognize longer sentences and create corresponding data structures. With a simple files following regular grammars with no ambiguities and other conflicts it should be really simple and manageable.


text:
Q: WP UI style within shortcode - Any Suggestions? I am using the wp-ui Wordpress plugin to create vertical tabbed content.  What I want to do is add a span to part of the tab title - to add some additional style, but the shortcode/plugin strips my "span" code
[wptabs mode="vertical" effect="fade"]
[wptabtitle] Silent auction - More title here.[/wptabtitle]
[wptabcontent] Content goes here [/wptabcontent]
[/wptabs]

Is there a simple way to keep the shortcode/plugin from stripping my added code.  The plugin shortcode is easier for the client otherwise, I'd try something different.
Help?  Can anyone explain what I need to do with the code below to get the result above?
I found this code:
add_shortcode( 'wptabtitle',    array(&$this, 'sc_wptabtitle'));

Then, I located this in the same file.
/**
 *  [wptabtitle]
 */
function sc_wptabtitle( $atts, $content = null ) {
    extract(shortcode_atts(array(
        'header'    =>  'h3',
        'hclass'    =>  'wp-tab-title',
        'label'     =>  'text',
        'image_size'=>  '24,24',
        '_id'       =>  false,
        'load'      =>  '',
        'post'      =>  '',
        'page'      =>  '',
        'cat'       =>  '',
        'category_name' => '',
        'tag'       =>  '',
        'tag_name'      =>  '',
        'number'    =>  '4',
        'exclude'   =>  '',
        'tag'       =>  '',
        'feed'      =>  '',
        'hide'      =>  "false",
        'elength'   =>  $this->options['excerpt_length'],
        'before_post'   =>  '',
        'after_post'    =>  '',
        'template'      =>  '1',
        'icon'      =>  false
    ), $atts));

    global $wpui_id_remove_chars;

    if ( str_ireplace( $wpui_id_remove_chars, '', $_id ) != $_id )
        $_id = false;

    $tmpl = ( isset( $this->options[ 'post_template_' . $template ] ) ) ?
                $this->options[ 'post_template_' . $template ] :
                $this->options[ 'post_template_1' ];

     if ( isset( $this->options[ 'title_template' ] ) && $this->options[ 'title_template' ] != '' ) {
         $title_template = $this->options[ 'title_template' ];
        if ( $_id ) {
            $title_template = str_ireplace( '>{$title}', 'id="' . $_id . '">{$title}', $title_template );
        }
     } else {
         $title_template = '<' . $header;
         $title_template .= ' class="' . $hclass . '"';
         if ( $_id ) {
             $title_template .= ' id="' . $_id . '"';
         }
         $title_template .= '>{$title}</' . $header . '>';
     }

    if ( $hide == "true" ) $hclass .= ' wpui-hidden-tab';

    $data = false;

    // Get the post contents.
    if ( $post != '' ) {
        $data = $this->wpuiPosts->wpui_get_post( $post, $elength );
    } elseif ( $page != '' ) {
        $data = $this->wpuiPosts->wpui_get_post( $page, $elength );
    } elseif ( $feed != '' ) {
        $data = $this->wpuiPosts->wpui_get_feeds( array(
                        'url'       =>  $feed,
                        'number'    =>  $number
                    ));

    } elseif ( $cat != '' || $category_name != '' || $tag != '' || $tag_name != '' ) {
        $data = $this->wpuiPosts->wpui_get_posts( array(
                                    'cat'       =>  $cat,
                                    'category_name' => $category_name,
                                    'tag'       =>  $tag,
                                    'tag_name'  =>  $tag_name,
                                    'number'    =>  $number,
                                    'exclude'   =>  $exclude,
                                    'length'    =>  $elength
                                ));
    }

    if ( $load != '' ) {
        $content = '' . $content . '';
    }

    $title_str = str_ireplace( '{$title}', $content, $title_template );

    if ( $icon && $icon != '' ) {
        $title_str = str_replace( '{$thumbnail}', htmlspecialchars_decode( $icon ), $title_str );
    }

    if ( is_array( $data ) ) {
        if ( isset( $data[ 'title' ] ) ) {
            $title_str = $this->wpuiPosts->replace_tags( $title_template, $data );
            $data = $before_post . $this->wpuiPosts->replace_tags( $tmpl, $data ) . $after_post;
        } else {
            $scra = '';
            foreach( $data as $index=>$values ) {
                $scra .= $this->wpuiPosts->replace_tags( $tmpl, $values );
            }
            $data = $before_post . $scra . $after_post;
        }
    }

    $title_str = preg_replace( '/\{.*\}/', '', $title_str );

    $output = $title_str;

    if ( $data ) {
        $output .= do_shortcode( "[wptabcontent]" . $data . "[/wptabcontent]" );
    }

    return $output;

} // END function sc_wptabtitle

Thanks,
Louise


text:
Q: facebook publish to wall as page I am developing a facebook application.
In my application I'd like to give page administrators the ability to publish to their page's wall, not as a user, but rather as they page itself.
Can this be done? If so how?
Thank you.

A: Apperently this possible when prompting user with the "manage_pages" permission. Then it is possible to query the page's access token, and perform the operation in the page's name.
You can check this documentation down here:
http://developers.facebook.com/docs/authentication/
And here's a small code sample, of how it might look using the facebook c# sdk:
            dynamic pagesInfo = FacebookApp.Api("/me/accounts");
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string pageAccessToken = null;
            foreach(IDictionary<string,object> page in serializer.DeserializeObject(pagesInfo.data.ToString()))
            {
                long pageId = long.Parse(page["id"].ToString());
                if (pageId == localBusiness.FanPageId)
                {
                    pageAccessToken = page["access_token"].ToString();
                }
            }
            if (pageAccessToken == null)
                return;

        var pageFbApp = new FacebookApp(pageAccessToken);
        // post as application
        Dictionary<string, object> parameters = new Dictionary<string, object>()
                                                {
                                                    {"from",
                                                    new Dictionary<string,object>()
                                                    {
                                                        {"id" , localBusiness.FanPageId},
                                                        {"name" , localBusiness.Name}
                                                    }},
                                                    {"description", description},
                                                    {"link", pageUrl },
                                                    {"name", name  },
                                                    {"picture" , imageUrl }
                                                };

        dynamic result = pageFbApp.Post(localBusiness.FanPageId + "/feed", parameters);


text:
Q: PHP /MySQL dynamic breadcrumb ----------------------------------------------------------------------------------
|id_category|parent_id|category_level|category_sort|category_name|category_rw_tag|
|--------------------------------------------------------------------------------|
|1          |0        |1             |NULL         |Shopping     |NULL           |
|2          |1        |2             |NULL         |Laptops      |NULL           |
|3          |2        |3             |NULL         |Accessories  |NULL           |
|4          |3        |4             |NULL         |HDD          |NULL           |
----------------------------------------------------------------------------------

I have a table of categories. to the configuration shown above.
Fist of my problem :
I would like to build a breadcrumb like this :
Shopping > Laptops > Accesories > HDD

Second :
the breadcrumb. must be dynamic!
so when I query the db table with parameter id_category= 5
to display :
Shopping > Laptops > Accesories > HDD

when I query the db table with parameter id_category= 4
Shopping > Laptops > Accesories

...and so on.
I have read all question regarding my question but simply I had no idea how to d this.
Php Jedy's you are my only Hope.

A: you would have to do some queries to retrieve each category until you hit a root category (i.e parent_id = 0). so in your example you would query category with id = 4, check the row parent_id is not equal to zero so query the next category with the parent_id and so on.
If your ecommerce website doesn't have too much categories that would be ok, if you have more than 5 levels of categories I would advice to make a breadscrumb field in your table with an already formated text.

A: Your question is a logical duplicate of What is the best practice for fetching a tree of nodes from a database for further rendering.
There is a long list of articles and resources you can use.


text:
Q: Cipher "clientSecret" params in OAuth2 JWT Token CAS Apereo version 6.1.7 I follow this instruction to cipher "clientSecret" params in OAuth2 JWT Token with CAS Apereo 6.1
https://apereo.github.io/2019/11/04/cas62x-oauth-jwt-access-token/
Step 1: Using CAS Shell to cipher clientSecret
root@ubuntu16:~/lam/cas-overlay-template# ./gradlew downloadShell runShell
root@ubuntu16:~/lam/cas-overlay-template# java -jar build/libs/cas-server-support-shell-6.1.7.jar
cas>encrypt-value value exampleOauthClientSecret alg PBEWithMD5AndTripleDES provider SunJCE password Vnpt@123 iterations 1000
==== Encrypted Value ====
{cas-cipher}La813rUHz0m2XM/DwqjvGtHPX+l8XtMzI80UGXH24uDMGXCqsAYFfg==
cas>decrypt-value value {cas-cipher}La813rUHz0m2XM/DwqjvGtHPX+l8XtMzI80UGXH24uDMGXCqsAYFfg== alg PBEWithMD5AndTripleDES provider SunJCE password Vnpt@123 iterations 1000

==== Decrypted Value ====
exampleOauthClientSecret

Step 2: I make service  registration like this
root@ubuntu16:/etc/cas/services-repo# cat OAuthJWTService-3.json
{
    "@class" : "org.apereo.cas.support.oauth.services.OAuthRegisteredService",
    "clientId": "exampleOauthClient",
   #"clientSecret": "exampleOauthClientSecret",
    "clientSecret": "{cas-cipher}La813rUHz0m2XM/DwqjvGtHPX+l8XtMzI80UGXH24uDMGXCqsAYFfg==",
    "serviceId" : "^https://cascore.vdc2.com.vn:9999/.*",
    "name" : "OAuthJWTService",
    "id" : 3,
    "jwtAccessToken": true,
    "attributeReleasePolicy" : {
        "@class" : "org.apereo.cas.services.ReturnAllowedAttributeReleasePolicy",
        "allowedAttributes" : [ "java.util.ArrayList", ["comdepartment","comid","lastname","usercode","userdate","useremail","userparentid","userstatus","usertel","usertype" ] ]
 },
        "properties" : {
        "@class" : "java.util.HashMap",
        "accessTokenAsJwtSigningKey" : {
            "@class" : "org.apereo.cas.services.DefaultRegisteredServiceProperty",
            "values" : [ "java.util.HashSet", [ "CoSfJ2WweU-cWcUYSjW2PWLVLd9hIVG0xxjFFUHSUbCjkkNiwPli_WlqF9V2MHJH3SGH_4DifSYxlgs98h4snA" ] ]
  },
            "accessTokenAsJwtEncryptionKey" : {
            "@class" : "org.apereo.cas.services.DefaultRegisteredServiceProperty",
            "values" : [ "java.util.HashSet", [ "_3gpqpSiIEjHT0xlscGvgDr0-iPIeeEeyecfFgbg_5E" ] ]
      },
      "accessTokenAsJwtSigningEnabled" : {
           "@class" : "org.apereo.cas.services.DefaultRegisteredServiceProperty",
           "values" : [ "java.util.HashSet", [ "true" ] ]
      },
      "accessTokenAsJwtEncryptionEnabled" : {
           "@class" : "org.apereo.cas.services.DefaultRegisteredServiceProperty",
           "values" : [ "java.util.HashSet", [ "true" ] ]
      },
      "accessTokenAsJwtCipherStrategyType" : {
          "@class" : "org.apereo.cas.services.DefaultRegisteredServiceProperty",
           "values" : [ "java.util.HashSet", [ "SIGN_AND_ENCRYPT" ] ]
      }
   }
}

Step 3: I config CAS Apereo global like this (my global config store in MongoDB)
{"_id":{"$oid":"5f058f62ee9a446824d4adf3"},"name":"org.apereo.cas.standalone.configurationSecurity.alg","value":"PBEWithMD5AndTripleDES"}
{"_id":{"$oid":"5f058f79ee9a446824d4adf4"},"name":"org.apereo.cas.standalone.configurationSecurity.provider","value":"SunJCE"}
{"_id":{"$oid":"5f058f8aee9a446824d4adf5"},"name":"org.apereo.cas.standalone.configurationSecurity.iterations","value":"1000"}
{"_id":{"$oid":"5f058f9dee9a446824d4adf6"},"name":"org.apereo.cas.standalone.configurationSecurity.psw","value":"Vnpt@123"}

Step 4: I rebuild CAS
Step 5: I call API to create JWT token like this
curl https://cascore.vdc2.com.vn:8443/cas/oauth2.0/token?grant_type=password'&'client_id=exampleOauthClient'&'client_secret=exampleOauthClientSecret'&'username=abc'&'password=Vnpt@123 | jq

But It shows this problem
{
  "@class": "java.util.LinkedHashMap",
  "timestamp": [
     "java.util.Date",
      1594370510760
   ],
  "status": 401,
  "error": "Unauthorized",
  "message": "No message available",
  "path": "/cas/oauth2.0/token"
}

I try agin with this
curl https://cascore.vdc2.com.vn:8443/cas/oauth2.0/token?grant_type=password'&'client_id=exampleOauthClient'&'client_secret={cas-cipher}La813rUHz0m2XM/DwqjvGtHPX+l8XtMzI80UGXH24uDMGXCqsAYFfg=='&'username=abc'&'password=Vnpt@123 | jq

But it shows this error again
{
  "@class": "java.util.LinkedHashMap",
  "timestamp": [
     "java.util.Date",
     1594370510760
  ],
     "status": 401,
     "error": "Unauthorized",
     "message": "No message available",
     "path": "/cas/oauth2.0/token"
}

Finally, I try change param to plain text in registration file from "clientSecret": "{cas-cipher}La813rUHz0m2XM/DwqjvGtHPX+l8XtMzI80UGXH24uDMGXCqsAYFfg==", to "clientSecret": "exampleOauthClientSecret",
It works and gives me JWT token.
Please help me.
Thanks

A:
I follow this instruction to cipher "clientSecret" params in OAuth2 JWT Token with CAS Apereo 6.1

If you read the blog post at the link you shared carefully, you'll note that:

Our starting position is based on:

*

*CAS 6.2.x

So that's probably why the instructions do not work for you.


text:
Q: Laravel mocking model with persistence I'm testing a job that receives a customer model. In the job I create the
customer in shopify and store that id on the customer model. Then I call a sendShopifyInvite that needs to be mocked (I don't want to send an email in my test).
My test looks like this:
/** @test */
public function a_shopify_customer_is_created_if_it_does_not_yet_exists()
{
    $this->partialMock(User::class, function ($mock) {
        $mock->shouldReceive('sendShopifyInvite')->once()->andReturn(new User());
    });

    $customer = app(User::class)->fill(
        factory(User::class)->create([
            'shopify_id' => null
        ])->toArray()
    );

    $this->assertNull($customer->shopify_id);

    CreateCustomerJob::dispatchNow($customer);

    $customer->refresh();

    $this->assertNotNull($customer->shopify_id);
}

The problem is that I receive this error:
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jensssen_db.mockery_0__domain__customer__models__users' doesn't exist

Is it not possible to persist data in a mock object? Are there any other ways?

A: Your problem is due to this line. Since a partial mocks creates a new mock object and calls your original model through it, it will take that class basename.
return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));

I can see two solutions, i don't feel like anyone is the perfect solutions, it will solve your problem. Firstly set your table hardcoded on the User.php model. This will avoid the class basename being called.
class User {
    $protected table = 'users';
}

Another approach, i have been forced to make before (when you have a hard time mocking some classes). Is instead of mocking your User.php model, simply put the same logic in a service / proxy class and mock that instead.
class ShopifyService {
    public function sendInvite(User $user)
    {
        ...
    }
}

In your User.php model now have.
public function sendShopifyInvite() {
    resolve(ShopifyService::class)->sendInvite($this);
}

Now you are able to mock only the Shopify service and now not tinker with the inner workings of the Eloquent Model.
$this->partialMock(ShopifyService::class, function ($mock) {
    $user = new User();
    $mock->shouldReceive('sendInvite')->with($user)->once()->andReturn($user);
});


text:
Q: When checking the validity of date of birth separated by dashes, an error rises when entering characters, and i can't solve that issue from the requirements of my final project is to validate the scanned date of birth in the following format (DD-MM-YYYY).
the date of birth is a struct formed of 3 integers, day, month and year. So, I scan it from the user as follow:
  scanf("%d-%d-%d",&dob.day,&dob.month,&dob.year);

However, when I enter a character, of course it enters an infinite loop.
I tried to use the flushinput concept (as I've used it with other scanned integers). It prevents the infinite loop. However, when re-scanning (through a certain loop), it keeps showing the "INVALID EMAIL" message, even though the entered email is correct! I guess this arises due to the presence of the dashes in the input.
So, can anybody tell me what to do?
Here's the part of the code where the issue arises (without the flushinput function):
void dobCheck(DATE dob) ///validates date of birth and rescans it if wrong
{
    while(1)
    {
       if (dob.year<1806 || dob.year>2021 || dob.month<1 || dob.month>12 || dob.day<1 || dob.day >31)
       {
          dobCheckAct(dob); continue;
       }
      if ((dob.year%4)==0 && dob.month ==2 && dob.day >29)
      {
          dobCheckAct(dob); continue;
      }
      if (dob.year%4)!=0 && dob.month ==2 && dob.day >28)
      {
          dobCheckAct(dob); continue;
      }
      if (dob.month == 4 ||dob.month == 6 || dob.month == 9 || dob.month == 11) && dob.day> 30)
      {
          dobCheckAct(dob); continue;
      }
      break;
  }
}
void dobCheckAct(DATE dob) ///action taken in case of invalid date of birth
{
    printf("\a\n**INVALID DATE OF BIRTH!\n");
    scanf("%d-%d-%d",&dob.day,dob.month,dob.year);
}

Thanks in advance!!


text:
Q: advanced boot options ubuntu 14.04 dvd I have been trying to access the advanced menu when booting from a ubuntu 14.04.1 32 bit dvd. I have tried f6, f12, all the f's actually, and I cant stop it from loading the graphical menu where you choose to try live or install. The md5 sum for the iso is right. Is there any reason I wouldn't be able to get to the advanced options?
EDIT: I should also mention that I have tries other keys, like letters, arrows, etc., and I have done all this when the little logo was at the bottom of the screen.

A: I would try pressing any other key that's not one of the f* keys when the small logo appears at the bottom of the screen during the boot process.  That's the way to access the advanced boot options in the Ubuntu DVD.
For more details on this go to the Boot Options page.


text:
Q: XML Validation Apache Camel Im trying to use the Camel Validation Component to validate an XML against an XSD.
<to uri="validator:validation_xsd/Schema.xsd" />

When I catch the SchemaValidationException and I get the errors .getErrors()
it just return a List of 1 element (just the first one).
Is is possible to validate the entire element and get all errors?.
The XML I'm trying to validate has almost 10.000 errors.


text:
Q: Calculations on geometrical shapes in R I would like to display and do some calculations (e.g. area, size) on geometrical shapes that intersect, in R. Can someone tell me how to do that? (previous wording "can someone recommend a suitable package for that" resulted in the question being closed, but that's really all I need, I am familiar with analytical geometry).
Extensive research on the internet resulted in loads of material about geographical objects and spherical geometry. Here I am interested in plain 2D shapes in cartesian coordinates only.
A simple example would be nice: a circle and a rectangle (size and position not importand) intersecting, and area and radius of the smallest surrounding circle of the intersection area being estimated.
I could use an image analysis library for the job and be ready immediately, but R really is the preferred tool for the following evaluations.

A: You might want to use sf package. While this package is most often used for geospatial data, it can also handle geometric intersections. Let me provide a basic example of calculating overlap of a rectangle and oval-like shape. I'll also use plotrix package briefly to generate data for an oval-like shape, since you didn't put sample data in your question.
library(sf)
plot(0)
#make a oval, then put oval points in a dataframe
oval<-plotrix::draw.circle( 0, 0, .5 ) %>% data.frame(.)

#combine oval data points into an sf object. Convert points to polygon
oval_sf <- sf::st_as_sf(oval, coords = c("x", "y")) %>%
  sf::st_combine(.) %>%
  sf::st_cast(., "POLYGON")

#Make a rectangle. I make a 1 X 1.5 rectangle in the example.
rectangle <-sf::st_polygon(list(cbind(c(0, 0, 1.5, 1.5, 0), c(0, 1, 1, 0, 0))))

#Sum of area of the two separate shapes
total_area <- st_area(rectangle) + st_area(oval_sf)
#Sum of area of two shapes if combined into one shape
combined_area<-st_area(st_union(oval_sf,rectangle))
#Then calculate the area of the intersection
intersection_area <- total_area - combined_area
intersection_area
[1] 0.4716912

For examples illustrating more complex intersections within sf, have a look at:
https://r-spatial.github.io/sf/reference/geos_binary_ops.html


text:
Q: Java Web Service makes JPA-MySql inserts, but not selects after the insert I'm using Link JPA with MySQL into a Web Service to select, insert, update and delete data from/to database.
The problem is: the Web Service makes correctly insert, but then it does not retrieve the data correctly. Example:
Table Usuario linked with a Collection of Table Pets:
-- Select how many pets the user X have: 2.
-- Insert 1 more pet into the user X: ok
-- Select how many pets the user X have: 2 too. (This data should be 3)
But, into the data base the data is correct (3): the insert is made correctly

A: In same session  , If you inserting through session object and reading through JPQL then It'll return only 2 record. Flush after inserting than check what you get.


text:
Q: Trying to convert for /f "tokens=*" %%a in ... to SHELL I am trying to convert a whole BATCH script to SHELL script with the help of this sort of converter manual.
I have almost finished, but I am struggling to convert this FOR LOOP:
for /f "tokens=*" %%a in ('%adb% shell mkdir /usr/ui/^|find /i "File exists"') do (
    if not errorlevel 1 goto :cannot_patch
)

I know that for /f is

Loop command: against a set of files - conditionally perform a command against each item.

However, as I am a noob to SHELL SCRIPT (and BASH as well), my best try was:
for -f "tokens=*" a in ( '$ADB shell mkdir /usr/ui/^|find /i "File exists"' ); do
    if [ $? -nq 1 ]
    then
        cannot_patch
    fi
done

which does not work, resulting in a Syntax error: Bad for loop variable.
Any hint, link, or suggestion would be very much appreciated.
EDIT
I am trying to understand what exactly ('%adb% shell mkdir /usr/ui/^|find /i "File exists"') is doing.
I thought those were sh commands, but it turns out I was wrong and that find /i is trying to

Search(ing) for a text string in a file & display all the lines where it is found.

(https://ss64.com/nt/find.html)
| is the pipe operator and "File exists" should be the error thrown by mkdir in case the command tries to create a directory that already exists.
So I think I could probably write this easier, but still, what does the ^ symbol in /usr/ui/^ do? Is it a regex?
EDIT2
It seems indeed that @glenn_jackman is right: probably I'd better understand what the code is trying to do.
So to give a better context, here is a bit more code of the original batch:
for /f "tokens=*" %%a in ('%adb% shell mkdir /usr/ui/^|find /i "File exists"') do (
    if not errorlevel 1 goto :cannot_patch
)
:cannot_patch
echo Error: Cannot create directory!
echo Patch is already installed or system files exist and might be overwritten.
choice /m "Do you want to continue"
if errorlevel 2 goto :END
goto :continue_patch

To my understanding, the code is trying to run the adb shell mkdir command and, if it fails (throwing the "File exists" error), it will ask to the user if he/she wants to continue regardless.
So in this case, I guess the real problem is trying to write a code that does the same in SH, probably without the need of a for loop.
Still, I am finding it out...

A: The general syntax of your loop matches https://ss64.com/nt/for.html
You should also look over https://ss64.com/nt/errorlevel.html and this SO reference that lists/explains error codes.
From the SO article, FOR /F │ 1 = No data was processed.
But the errorlevel page says
IF ERRORLEVEL 1 will return TRUE whether the errorlevel is 1 or 5 or 64

and the SO article also says
if %errorlevel% equ 5 (
    echo Can not access the directory, check rights
)

Apparently ^ is a CMD escape character, used here to escape the pipe character being passed as part of a compound command that (I'm guessing...) creates a directory and checks for a failure, so I'm parsing this as an attempt to make the directory, detect if it already exists, and respond accordingly.
I think in bash this would be written this way:
mkdir /usr/ui/ || cannot_patch

A: for /f "tokens=*" %%a in ('%adb% shell mkdir /usr/ui/^|find /i "File exists"') do (
    if not errorlevel 1 goto :cannot_patch
)

runs the command %adb% shell mkdir /usr/ui/ then searches that output for the string File exists. if not errorlevel 1 means "if %errorlevel% is not greater than or equal to 1," which is a weird and awkward way of just saying if "%errorlevel%"=="0", which would mean that the string was found. If it's found, the script then goes to the label :cannot_patch.
In bash, the way to process the output of a command is to use $() instead of for /f, so
$(${adb} shell mkdir /usr/ui/ | grep "File exists") && cannot_patch

This assumes that the variable adb is set and you've got a function in your shell script somewhere called cannot_patch.
Note that the only difference between my answer and Paul Hodge's answer is that I'm assuming that you still need ADB to be called.

A: Sorry, but I have got bad news for you — the batch code you want to transcript is wrong:
for /f "tokens=*" %%a in ('%adb% shell mkdir /usr/ui/^|find /i "File exists"') do (
    if not errorlevel 1 goto :cannot_patch
)

This is not going to do what you probably think it does. The following steps actually happen:

*

*It executes the command %adb% shell mkdir /usr/ui/ and pipes (|) its output into the command find /i "File exists", but all this happens in a new cmd.exe instance created by the for /F loop.

*The for /F loop, well, loops over the lines of the output of the aforesaid commands after they have completed; the new cmd.exe instance is destroyed before starting to iterate.

*BUT: The ErrorLevel value resulting from the %adb% …|find … command line is not available in the body of the for /F loop, because this executes in the cmd.exe instance the batch script itself runs in too. This means, that the condition if not errorlevel 1 in the loop body actually reacts on a preceding command, unintentionally.

Since, as I believe, you simply want to test whether the output of %adb% shell mkdir /usr/ui/ contains the sub-string File exists in a case-insensitive manner, you actually just need this:
rem /* Just using `echo` for demonstration purposes, to be replaced;
rem    moreover, you may also omit the `&&` or the `||` part: */
%adb% shell mkdir /usr/ui/ | find /i "File exists" && (
    echo ErrorLevel 0: sub-string found.
) || (
    echo ErrorLevel 1: sub-string NOT found!
)

Unfortunately, I cannot tell you exactly how to translate this, but find might probably have to be substituted by grep, and the operators && and || could be replaced by checking the exit code returned in $?, unless there are similar operators…


text:
Q: How to make this menu effect work in Safari (Mac) This is the menu of my website. This menu and the effect not working only on MAC Safari browser.
I am a beginner developer It would be great if anyone can help me with it.
Because of not enough characteristic, CSS and JS codes will posted in codepen.
here's source code link: https://codepen.io/Naashik/pen/abGoQOO

        <button onclick="GMclose()" class="menu-trigger menu-trigger--close" style="font-size:22px;font-weight:bold;">X</button>

Contact Us

News & Media

Quality

About Teas

Ceylon Tea

Home

Products


text:
Q: Is it a good or bad idea to maintain references to Assembly objects to avoid unnecessary calls of Assembly.LoadFrom? In a plugin system I instantiate objects and call methods of those objects based on some incoming requests which have some identifier (simply a string). With the help of a configuration this identifier determines which assembly to load, which class in this assembly to instantiate and which method to call. The assemblies are loaded into a separate AppDomain. This happens in a proxy class which is created like so:
secondDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().CodeBase,
    typeof(SecondDomainProxy).FullName) as SecondDamainProxy;

In the class SecondDomainProxy I load the assembly which is related to the identifier mentioned above:
string assemblyFileName = GetAssemblyFileNameFromConfig(identifier);
Assembly assembly = Assembly.LoadFrom(assemblyFileName);
// Instantiate and run something in assembly

Question: Does it make sense to hold a reference to this Assembly object once the assembly has been loaded? For instance with a Dictionary...
Dictionary<string, Assembly> _assemblyDict;

... and by changing the code above to:
Assembly assembly;
if (!_assemblyDict.TryGetValue(identifier, out assembly))
{
    string assemblyFileName = GetAssemblyFileNameFromConfig(identifier);
    assembly = Assembly.LoadFrom(assemblyFileName);
    _assemblyDict[identifier] = assembly;
}
// Instantiate and run something in assembly

I am aware that the assembly is loaded after the first call of Assembly.LoadFrom forever until the AppDomain is unloaded. (The second AppDomain lives as long as the main application in my case.) So does that mean that a second call to Assembly.LoadFrom is cheap, as cheap or almost as cheap as the dictionary lookup? Or does it have drawbacks NOT to call assembly.LoadFrom and to use the saved reference instead?
(My feeling is that it doesn't really matter unless I have high performance requirements which I don't have (one request every 15 seconds roughly). But I could be wrong.)
Thank you for feedback in advance!
Edit:
Assembly is a "normal" .NET class. If I don't have any references to an instance of this class it gets garbage collected, I think. But the assembly itself keeps still loaded. So Assembly.LoadFrom needs at least to create a new instance of the Assembly class, although at the second time this instance creation might be based on the already loaded assembly.
I'd like to add the question: Does creating an assembly object for a given assembly require some heavy reflection and is therefore always expensive, no matter if the assembly is loaded or not?

A: No, it is not necessary.
Once loaded into an AppDomain, the assembly can accessed by using the GetAssemblies() method of the underlying AppDomain object that returns any loaded/available Assembly, s: http://msdn.microsoft.com/en-US/library/system.appdomain.getassemblies.aspx
The only way to unload one or more Assemblies is to unload the AppDomain, by using static Unload() method of the same class.


text: Q: I'm curious about the directory layout in LFS. Why can't we use lib64 as the default directory in LFS if LFS is a pure 64 bit system? In Linux From Scratch during the 1st pass of GCC we have a case command that changes -m64 to ../lib instead of lib64. I am aware that this patch is to eliminate a compile time error but why can't we set the -m64 variable to ../lib64? I am also wondering about the LSB compatibility symlink on glibc in chapter 5. There is also a hardcoded path in ldd that we fix after the install of glibc. the path points to /usr/lib. We patch the ldd to point to /lib but we set the default directory path for our libraries to /usr/lib during configure. I am aware of fedoraprojects usr/move and how the developers have been working on the start up of the boot loader. So we put everything in /usr/lib /usr/bin and /usr/sbin. I guess my confusion is why we can't put libraries in lib64 on LFS if LFS is a pure 64 bit system. I am wondering if they're any 32 bit libraries that still come with glibc or 32 bit legacy programs that we build in blfs even though lfs is a pure 64 bit system and that is why we cannot use lib64? Any help appreciated. GLAWMAN


text:
Q: How to remove text-decoration when li is a hyperlink Here is the CSS
.ulLink{
text-decoration: none;
color: grey;
}

Here is html

http://www.acterra.org/greenteams/bottledwater.html

http://www.ewg.org/research/chlorine-pollutants-high-levels-dc-tap- water

http://www.statisticbrain.com/attention-span-statistics/

Tried using the id from the ul and then putting that still dint work.
#myResources {
    text-decoration: none
}

A: Your HTML is très invalid;
s must be direct descendants of the list. Fix those, and your CSS should work.

 http://www.acterra.org/greenteams/bottledwater.html

http://www.ewg.org/research/chlorine-pollutants-high-levels-dc-tap- water

   http://www.statisticbrain.com/attention-span-statistics/

Removing the spaces between dc- and tap-water couldn't hurt either.

A: Dont put link a before li

 http://www.acterra.org/greenteams/bottledwater.html

http://www.ewg.org/research/chlorine-pollutants-high-levels-dc-tap- water

   http://www.statisticbrain.com/attention-span-statistics/

Use above HTML


text:
Q:  elements surrounding  to overlap it whilst still being able to click on the  and the 's in the 's I'm hitting a problem with a p5js integration in a webpage.
I'm trying to get two paragraph elements, positioned before and after an iframe, to overlap that iframe, whilst still allowing the iframe to be clickable, and still allowing the links in the paragraph elements to be clickable. I've fiddled around and read a lot about how z-index works and about pointer-events but I couldn't find a solution in these. Here is the minimal reproducible example :
The example works as intended with the bottom text, but the top text is being overlapped wrong.

<!DOCTYPE html>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vulputate et libero sit amet blandit. Integer mollis felis dui, vitae euismod nunc tincidunt sed. Aliquam eget libero sed ante interdum consectetur. Quisque a vulputate lorem. Morbi sit
      amet
      scelerisque turpis.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      scelerisque turpis. Fusce vulputate et libero sit amet blandit. Integer mollis felis dui, vitae euismod nunc tincidunt sed. Aliquam eget libero sed ante interdum consectetur. Integer a placerat magna.

note : I've purposefully created a container for the iframe to aid it in its underlapping behavior
which direction could I go in from now ? is there a simple solution I am not seeing ? Thanks a lot

A: You should try this...

#roll{
    width:500px;
    margin-right:auto;
    margin-left:auto;
}

p{
    position:relative;
    font-size:1.5em;
    z-index: 1;
}

.codepoem{
    width:500px;
    height:200px;
}

.codepoem iframe{
    position:relative;
    width:calc(500px + 20vw);
    margin-left:-10vw; /* center horizontal */
    height:calc(200px + 40vh);
    margin-top:-20vh; /* center vertical */
    /*z-index:1;*/
}


text:
Q: Tensorflow precision metrics not initializing I have written the following Tensorflow code that performs logistic regression on a custom dataset.
def logi_regression(data, labels, test_data, test_labels, learning_rate,
                batch_size, training_epochs, display_step):

x = tf.placeholder(tf.float32, [None, data.shape[1]])
y = tf.placeholder(tf.float32, [None, labels.shape[1]])

# Weights
W = tf.Variable(tf.zeros([data.shape[1], 1]))
b = tf.Variable(tf.zeros([1, 1]))

# Logistic Model
pred = tf.nn.sigmoid(tf.matmul(x, W) + b)

# Error function
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred,
                                                              labels=y))

# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

# Initialise global variables
init = tf.global_variables_initializer()
init_l = tf.local_variables_initializer()

# Training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)
    sess.run(init_l)
    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(data.shape[0]/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            # The next_data_batch is a custom made function
            batch_xs, batch_ys = next_data_batch(batch_size,
                                                 data, labels)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, loss], feed_dict={x: batch_xs,
                                                          y: batch_ys})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))

    print("Optimization Finished!")

    # Test model
    prediction = tf.round(tf.sigmoid(pred))
    correct = tf.cast(tf.equal(prediction, y), dtype=tf.float32)
    _, precision = tf.metrics.precision(y, prediction)
    # Calculate accuracy
    accuracy = tf.reduce_mean(correct)
    avg_prec = tf.reduce_mean(precision)
    print("Accuracy:", accuracy.eval({x: test_data, y: test_labels}))
    print("Average Precision Score:", avg_prec.eval({x: test_data, y: test_labels}))

But, even though I get the correct output from the training (Epoch: xxxx cost= 0.xxxx) and from the test set (Accuracy:0.xxx). When the program tries to calculate the precision it returns an error:

FailedPreconditionError (see above for traceback): Attempting to use
  uninitialized value precision/true_positives/count     [[node
  precision/true_positives/AssignAdd (defined at
  :54) ]]

Therefore, the problem is in the final lines that I have added the (_, precision = tf.metrics.precision(y, prediction)). I have tried various suggestions from Stackoverflow posts but nothing has worked. It must be a silly coding mistake but due to my inexperience with Tensorflow I cannot figure out what it is.

A: The lines creating nodes in the tensorflow-graph should be before the 'tf.global_variables_initializer()' statement to be part of the default graph. Move the following lines to above the initializer and it will work:
# Test model
    prediction = tf.round(tf.sigmoid(pred))
    correct = tf.cast(tf.equal(prediction, y), dtype=tf.float32)
    _, precision = tf.metrics.precision(y, prediction)
    # Calculate accuracy
    accuracy = tf.reduce_mean(correct)
    avg_prec = tf.reduce_mean(precision)


text:
Q: Can I control positioning of IE 10 select boxes? In Internet Explorer 10 the behavior of drop-down boxes (<select> element) has changed: when expanding the box, instead of placing the list of options below the field, the list overlays the field, with the list positioned so that the currently-selected element is centered over the input field.
This is a little hard to describe, so here's a jsFiddle that shows it.
Our users are finding this behavior very confusing. Is there anything I can do in CSS to make the box behave like it did in IE9, and like every other major browser? (Perhaps something like the -ms-clear pseudo-element that hides the clear button in IE10 text input fields.)
Here's a sort of time-lapse screenshot:

A: One option is dynamically change size property of the select to the number of options (or a fixed number - if you have too many options). You would do it on mouse-down, and change it back on-change.
Style, Position of select as well as additional events will have to be tweaked - but here is the proof of concept: http://jsfiddle.net/KnAXL/1/


text:
Q: Angular4 - Routing with optional parameters and query parameters In angular4 routing, i am trying navigate to specific path with optional parameters but it not navigating to the correct path, Please see the below code
routes i have configured as
{ path:"login",component:"LoginComponent"},
 {path:"register",component:"RegisterComponent"},
 {path:"**",redirectTo:"register"}

i am routing to login as below
this.router.navigate(["login",{optionalParam:"param"}]) but this is navigating to Register, i could observe in router debugging as url Redirects from "login;optionalParam=param" to "register". what could be the issue, i am facing same issue with queryParameters also.

A: I have done a simple example: https://plnkr.co/edit/F3mfg9jXHZEAyZz6xZjf.
With redirection and query.
let routes: Routes = [
    { path: '', component: MainComponent },
    { path: 'login',component: LoginComponent},
    { path: 'redirection',component: RedirectComponent},
    { path: '**',redirectTo: 'redirection'}
];

and
<a [routerLink]="['/login',{'plop':'pom'}]">go to login with query</a>


text:
Q: Magento 2 : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails When I save records, I got this error message.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails
  (report.vendorname_modulename_entity, CONSTRAINT
  VENDORNAME_MODULENAME_ENTT_ENTT_TYPE_ID_EAV_ENTT_TYPE_ENTT_TYPE_ID
  FOREIGN KEY (entity_type_id) REFERENCES eav_entity_type
  (entity_type_id) ), query was: INSERT INTO
  vendorname_modulename_entity (created_at,updated_at) VALUES
  ('2019-02-26 00:00:00', '2019-02-27 05:12:31')

Save controller file (execute function):
$storeId = (int) $this->getRequest()->getParam('store_id', 0);
$data = $this->getRequest()->getParams();

/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($data) {
    $params = [];
    $model = $this->modelFactory->create();
    $params['store'] = $storeId;
    if (empty($data['entity_id'])) {
        $data['entity_id'] = null;
    } else {
        $model->load($data['entity_id']);
        $params['entity_id'] = $data['entity_id'];
    }
    $model->setData('entity_type_id', 10);
    $model->setData('attribute_set_id', 17);
    $model->setData('store_id', $storeId);
    $model->setData('field_title', $data['field_title']);
    $model->setData('field_url', $data['field_url']);
    $model->setData('field_desc', $data['field_desc']);
    $model->setData('created_at', $this->_dateFactory->create()->date());
    $model->setData('updated_at', $this->_dateFactory->create()->date());

    try {
        $model->save();
        $this->messageManager->addSuccessMessage(__('You saved this record.'));
        $this->_getSession()->setFormData(false);
        if ($this->getRequest()->getParam('back')) {
            $params['entity_id'] = $model->getId();
            $params['_current'] = true;
            return $resultRedirect->setPath('*/*/edit', $params);
        }
        return $resultRedirect->setPath('*/*/');
    } catch (\Exception $e) {
        $this->messageManager->addErrorMessage($e->getMessage());
        $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the record.'));
    }

    $this->_getSession()->setFormData($this->getRequest()->getPostValue());
    return $resultRedirect->setPath('*/*/edit', $params);
}
return $resultRedirect->setPath('*/*/');

How I solve this error?

A: Without the specific code it is a little hard to guess but "unknown entity type" could be because of missing value for the entity type in the resource model you have created or a incomplete / incorrect settings in di.xml
Resource model needs the entity type set - something like this usually in constructor (you checked that, it's there in your case): $this->setType('your_entity_type_code');
"Unknown entity type: VendorName\ModuleName\Model\Mainpage requested" comes from the getMetadata() method in the EntityManagers MetadataPool. The di.xml needs a tag for Magento\Framework\EntityManager\MetadataPool to avoid this error
<type name="Magento\Framework\EntityManager\MetadataPool">
  [....]
  <item name="eavEntityType" xsi:type="string">your_entity_type_code</item>

If the di.xml is correct and you have generated the dependency injection after the changes, we have to look further :-)


text:
Q: Two IDs from same table in query - trying to get names for both IDs I have a couple of tables I'm trying to link together.  One table (tblBrokeragePurchase) has the information regarding a purchase order completed by a customer.  Within that table exists a BuyerID and a SellerID.  Both of those fields link to another table (tblContacts).  I'm wanting to output the full names of both the Buyer and the Seller, but Access is giving me some grief regarding the fields are being used in multiple aspects of my SQL statement.

So far, this is what I've got going on for myself:
SELECT [First Name] & " " & [Last Name] AS BuyerName,
       [First Name] & " " & [Last Name] AS SellerName
FROM   (tblBrokeragePurchase
        LEFT JOIN tblContacts
               ON ( tblBrokeragePurchase.SellerID = tblContacts.ID )
                  AND ( tblBrokeragePurchase.BuyerID = tblContacts.ID ))
       INNER JOIN qryCityLookup
               ON tblBrokeragePurchase.ID = qryCityLookup.ID
WHERE  ( ( [BuyerID] = [ID] )
         AND ( [SellerID] = [ID] ) );

I'm decently sure it has to do with the WHERE statement.  The Buyer and the Seller will not be the same person (generally?).  So where do I need to fix up the JOIN or WHERE statement in my SQL?

A: You have to join to the contact table twice, and use alias to difference between boths
SELECT Buyer.[First Name] & " " & Buyer.[Last Name] AS BuyerName,
       Seller.[First Name] & " " & Seller.[Last Name] AS SellerName
FROM   (tblBrokeragePurchase
        LEFT JOIN tblContacts as Seller
               ON ( tblBrokeragePurchase.SellerID = tblContacts.ID )
        LEFT JOIN tblContacts as Buyer
               ON ( tblBrokeragePurchase.BuyerID = tblContacts.ID )
       INNER JOIN qryCityLookup
               ON tblBrokeragePurchase.ID = qryCityLookup.ID

Now if you are looking for a single ID then the WHERE clausule probably should be
WHERE  ( ( [BuyerID] = [ID] )
         OR ( [SellerID] = [ID] ) );

A: Since your query will be accessing two separate records from the tblContacts table for each record in your tblBrokeragePurchase, the tblContacts record will need to be referenced twice so that two separate records can be obtained by the query simultaneously.
In MS Access, the following should be valid SQL:
select
    b.[First Name] & " " & b.[Last Name] as BuyerName,
    s.[First Name] & " " & s.[Last Name] as SellerName
from
    (
        (
            tblBrokeragePurchase p left join tblContacts s on p.SellerID = s.ID
        )
        left join tblContacts b on p.BuyerID = b.ID
    )
    inner join qryCityLookup c on p.ID = c.ID
where
    p.BuyerID  = [YourBuyerID] and
    p.SellerID = [YourSellerID]

The additional parentheses are used as MS Access requires that each pair of joined tables/queries be surrounded by a separate set of parentheses - I describe the general structure here.


text:
Q: Does the equality $[u, v]=[X, Y](e)$ holds? Let $G$ be a Lie group, $\mathfrak{g}$ its Lie algebra and $\mathfrak{h}\subseteq \mathfrak{g}$ a vector subspace. I defined two smooth vector fields $X, Y:G\rightarrow TG$ setting $X(g)=DR_g(e)u$ and $Y(g)=DR_g(e)v$ where $R_g:G\rightarrow G$ is the right translation and $u, v\in \mathfrak{h}$ are fixed elements. Is it true that $[u, v]=[X, Y](e)$? I need that in a proof but I can't justify it, can anyone help me?

A: Your statement does not hold, but requires only throwing in a minus sign on one side to be repaired. Citing from Wikipedia,

For a Lie group $G$, the corresponding Lie algebra is the tangent space at the identity, which can be identified with the left invariant vector fields on $G$. The Lie bracket of the Lie algebra is then the Lie bracket of the left invariant vector fields, which is also left invariant.

This means that your statement would be true if you had defined $X,Y$ to be left-invariant vector fields with values $u,v$ respectively at the origin, as $X'(g)=DL_g(e)u$ and $Y'(g)=DL_g(e)v$; then $Z'(g)=DL_g(e)[u,v]$ is a left-invariant vector field with value $[u,v]$ et $e$, and according to the cited statement one has $Z'=[X',Y']$, and in particular $[u,v]=Z'(e)=[X',Y'](e)$.
To see that for right-invariant vector fields one has to throw in a minus sign, one may reason that right-invariant vector fields on $G$ are left-invariant vector fields on the opposite group $G^{op}$, which is just $G$ but with multiplication in the opposite order. The Lie bracket $[X,Y]$ of vector fields does not depend on the group structure, but the Lie bracket $[u,v]$ on the Lie group changes sign if we replace $G$ by $G^{op}$ (this is easy to check when the the Lie bracket is given by a commutator).


text:
Q: Overriding rake task fails after upgrading to rails 4 I am trying to upgrade my app from rails 3.2.18 to rails 4.0 and I'm stuck on an issue with rake.
I have a custom doc.rake task that overrides doc:app with the following code inside that worked fine on rails 3:
  # Replace Rails' rake doc:app with ours, which uses yardoc
  Rake::Task["doc:app"].clear.enhance do
    # Uses .yardopts_app file in rails root
    app_dir = 'doc/generated/app'
    sh "rm -rf #{app_dir}"
    sh "bundle exec yardoc --plugin rails --yardopts .yardopts_app"
    app_doc_files_dir = "#{app_dir}/doc-files"
    Dir.mkdir( app_doc_files_dir )
    cp_r( 'doc/files/app/doc-files/.', app_doc_files_dir )
  end

Since upgrading rails, any rake task I try to run fails with the error:
rake aborted!
Don't know how to build task 'doc:app'

I'm really at a loss as to why this is happening. I can't find any reference to rails 4 removing the default doc:app task, so it should still exist for me to overwrite.

A: I was able to solve this by adding
require 'rails/tasks'

to the top of my rake file. So my full rake file looks like this now:
require 'rdoc/task'
require 'rails/tasks'

Rake::Task["doc:app"].clear

namespace :doc do
  RDoc::Task.new('app') do |rdoc|
    ...
  end
end


text:
Q: module 'tkinter' has no attribute 'tkinter'? I'm using Python3, I have a program written in Python2, I converted to Python3 using 2to3 command.
After running the code an error had occurred:
AttributeError: module 'tkinter' has no attribute 'tkinter'
Traceback (most recent call last):
  File "pacman.py", line 679, in <module>
    args = readCommand( sys.argv[1:] ) # Get game components based on input
  File "pacman.py", line 567, in readCommand
    import graphicsDisplay
  File "graphicsDisplay.py", line 15, in <module>
    from graphicsUtils import *
  File "graphicsUtils.py", line 294, in <module>
    def keys_pressed(d_o_e=tkinter.tkinter.dooneevent,
AttributeError: module 'tkinter' has no attribute 'tkinter'


text:
Q: Can training set be used to determine variable importance using randomForest in R although the prediction of testing set is quite low? I am using randomForest in R, I have a training model with R^2 of 0.94 , however , the prediction capacity for testing data is quite low. I would like to know if I can still use this training model only for determining which variable is more important/effective for output prediction.
Thanks

A: Based on what little information you provide, the question is hard to answer (think about providing more detail and background). Low prediction quality can result from wrong algorithm tuning, or it can be inherent in the data, i.e. your predictors themselves are not very strongly related to the outcome. In the first case, the prediction could be better with different parameters, e.g. more or less trees, different values for mtry, etc. If this is the case, then your importance measures are just as biased as your prediction (and should be used with caution). If the predictors themselves are weak, that means that your low quality prediction is as good as it gets. In this case, I would say the importance measures can be used, but they only tell you which of your overall weak predictors are more or less weak.


text:
Q: Webpack error due to ES2015 template literal - "Unterminated string constant" I'm trying make a Relay.QL call with a ES2015 template literal as per the documentation but Webpack is not happy with it.
This is the file that contains the Relay.QL call:
import React from "react";
import ReactDOM from "react-dom";
import Relay from "react-relay";
import Main from "./components/Main";

ReactDOM.render(<Main />, document.getElementById('react'));

console.log(
    Relay.QL'
        {
            links {
                title
            }
        }
        '
);

And this is the Webpack error:
ERROR in ./js/app.js
Module build failed: SyntaxError: C:/websites/rgrjs/js/app.js: Unterminated string constant (11:12)
   9 |
  10 | console.log(
> 11 |     Relay.QL'
     |             ^
  12 |         {
  13 |             links {
  14 |                 title
    at Parser.pp.raise (C:\websites\rgrjs\node_modules\babylon\index.js:1413:13)

It looks like Webpack doesn't like the ES2015 template literal used by Relay.QL?
I've included ES2015 options in my webpack.config.js file as follows:
       query: {
            presets: ['react', 'es2015', 'stage-0'],
            plugins: ['./babelRelayPlugin']
        }

And finally the .babelRelayPlugin file looks like this:
// `babel-relay-plugin` returns a function for creating plugin instances
var getBabelRelayPlugin = require('babel-relay-plugin');

// load previously saved schema data (see "Schema JSON" below)
var schemaData = require('./data/schema.json').data;

module.exports = getBabelRelayPlugin(schemaData);

Is there something else I need to do?  I'm new to Relay and ES2015, so I'm probably missing something obvious.

A: Template literals are denoted with backticks, not quotation marks.
Relay.QL`...`

If you look more closely at the example you will notice that they are using backticks as well:
var fragment = Relay.QL`
  fragment on User {
    name
  }
`;


text:
Q: JavaScript regular expression mobile phone number

*

*XXX-XXX-XXXX

*XXXXXXXXXX

  I want to use a regular expression of the format. I tried as shown
  below, and an error occurs. How do I fix it?

*

*sample
var regExp = / ^ 01 ([0 | 1 | 6 | 7 | 8 | 9]?) - ([0-9] {3}) - ([0-9] {4}) $ /??;

*sample
var regExp = / ^ 01 ([0 | 1 | 6 | 7 | 8 | 9]?) ([0-9] {3}) ([0-9] {4}) $ /??;

A: sample 1
var regExp = /^01([016789]?)-([0-9]{3})-([0-9]{4})$/;

sample 2
var regExp = /^01([016789]?)[0-9]{3}[0-9]{4}$/;

just make sure you don't have spaces and remove | from [0|1|6|7|8|9]