Q: Oauth2 and YouTube - what am I doing wrong? I've been working on this unsuccessfully for a long time now.  The YouTube developer examples seem straightforward enough, but I always meet the same two errors:
Access is Denied (when running on IIS)
Or
redirect_uri_mismatch (When running in Visual Studio)
This is the code that always fails for me:
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
  {
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        // This OAuth 2.0 access scope allows an application to upload files to the
        // authenticated user's YouTube channel, but doesn't allow other types of access.
        new[] { YouTubeService.Scope.YoutubeUpload },
        "user",
        CancellationToken.None
    );
  }

I have:
- Updated the clients_secret and used it with the Javascript version, so I'm fairly sure that isn't the issue
- Tried to create a custom FileDataStore to add as another parameter
Here is more detail to the Access Denied error I get when debugging.  It appears as soon as I get to the "credential" line.

at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
     at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext() in c:\ApiaryDotnet\default\Src\GoogleApis.Auth.DotNet4\OAuth2\GoogleWebAuthorizationBroker.cs:line 59
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
     at _Default.d__1.MoveNext() in c:\Users\Michael\documents\visual studio 2015\websites\website1\Default.aspx.cs:line 46

And this is what shows up in the properties for the credential right before it errors out:

ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
  WriteTimeout = 'stream.WriteTimeout' threw an exception of type 'System.InvalidOperationException'  int {System.InvalidOperationException}


Q: How to put constraints on HTML form inputs?
I have a form that looks like this.
What I want to do is, I want to make sure that Minimum Age < Maximum Age
and Minimum Skill Level < Maximum Skill Level
What is a way to put constraints on the inputs?
HTML
{% extends "template.html" %}
{% set active_page = "events" %}
{% block content %}

EVENTS PAGE

Click here to go to the welcome page

    <form action = "/events_success" method=post>
      Event Name:

      <input type="text" name="eventname" required="">

      Sports:

      <select name="sports">
       {% for item in sports_data %}
         <option value="{{ item[0] }}">{{ item[0] }}</option>
       {% endfor %}
     </select>

     Location:

      <select name="location">
       {% for item in loc_data %}
         <option value="{{ item[0] }}">{{ item[0] }}</option>
       {% endfor %}
     </select>

      Time:

        <input type="datetime-local" name="time" required>

      Number of Players:

      <input type="text" name="numplayers" required>

      Minimum Age:

      <input type="text" name="minage" required>

      Maximum Age:

      <input type="text" name="maxage" required>

      Minimum Skill Level:

      <input type = "radio" name = "minskill" value = "1" required> 1
      <input type = "radio" name = "minskill" value = "2"> 2
      <input type = "radio" name = "minskill" value = "3"> 3
      <input type = "radio" name = "minskill" value = "4"> 4
      <input type = "radio" name = "minskill" value = "5"> 5

      Maximum Skill Level:

      <input type = "radio" name = "maxskill" value = "1" required> 1
      <input type = "radio" name = "maxskill" value = "2"> 2
      <input type = "radio" name = "maxskill" value = "3"> 3
      <input type = "radio" name = "maxskill" value = "4"> 4
      <input type = "radio" name = "maxskill" value = "5"> 5

      Creator: {{ session['username'] }}

      <input type="submit" value="Send">
    </form>

{% endblock %}

A: You can just try some javaScript to prevent the form submission if those fields fails to fulfill that condition. Please check my demo.
**Note: It's just a demo. That's why didn't put any authentication.

window.onload = function() {
    let submit = document.querySelector("#submit");

    function validateAge(minAge, maxAge) {
        let min = parseInt(minAge, 10);
        let max = parseInt(maxAge, 10);
        return min >= max ?  false :  true;
    }
    function validateSkill(minSkill, maxSkill) {
        let min = parseInt(minSkill, 10);
        let max = parseInt(maxSkill, 10);
        return min >= max ?  false :  true;
    }

    submit.onclick = function() {
        let minAge = document.querySelector("#minage").value;
        let maxAge = document.querySelector("#maxage").value;
        let radios = document.querySelectorAll('input[type="radio"]:checked');
        let minSkill = radios[0].value;
        let maxSkill = radios[1].value;

        if(validateAge(minAge, maxAge) && validateSkill(minSkill, maxSkill))
            return  true;
        else {
            alert("Invalid data");
            return false;
        }
    }

}
    <form id="myForm" action = "/events_success" method=post >

      Minimum Age:

      <input type="text" name="minage" id="minage" required>

      Maximum Age:

      <input type="text" name="maxage" id="maxage"  required>

       Minimum Skill Level:

      <input type = "radio" name = "minskill" value = "1" required> 1
      <input type = "radio" name = "minskill" value = "2"> 2
      <input type = "radio" name = "minskill" value = "3"> 3
      <input type = "radio" name = "minskill" value = "4"> 4
      <input type = "radio" name = "minskill" value = "5"> 5

      Maximum Skill Level:

      <input type = "radio" name = "maxskill" value = "1" required> 1
      <input type = "radio" name = "maxskill" value = "2"> 2
      <input type = "radio" name = "maxskill" value = "3"> 3
      <input type = "radio" name = "maxskill" value = "4"> 4
      <input type = "radio" name = "maxskill" value = "5"> 5

      <input type="submit" value="Send" id="submit">
    </form>

A: You can use some common PHP validation techniques. These are more beneficial as less risky to injection and other exploits.
PHP:
  if (empty($_POST["code"])) {
    $errcode = "Verify that you're human";
  } else {
    $code = test_input($_POST["code"]);
    if (!$_POST['code'] < $string) {
      $errcode = "Make code greater than string";
    }
  }

HTML:

Scrambled code:  <input type="text" name="code" id="code" />  * <?php echo $errcode;?>


Q: CouchDB backup into S3 in json format I am checking ways to back up CouchDB records for all databases. The docs suggest to either use replication to a new CouchDB instance or simply copy the .couch files. But .couch files cannot be read by a text editor and we want to export records to json format and put it to S3.
I found curl can be used to retrieve data in json
curl -X GET http://127.0.0.1:5984/[mydatabase]/_all_docs?include_docs=true > /Users/[username]/Desktop/db.json

Is there a way to

*

*Split it into json files of say 10,000 records each so that if the DB is huge and there's a failure at Y record I can resume it from the batch that includes Y

*Run the _all_docs on all databases that exist instead of running it individually for each database?

If there's an alternative to curl I'd be happy to try use that as well


Q: How to Correctly Cancel a TPL Task with Continuation I have a long running operation which I am putting on a background thread using TPL. What I have currently works but I am confused over where I should be handling my AggregateException during a cancellation request.
In a button click event I start my process:
private void button1_Click(object sender, EventArgs e)
{
    Utils.ShowWaitCursor();
    buttonCancel.Enabled = buttonCancel.Visible = true;
    try
    {
        // Thread cancellation.
        cancelSource = new CancellationTokenSource();
        token = cancelSource.Token;

        // Get the database names.
        string strDbA = textBox1.Text;
        string strDbB = textBox2.Text;

        // Start duplication on seperate thread.
        asyncDupSqlProcs =
            new Task<bool>(state =>
                UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB),
                "Duplicating SQL Proceedures");
        asyncDupSqlProcs.Start();

        //TaskScheduler uiThread = TaskScheduler.FromCurrentSynchronizationContext();
        asyncDupSqlProcs.ContinueWith(task =>
            {
                switch (task.Status)
                {
                    // Handle any exceptions to prevent UnobservedTaskException.
                    case TaskStatus.Faulted:
                        Utils.ShowDefaultCursor();
                        break;
                    case TaskStatus.RanToCompletion:
                        if (asyncDupSqlProcs.Result)
                        {
                            Utils.ShowDefaultCursor();
                            Utils.InfoMsg(String.Format(
                                "SQL stored procedures and functions successfully copied from '{0}' to '{1}'.",
                                strDbA, strDbB));
                        }
                        break;
                    case TaskStatus.Canceled:
                        Utils.ShowDefaultCursor();
                        Utils.InfoMsg("Copy cancelled at users request.");
                        break;
                    default:
                        Utils.ShowDefaultCursor();
                        break;
                }
            }, TaskScheduler.FromCurrentSynchronizationContext()); // Or uiThread.

        return;
    }
    catch (Exception)
    {
        // Do stuff...
    }
}

In the method DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true) I have
DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true)
{
    try
    {
        for (int i = 0; i < someSmallInt; i++)
        {
            for (int j = 0; j < someBigInt; j++)
            {
                // Some cool stuff...
            }

            if (_token.IsCancellationRequested)
                _token.ThrowIfCancellationRequested();
        }
    }
    catch (AggregateException aggEx)
    {
        if (aggEx.InnerException is OperationCanceledException)
            Utils.InfoMsg("Copy operation cancelled at users request.");
        return false;
    }
    catch (OperationCanceledException)
    {
        Utils.InfoMsg("Copy operation cancelled at users request.");
        return false;
    }
}

In a button Click event (or using a delegate (buttonCancel.Click += delegate { /Cancel the Task/ }) I cancel theTask` as follows:
private void buttonCancel_Click(object sender, EventArgs e)
{
    try
    {
        cancelSource.Cancel();
        asyncDupSqlProcs.Wait();
    }
    catch (AggregateException aggEx)
    {
        if (aggEx.InnerException is OperationCanceledException)
            Utils.InfoMsg("Copy cancelled at users request.");
    }
}

This catches the OperationCanceledException fine in method DuplicateSqlProcsFrom and prints my message, but in the call-back provided by the asyncDupSqlProcs.ContinueWith(task => { ... }); above the task.Status is always RanToCompletion; it should be cancelled!
What is the right way to capture and deal with the Cancel() task in this case. I know how this is done in the simple cases shown in this example from the CodeProject and from the examples on MSDN but I am confused in this case when running a continuation.
How do I capture the cancel task in this case and how to ensure the task.Status is dealt with properly?

A: You're catching the OperationCanceledException in your DuplicateSqlProcsFrom method, which prevents its Task from ever seeing it and accordingly setting its status to Canceled. Because the exception is handled, DuplicateSqlProcsFrom finishes without throwing any exceptions and its corresponding task finishes in the RanToCompletion state.
DuplicateSqlProcsFrom shouldn't be catching either OperationCanceledException or AggregateException, unless it's waiting on subtasks of its own. Any exceptions thrown (including OperationCanceledException) should be left uncaught to propagate to the continuation task. In your continuation's switch statement, you should be checking task.Exception in the Faulted case and handling Canceled in the appropriate case as well.
In your continuation lambda, task.Exception will be an AggregateException, which has some handy methods for determining what the root cause of an error was, and handling it. Check the MSDN docs particularly for the InnerExceptions (note the "S"), GetBaseException, Flatten and Handle members.

EDIT: on getting a TaskStatus of Faulted instead of Canceled.
On the line where you construct your asyncDupSqlProcs task, use a Task constructor which accepts both your DuplicateSqlProcsFrom delegate and the CancellationToken. That associates your token with the task.
When you call ThrowIfCancellationRequested on the token in DuplicateSqlProcsFrom, the OperationCanceledException that is thrown contains a reference to the token that was cancelled. When the Task catches the exception, it compares that reference to the CancellationToken associated with it. If they match, then the task transitions to Canceled. If they don't, the Task infrastructure has been written to assume that this is an unforeseen bug, and the task transitions to Faulted instead.
Task Cancellation in MSDN

A: Sacha Barber has great series of articles about TPL. Try this one, he describe simple task with continuation and canceling


Q: mysql query slow with joins upon enabling the slow_query_log in mysql. I found that the query below was one of slowest query with 15 secs or more. How can I optimize this query. All tables are Innodb and
server: Server version: 5.6 Thank you
    EXPLAIN EXTENDED SELECT
    ntv_staffs.fname,
    ntv_staffs.id,
    ntv_staffs.mname,
    ntv_staffs.profile_pic,
    ntv_staffs.lname,
    ntv_staff_office.cug,
    ntv_staff_office.extension,
    ntv_staff_office.off_email,
    ntv_staff_office.job_title,
    ntv_designations.`name` as designation_name,
    ntv_branches.`name` as branch_name,
    ntv_departments.`name` as department_name,
    ntv_departments.id as department_id
    FROM
    ntv_staffs
    INNER JOIN ntv_staff_office ON ntv_staffs.id = ntv_staff_office.pid
    INNER JOIN ntv_departments ON ntv_staff_office.department_id = ntv_departments.id
    INNER JOIN ntv_branches ON ntv_staff_office.branch_id = ntv_branches.id
    INNER JOIN ntv_designations ON ntv_staff_office.designation = ntv_designations.id
    where ntv_staffs.id='662';

+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
| id | select_type | table            | type   | possible_keys | key     | key_len | ref                                          | rows | filtered | Extra       |
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
|  1 | SIMPLE      | ntv_staffs       | const  | PRIMARY       | PRIMARY | 4       | const                                        |    1 |   100.00 |             |
|  1 | SIMPLE      | ntv_staff_office | ALL    | NULL          | NULL    | NULL    | NULL                                         |  247 |   100.00 | Using where |
|  1 | SIMPLE      | ntv_branches     | eq_ref | PRIMARY       | PRIMARY | 4       | abc_portal_new.sks_staff_office.branch_id     |    1 |   100.00 |             |
|  1 | SIMPLE      | ntv_designations | eq_ref | PRIMARY       | PRIMARY | 4       | abc_portal_new.sks_staff_office.designation   |    1 |   100.00 | Using where |
|  1 | SIMPLE      | ntv_departments  | eq_ref | PRIMARY       | PRIMARY | 4       | abc_portal_new.sks_staff_office.department_id |    1 |   100.00 |             |
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+

A: Try setting a btree-index for ntv_staff_office.pid.


Q: How can I get the output of a Timed Out command by subprocess.check_output()? I'm trying to run some commands using the python library subprocess. Some of my commands might get stuck in loops and block the python script. Therefore I'm using check_output() with a timeout argument to limit the commands in time. When the command takes too much time, the function raise a TimeoutExpired error. What I want to do is get what the command has been able to run before being killed by the timeout.
I've except the error and tried "except sp.TimeoutExpired as e:". I read on the doc that if I do e.output it should give me what I want. "Output of the child process if this exception is raised by check_output(). Otherwise, None.". However I don't get anything in the output.
Here is what I did:
import subprocess as sp
try:
        out = sp.check_output('ls', stderr=sp.STDOUT, universal_newlines=True, timeout=1)
except sp.TimeoutExpired as e:
        print ('output: '+ e.output)
else:
        return out

Let say the folder I'm working with is huge and so 1 second isn't enough to ls all its files. Therefore the TimeoutExpired error will be raised. However, I'd like to store what the script was able to get at least. Does someone have an idea?

A: Found a solution, posting it here in case someone is interested.
In Python 3, the run method allows to get the output.
Using the parameters as shown in the example, TimeoutExpired returns the output before the timeout in stdout:
import subprocess as sp

for cmd in [['ls'], ['ls', '/does/not/exist'], ['sleep', '5']]:
    print('Running', cmd)
    try:
        out = sp.run(cmd, timeout=3, check=True, stdout=sp.PIPE, stderr=sp.STDOUT)
    except sp.CalledProcessError as e:
        print(e.stdout.decode() + 'Returned error code ' + str(e.returncode))
    except sp.TimeoutExpired as e:
        print(e.stdout.decode() + 'Timed out')
    else:
        print(out.stdout.decode())

Possible output:
Running ['ls']
test.py

Running ['ls', '/does/not/exist']
ls: cannot access '/does/not/exist': No such file or directory
Returned error code 2
Running ['sleep', '5']
Timed out

I hope it helps someone.


Q: How to set text dynamically to texbox in vba? Dear Fellow StackOverFlow-members,
I try to dynamically create texboxes in a userform and set default text depending on value from a tab.
First the user fill in textboxes like in the photo
When he clicks the button above, it calls the function that create textboxes in the same userform. Exactly as much as the total of values of the textboxes, futhermore for value "0" it counts as 1 textbox to add.
What I want is when it encounters 0 value I want the new texbox created to set defaut text as "null". Like so :
My code :
For i = 0 To UBound(tabValTextBox)
            valTemp = tabValTextBox(i)
            If valTemp = 0 Then
                iTextBoxMasqueA = iTextBoxMasqueA + 1
                Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
                colTextBoxCableA.Add textBoxCableA
                With textBoxCableA
                    .Name = "cable" & iTextBoxCableA
                    .Top = iTextBoxCableA * textBoxCableA.Height + 50
                    .Left = 150
                    .Text = "Nul"
                End With
            Else
                For j = 0 To valTemp - 1
                    iTextBoxCableA = iTextBoxCableA + 1
                    Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
                    colTextBoxCableA.Add textBoxCableA
                    With textBoxCableA
                        .Name = "cable" & iTextBoxCableA
                        .Top = iTextBoxCableA * textBoxCableA.Height + 50
                        .Left = 150
                    End With
                Next j

            End If
        Next i

 tabValTextbox() is a tab containing the values of the left textboxes.
However the result I get looks like this  :    I don't get as much textboxes as expected.
I don't understand where I'm missing something. I want to learn from this, so if possible, explain me what I'm doing wrong here, or if my approach is lacking insight.

A: Try this:
For i = 0 To UBound(tabValTextBox)
    valTemp = tabValTextBox(i)
    iTextBoxCableA = iTextBoxCableA + 1
    If valTemp = 0 Then
        Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
        colTextBoxCableA.Add textBoxCableA
        With textBoxCableA
            .Name = "cable" & iTextBoxCableA
            .Top = iTextBoxCableA * textBoxCableA.Height + 50
            .Left = 150
            .Text = "Nul"
        End With
    Else
        For j = 0 To valTemp - 1
            Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
            colTextBoxCableA.Add textBoxCableA
            With textBoxCableA
                .Name = "cable" & iTextBoxCableA
                .Top = iTextBoxCableA * textBoxCableA.Height + 50
                .Left = 150
            End With
        Next j
    End If
Next i

I've moved the iTextBoxCableA increment outside of the zero condition, and removed the iTextBoxMasqueA increment entirely as you weren't using it.
I can't test this myself but I think it'll sort the problem of overlapping out.


Q: Azure AD B2C Application won't show up as an option to add role assignment. (Graph API) I'm following this documentation:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/microsoft-graph-get-started?tabs=app-reg-ga
And I found another question answered that I thought fit my case:
https://learn.microsoft.com/en-us/answers/questions/199433/can39t-add-role-assignments-to-azure-b2c-applicati.html
My problem is that the app that I registered will not appear as an option when I try to follow the "Enable user delete and password update" portion of the documentation.
I am also mindful of the notice "Please allow a few minutes to for the permissions to fully propagate." But I've at it for 2 hours now, so I don't think that is the problem.
Here is my App and its API permissions:

And my B2C Tenant:

A: Microsoft has answered this question on this thread as follows:
Hi All · Thank you for reaching out.
There seems to be an issue with the UI. I will report the issue to the product team and get it addressed.
However, as of now, you can follow below steps and use PowerShell to add application to the User Administrator role:

*

*Install latest Azure AD PowerShell Module.

*Run Connect-AzureAD -TenantId Your_B2CTenant.onmicrosoft.com and sign in with Global Administrator account in that tenant.

*Run Get-AzureADDirectoryRole cmd and copy the object id of the User Administrator role.

*Navigate to Azure AD > Enterprise Applications > Search the app and copy the object id of the app.

*Run Add-AzureADDirectoryRoleMember -ObjectId object_ID_copied_in_Step3 -RefObjectId object_ID_copied_in_Step4 cmdlet.
To verify, navigate to Azure AD B2C > Roles and Administrators > User Administrator. You should see the application present under this role


Q: Is such an iOS model possible to implement? I would like to do the following:

*

*Sell a game for $0.99 at launch with no feature restrictions.

*If it's less than successful, make it free, but limit some features to in-app purchase (I would do this via an update to the existing app).

*BUT, I would like users who originally purchased the app (before it was free) to still have all of the features.  In other words, I want to find a way to credit the new in-app purchases to those users, so that they don't have to pay twice.

I would like to do this all with the existing app, instead of making two separate versions of the app (paid and free).
EDIT: it is essential that not a single user ever have to pay twice (i.e. that users who previously paid for the app, do not have to purchase the in-app upgrades in the future).
EDIT 2: It seems like this question has already been answered here: From Paid to FREE w/IAP: Preventing double-charging

A: Certainly.
The company I work for has done this in the past.
If you know you might want to do this in the future, in your first version store a flag to NSUserDefaults indicating that the user has had the paid version. Then, on your In-App version check this flag and provide the content immediately.
If you already have a version released, you may have to look for something that you are already storing, e.g. the user has a highscore greater than zero to indicate that the user has already purchased the app. (There will be a small number of users that may have downloaded the app but not opened it and these users may be charged twice).

A: Yeah, it is. Before you Update your app with FREE version, you add all users that have paid for it serial number "PAID"(or something), and everything else is just conditional statements(if-else). Congrats!


Q: Add unique ID to containing div of file input thumbnail image I have thumbnail previews of a users selected images prior to upload. It will also allow a user to re-arrange the order of the images using jQuery UI. I want to track the order of the images by adding a unique ID to each thumbnails containing div, but I am not able to generate a unique ID. See Code below. Ideally I would like the div ID to match the image name, so then after the form post I use it to match to the filename in the IEnumerable<HttpPostedFileBase>. For example, if the uploaded image is called pic1.jpg, the div containing the thumbnail would be
. The line in question would seem to be div.id = File.name, but I am unable to generate a unique ID of any kind?
CODE
//jQuery UI sort
$(function () {
  $("#upload-thumbnails").sortable();
  $("#upload-thumbnails").disableSelection();
});
//Thumbnail preview
jQuery(function ($) {
  var filesInput = document.getElementById("ImageUploads");

  filesInput.addEventListener("change", function (event) {

var files = event.target.files; //FileList object
var output = document.getElementById("upload-thumbnails");

for (var i = 0; i < files.length; i++) {
  var file = files[i];

  var picReader = new FileReader();

  picReader.addEventListener("load", function (event) {

    var picFile = event.target;

    var div = document.createElement("div");
    div.id = File.name;
    div.innerHTML = "Remove";

    output.insertBefore(div, null);
    div.children[1].addEventListener("click", function (event) {
      div.parentNode.removeChild(div);
    });

  });

  //Read the image
  picReader.readAsDataURL(file);
}

});
});

A: In most cases while we uploading images we rename them as the time stamp because of the uniqueness. But for searching, dealing with time stamp is much harder, then add a class name of the div as the file name.
...
var div = document.createElement("div");
div.id = Date.now();
div.className += ' ' + File.name;
...

I am sure this will be help full.
Thanks

A: Not sure I get the question :)
Try instead:
$(div).attr('id', 'yourIDHere')

Or you never use your defined var file , could it not be?
div.id = file.name;

You can generate UUIDs via JS see here


Q: Improving JavaScript path finding algorithm I'm working on an HTML/JavaScript flowchart designer similar to Visual Studio flowchart designer. One of the most fascinating features of VS flowchart designer, is its intelligent path creation algorithm, I think there should be a powerful path finding algorithm behind the scenes (something like A* for example).
I've implemented a path finding algorithm (a simple version of A*) in my application which tries to find a path between my source and destination nodes. Although it is generating the expected results, but it is really poor in terms of performance and speed, as it takes a long calculation time (in fact the calculation time increases as the path gets longer).
What are your suggestions for improving the performance? Do you know how Visual Studio is finding the path so quickly?


Q: Javascript Design Pattern Prototype error for web3.js Don't know what I am doing wrong, created a javascript prototype for a web3js application I am working on. When I try calling the function in the prototype it is not seeing the function in it. Throwing "persona.testing() is not a function" when I check the console.log.
Web3 = require('web3');

if(typeof web3 != "undefined")
    web3 = new Web3(web3.currentProvider);
     else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
     }

var initweb3 = function(address,abi) {
        this.address = address,
        this.abi = abi;
        this.contract;
        web3.eth.defaultAccount = web3.eth.accounts[0];
        this.contract = web3.eth.contract(this.abi);
        this.contract = this.contract.at(this.address);
 }

var paddress = "0x0",
    pabi = "",

    maddress = "",
    mabi = "";
    persona = new initweb3(paddress,pabi);
    //minion = new initweb3(maddress,mabi);

persona.prototype = {

testing: function(){
  console.log('Yes, I know');
},

testing1: function(){
  console.log('No, I don't');
}
};

persona.testing();

A: You could use Object.assign
persona = Object.assign({}, persona, {
  testing: function(){
    console.log('Yes, I know');
  }
});

or
persona.prototype.testing = function(){};

A: You should use prototype when you want to create one or more instances of a function.
in your case initweb3 is a constructor function.
make sure your constructor function starts with uppercase letter.
For example:
  function Person(){ /*...*/ }
  Person.prototype.sayHi = function() { };

  const p = new Person();
  p.sayHi();

in your use case persona is already an instance object, if you want to add a new function to it you simply do persona.testing = function() {}
OR
You can also try extending the initweb3 function.
initweb3.prototype.testing = function(){ /* code goes here */}
.
.
.
persona.testing();

Watch this video to learn more about prototypes in JavaScript.
https://www.youtube.com/watch?v=riDVvXZ_Kb4


Q: Page breaks on php tag The following code is written in php file and breaks page
<?php

$myrows1=cpabc_player_plan();

foreach ($myrows1 as $index=>$item1) //start foreach party plan
{
    if ($item1 === reset($myrows1))
    {}
?>

<?php }?>

while if I use it as
<?php
$myrows1=cpabc_player_plan();

foreach ($myrows1 as $index=>$item1) //start foreach party plan
{
  if ($item1 === reset($myrows1))
    {}
}?>

then it works fine.

A: You can use foreach():  endforeach Block like this:
<?php foreach ($myrows1 as $index=>$item1): ?>

 some html tags

   <?php
     if ($item1 === reset($myrows1))
       {}
   ?>

 some html tags

<?php endforeach; ?>

for other php statements you can read this page.


Q: Make Syntastic close just the error window I've got the (Mac)Vim Syntastic plugin installed via Janus. When I open the :Errors window to view the reason for syntax errors, it shrinks the file with the errors to one line and uses the rest of the real estate for the Errors window.
Is there a way to make it hog less room for errors and more importantly, how do I close just the Errors window?  The usual :q closes both the Errors window AND the original file, even if the cursor is in the Errors window.  (That's not 100% correct -- it gratefully does not close the file if the file hasn't yet been saved).

A: Syntastic uses the location list (a window-local variant of the quickfix list), so a :lclose will close it, but keep the other buffers.
As per syntastic's help pages, the initial height can be configured:
:let g:syntastic_loc_list_height=5

But I suspect that your intrusive Janus distribution has a hand in that. Vim "distributions" like spf-13 and Janus lure you with a quick install and out of the box settings, but you pay the price with increased complexity (you need to understand both Vim's runtime loading scheme and the arbitrary conventions of the distribution) and inflexibility (the distribution may make some things easier, but other things very difficult). Vim is incredibly customizable, using someone else's customization makes no sense.

A: Syntastic gets confused when you're juggling multiple buffers on one screen so here's a script that will collect information about the situation, then do the right thing:
function JustCloseSyntasticWindow()
    "Check which buffer we are in, and if not, return to the main one:
    if &ft == "qf"
        normal ZZ
    endif
    "Since different buffers have different command spaces, check if we've
    "escaped the other buffer and then tell syntastic to stop.
    if &ft != "qf"
       SyntasticReset
       " --- or ----
       SyntasticToggleMode
    endif
endfunction

au FileType buffer1_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>

au FileType main_win_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>

Don't be shy on the duct tape for this job, it's the only thing holding the unit together.

A: The command to close the Syntastic error window is:
:SyntasticReset

A: You can use :lclose to close it.


Q: VSCode, typescript, eslint and prettier -> null check does not work I've tried to setup typescript linting to use prettier and while prettier works, i seem to have lost the basic typescript error checking. How can i get this back?

^ should complain about accessing .value on foo?
My tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "baseUrl": "./src",
    "allowSyntheticDefaultImports": true,
    "paths": {
      "~/*": ["./*"]
    }
  },
}

.eslintrc.json
{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended"
  ],
  "plugins": ["@typescript-eslint", "prettier"],
  "env": {
    "browser": true,
    "jasmine": true,
    "jest": true,
    "es6": true
  },
  "rules": {
    "prettier/prettier": [
      "error",
      { "singleQuote": true, "semi": false }
    ],
    "@typescript-eslint/no-use-before-define": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/class-name-casing":  ["error", { "allowUnderscorePrefix": true }],
    "@typescript-eslint/interface-name-prefix": ["error", { "prefixWithI": "always", "allowUnderscorePrefix": true}],
    "@typescript-eslint/no-unused-vars": ["error", { "args": "none"}],
    "@typescript-eslint/no-non-null-assertion": "off",
    "semi":"off"
  },
  "parser": "@typescript-eslint/parser"
}


Q: Music and Sound Effects How to separate on and off(i mean how to mute separate ) function of Music Background and Sound Effect
AudioManager
public Sound[] sounds;

public static AudioManager instance;

void Awake()
{
    if (instance == null)
        instance = this;
    else
    {
        Destroy(gameObject);
        return;
    }

    DontDestroyOnLoad(gameObject);

    foreach (Sound s in sounds)
    {
        s.source = gameObject.AddComponent<AudioSource>();
        s.source.clip = s.clip;

        s.source.volume = s.volume;
        s.source.loop = s.loop;
        s.source.mute = s.mute;
    }
}

Sound.cs
public string name;
public AudioClip clip;

[Range(0f, 1f)]
public float volume;

public bool loop;
public bool mute;

[HideInInspector]
public AudioSource source;

This is my Music and Sound Effects


Q: Set variable while foreach loop is working I have foreach loop that copies files.
I want to set label to "Working.." while the foreach loop is copying the files.
I have tried:
label.text = "Ready";
foreach (file in files)
{
    File.Copy(firstDest, secondDest);
    label.text = "Working..";
}
label.text = "Ready";

But the label never changes even when it's copying the files for a while 2-3 seconds.
Do you know how to solve this? Thanks!

A: You should do your copy operation in another thread.
 label.text = "Ready";
var tasks = Task[files.length];

for (var i=0 ; i<files.length; i++) {
    tasks[i] = Task.Run(()=>{
        File.Copy(firstDest, secondDest);
    });
}

label.text = "Working..";
await Task.WhenAll(tasks);
label.text = "Ready";

In case you want to run it all in one task and not each copy in parallel
label.text = "Ready";

var task =Task.Run(()=>{
foreach (file in files){
      File.Copy(firstDest, secondDest);

}
});

label.text = "Working..";
await task;
label.text = "Ready";


Q: Is there a way in Javascript/Angular to subscribe to a 'request sent' event hook? I'm wondering if there's a way in a Javascript/Angular application to hook into a 'request-sent' event emitted by the browser immediately after it sends off a request. The purpose is that we want to ensure/control the order of the requests that go out, and we were thinking of sending each one out in response to the previous one emitting a 'request sent' event (this way we ensure the most important requests get out first). We want to allow the requests to run asynchronously/simultaneously so we don't have the option of waiting for one request to return before sending the next one. We want to send each request as soon as we know the previous one was successfully sent.
The challenge with this is that the order in which the requests are sent in the code does not match the order we see in the Chrome network tab, so we can't rely on the sequences of events that run in the code to guarantee that the same sequence will be followed when the browser sends the requests.
This is why it would be really convenient if we could hook into a 'request sent' event fired from the browser or something of that sort. That would ensure that all requests can still go out asynchronously while also controlling the order in which they go out.
Thanks for any forthcoming help.

A: If you want to maintain the order of api calls, you can user switchMap operator.
let's say that you have two api calls:
const apiCall1$ = this.http.get("/endpoint1");
const apiCall2$ = this.http.get("/endpoint2");

and you want to wait for apiCall1 to finish before sending apiCall2, you can do it like this:
apiCall1$.pipe(switchMap(() => apiCall2$)).subscribe({
    next: (response) => {
        //do something...
    }
});


Q: Getting checkbox values in angularjs and passing them into another controller I am transitioning from jquery to angularjs. I am trying to develop a small app in SPA style. Left side is the menu that controls the content on the right side. Left side menu has its own controller. When the user selects a checkbox and clicks on 'Go', the checkbox value should be passed to the controller that controls the right side content. Here is the link to the app. Below are the issues I have.
1)I am stumped on a simple problem of accessing checked values of a checkbox. How do I access values of checked checkboxes. The checboxes are on left side menu, and I am using ng-model to currently access the values as below
index.html

          <input type="checkbox" name="firstSearch" id="firstSearch_{{searchOneCB.code}}" ng-model="main.selected[searchOneCB.code]" />
{{searchOneCB.description}}

      <button class="btn btn-primary" style="width:80px;margin-right: 10px" ng-click="main.submit()">
          Go
      </button>

MainCtrl.js to access the checkbox value.
main.submit = function() {
  console.log(main.selected);
}

The values are now in the form of an array as below
[BBBB: true, AAAA: true].

Is this the right way to access the values? What is the best way to retrieve only the checked checbox values?
2) Another question is, once I get the list of checked checkboxes values, how can I pass them to the contentCtrl.js that controls the content on right side?

A: You should inject the controller into the controller you want to use. The answer has already been answered here is the link.
How do I inject a controller into another controller in AngularJS


Q: ASP.Net MVC in shared hosting environment It's a very simple question, but I wasn't able to find exact answer.
Do you need to install anything extra besides .Net Framework 3.5 and IIS7 to run ASP.Net MVC applications?
Hope it will be useful to other people too.

A: If you don't use any third party libraries, then no.
The host has to have the .NET 3.5 SP1 installed.
However you need to be aware of the trust level issues. Most shared hosts run in medium trust mode. Although this will suffice for the MVC itself, it may not for your other code. If you use reflection for example, you will need the full trust enabled.
Basically this simple code may get you into trouble:
object something = 5;

if (something is int)
{
    // Do something
}

Check your code and choose the host wisely.


Q: When using oracle-jdk17 and gson 2.10, there is an issue that private time cannot be converted The following error occurred when using gson for conversion；
 Unable to make field private final java.time.LocalDate java.time.LocalDateTime.date accessible: module java.base does not "opens java.time" to unnamed module @7006c658
My JDK version is java 17.0.5 2022-10-18 LTS, the os is ubuntu 22.04, and the gson version is 2.10;
Here is my code
        Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe()).create();
        Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
        Type listType = new TypeToken<List<Object>>() {}.getType();
        Map<String,Object> map = gson.fromJson(geoCode, mapType);
        String adCode = null;
        if (Objects.nonNull(map) && map.get("infocode").equals("10000")){
            List<Object> list = gson.fromJson(gson.toJson(map.get("geocodes")), listType);
            Map<String,Object> temp = gson.fromJson(gson.toJson(list.get(0)),mapType);
            adCode = String.valueOf(temp.getOrDefault("adcode","110000"));
        }
        String weatherInfo = getWeatherInfo(adCode);
        return gson.fromJson(weatherInfo, Weather.class);

public class LocalDateAdapter  extends TypeAdapter<LocalDate>   implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
    @Override
    public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        String asString = jsonElement.getAsJsonPrimitive().getAsString();
        return LocalDate.parse(asString,DateTimeFormatter.ISO_LOCAL_DATE);
    }

    @Override
    public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }

    @Override
    public void write(JsonWriter jsonWriter, LocalDate localDate) throws IOException {
        jsonWriter.value(localDate.toString());
    }

    @Override
    public LocalDate read(JsonReader jsonReader) throws IOException {
        return LocalDate.parse(jsonReader.nextString());
    }
}

The data structure looks like this
{"date":"2022-11-28","week":"1","dayweather":"多云","nightweather":"晴","daytemp":"14",
   "nighttemp":"-5","daywind":"西北","nightwind":"西北","daypower":"4","nightpower":"4"}


Q: Trouble with writing text to a .ini file I am working on a small game project in the Unity 3D engine. I am trying to write a class that will allow a settings menu to write the recorded settings to an .ini file. However, I can't seem to get myto write to the file. I think I wrote the class correctly to do it based upon the MSDN article on the subject. Here is my class
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;

//Used to allow other files to access the script by name
namespace INI

{
public class iniFile {
    public string path;

    string winDir=System.Environment.GetEnvironmentVariable("windir");

    [DllImport("KERNEL32.DLL")]
    private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
    [DllImport("KERNEL32.DLL")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

    /// INIFile Constructor.
    public iniFile(string INIPath) {
        path = INIPath;
    }
    /// Write Data to the INI File
    public void IniWriteValue(string Section, string Key, string Value) {
        long success = WritePrivateProfileString(Section, Key, Value, this.path);
        Debug.Log (Section);
        Debug.Log (Key);
        Debug.Log (Value);
        Debug.Log (path);
        Debug.Log (success);
        return;
    }

    /// Read Data Value From the Ini File
    public string IniReadValue(string Section, string Key) {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(Section,  Key, "", temp, 255, this.path);
        return temp.ToString();
    }
}
}

Here is my call for this class:
if (GUI.Button (new Rect (Screen.width * guiGameplayApplyButtonPlaceX, Screen.height *    guiGameplayApplyButtonPlaceY, Screen.width * guiGameplayApplyButtonSizeX, Screen.height *     guiGameplayApplyButtonSizeY), "Apply")) {
        ini.IniWriteValue("Gameplay","Difficulty","Test");
        print ("Apply");
    }

I created the instance of the class like this:
iniFile ini = new iniFile(@"..\settings\settingsTest.ini");

A: Maybe that's not the exact answer to your question, but what for you want to create file with settings? Wouldn't be much easier, to use Unity3d built-in feature for saving game preferences, which also works cross-platform?
If you want to give it a try, read about PlayerPrefs.


Q: How to structure/implement multidimensional data / data cube I've been reading into what a data cube is and there are lots of resources saying what it is and why (OLAP/ business intelligence / aggregations on specific columns) you would use one but never how.
Most of the resources seem to be referencing relational data stores but it doesn't seem like you have to use an RDBMS.
But nothing seems to show how you structure the schema and how to query efficiently to avoid the slow run time of aggregating on all of this data.  The best I could find was this edx class that is "not currently available": Developing a Multidimensional Data Model.

A: You probably already know that there are 2 different OLAP approaches:

*

*MOLAP that requires data load step to process possible aggregations (previously defined as 'cubes'). Internally MOLAP-based solution pre-calculates measures for possible aggregations, and as result it is able to execute OLAP queries very fast. Most important drawbacks of this approach come from the fact that MOLAP acts as a cache: you need to re-load input data to refresh a cube (this can take a lot of time - say, hours), and full reprocessing is needed if you decide to add new dimensions/measures to your cubes. Also, there is a natural limit of the dataset size + cube configuration.

*ROLAP doesn't try to pre-process input data; instead of that it translates OLAP query to database aggregate query to calculate values on-the-fly. "R" means relational, but approach can be used even with NoSQL databases that support aggregate queries (say, MongoDb). Since there is no any data cache users always get actual data (on contrast with MOLAP), but DB should able to execute aggregate queries rather fast. For relatively small datasets usual OLTP databases could work fine (SQL Server, PostgreSql, MySql etc), but in case of large datasets specialized DB engines (like Amazon Redshift) are used; they support efficient distributed usage scenario and able to processes many TB in seconds.

Nowadays it is a little sense to develop MOLAP solution; this approach was actual >10 years ago when servers were limited by small amount of RAM and SQL database on HDD wasn't able to process GROUP BY queries fast enough - and MOLAP was only way to get really 'online analytical processing'. Currently we have very fast NVMe SSD, and servers could have hundreds gigabytes of RAM and tens of CPU cores, so for relatively small database (up to TB or a bit more) usual OLTP databases could work as ROLAP backend fast enough (execute queries in seconds); in case of really big data MOLAP is almost unusable in any way, and specialized distributed database should be used in any way.

A: The general wisdom is that cubes work best when they are based on a 'dimensional model' AKA a star schema that is often (but not always) implemented in an RDBMS. This would make sense as these models are designed to be fast for querying and aggregating.
Most cubes do the aggregations themselves in advance of the user interacting with them, so from the user perspective the aggregation/query time of the cube itself is more interesting than the structure of the source tables. However, some cube technologies are nothing more than a 'semantic layer' that passes through queries to the underlying database, and these are known as ROLAP. In those cases, the underlying data structure becomes more important.
The data interface presented to the user of the cube should be simple from their perspective, which would often rule out non-dimensional models such as basing a cube directly on an OLTP system's database structure.


Q: I have hbase metadata in gcs from another environment. I want to create table from this but not sure how? I have a Hbase table extract in google cloud bucket from SIT environment. I want to create a hbase table using that but I am not sure how to do it. I tried creating dummy table and pushing the data inside of it but it didn't worked out. Any help is appreciated. Thank You !
I tried creating hbase table from metadata stored in gcs but somehow the data is not visible in the new table created. I want to use the data to create hbase table so I can continue my development.


Q: How to navigate to a route without routerLink in angular2 I am working with nebular framework, from the amazing guys at akveo.
One of the components is a context menu that creates a popup menu with it's options read from an array
items = [{ title: 'Profile' }, { title: 'Log out' }];

I want to navigate to a different screen but tutorials talk mostly about routerLink

This is my link out

But in this case, I can't add a  tag because they abstracted the click event and allow you to subscribe like
this.menuService.onItemClick()
  .pipe(
    filter(({ tag }) => tag === 'my-context-menu'),
    map(({ item: { title } }) => title),
  )
  .subscribe(title => {
    console.error(`${title} was clicked!`)
  });

And that prints when each button was clicked, but I have to trigger the navigation inside the .subscribe() function.
How to do so?

A: First of all, the outer route has got to exist, in some routing.module
// app-routing.module.ts
const routes: Routes = [
  { path: 'getMeOut', component: OutComponent },
  ..
]

Four things are needed then

*

*Import Router from @angular/router.

*Create a private router in your constructor private router: Router.

*Call navigateByUrl() with the desired route.

*Identify your context menu with the nbContextMenuTag property.

Then, in the module that holds the context menu, we create the router to handle the navigation like
// awesome.component.ts
import { Router } from '@angular/router'
import { NbMenuService } from '@nebular/theme';

@Component({
  selector: 'awesome',
  styleUrls: ['./awesome.component.scss'],
  templateUrl: './awesome.component.html',
})

ngOnInit() {
  this.menuService.onItemClick()
  .pipe(
    filter(({ tag }) => tag === 'my-context-menu'),
    map(({ item: { title } }) => title),
  )
  .subscribe(title => {
    if (title === 'Log out') this.router.navigateByUrl('/getMeOut');
    console.error(`${title} was clicked!`)
  });
}

constructor(
  private menuService: NbMenuService,
  private router: Router) {
}

See the simple use of navigateByUrl from @angular/router.
Just add nbContextMenuTag="my-context-menu" to the html template
<nb-action *nbIsGranted="['view', 'user']" >
 <nb-user nbContextMenuTag="my-context-menu"></nb-user>
</nb-action>

I hope it's not a dupe. I found this answer but it meant more about nested routers.


Q: How to reference friends in Open Graph? I am creating a Facebook-enabled game where the users will be able to publish 'friend passes'; where a player will be able to post (automatically) such as: 'I passed James Brown on MY_GAME'. I am using Open Graph for posting my actions. I've created an action named 'pass' and an object named 'friend'. Here is my properties (where 'friendpass' is a Friend reference):

I am trying to post actions such as 'Michael passed a friend on MY_GAME' and also tag my passed friend[s?]. How can I enable this functionality? Currently, I ve set up a page (actually just meta-tag) renderer and Here is an example rendered page:
 <html and other headers...>
    <meta property="fb:app_id" content="345390505541783">
    <meta property="og:type" content="smileys-game:friendpass">
    <meta id="ogurl" property="og:url" content="http://apps.canpoyrazoglu.com/smileys/pass/mehmet/sucuk">
    <meta property="og:title" content="Friend passed!">
    <meta property="og:image" content="https://s-static.ak.fbcdn.net/images/devsite/attachment_blank.png">
    <meta id="friendid" property="smileys-game:friend" content="735475141">
    <meta id="ogdesc" property="og:description" content="something comes here.">
    <rest of header and page...>

I use the debug tool to get what Facebook sees and there is a link to the action there as a Graph API call. When I click it it returns OAuth error, when I type that URL to the Graph API explorer, I get this:

Graph API sees my 'friend' object as a webpage, which is actually a reference to a Facebook ID (my own ID). How can I make use of that Friend ID useful and make a link to the friend in the post?
Thanks,
Can.

A: When you create your action type, you need to use the profile object type (aka connected object type). Here I created my verb to "high five" a person:

The object type will be configured automatically because profile is a built-in, FB-provided object type. So you don't have to configure the object type, unless there's an advanced setting you need.
Then create an aggregation:

Your og meta tags for the object then need to use the type profile (filepath for this example is /og/profile2.html):
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# high_fiver: http://ogp.me/ns/fb/high_fiver#">
   <meta property="fb:app_id"      content="27877347222" />
   <meta property="og:url"         content="http://www.rottentomatoes.com/celebrity/tom_hanks/" />
   <meta property="og:type"        content="profile" />
   <meta property="og:title"       content="Tom Hanks" />
   <meta property="og:description" content="Tom Hanks profile on RT" />
   <meta property="og:image"       content="http://content6.flixster.com/rtactor/40/37/40376_pro.jpg" />

Notice that you can point to any profile, not just a FB profile. Above, I am using Tom Hanks' profile on Rotten Tomatoes, which uses Open Graph and has og:type profile.
And I publish actions like so:
<script type="text/javascript">
 function postAction() {
   FB.api(
     '/me/high_fiver:high_five' + '?profile=http://www.plooza.com/og/profile2.html',
     'post',
     function(response) {
       if (!response || response.error) {
         alert('Error occured');
         console.log(response.error);
       } else {
         alert('Post was successful! Action ID: ' + response.id);
       }
     }
   );
 }
</script>

Finally, a user of my app will publish the OG story on his/her timeline (in a "timeline unit"):

When you click the link "Tom Hanks" in the story unit, it loads the Rotten Tomatoes profile.
You can try this demo app here:  http://plooza.com/og/profile2.html

A: So “friend” is your own object type? How exactly is it defined?
I think for what you’re planning to do here, the built-in object type Profile might suit your needs better – because that already creates a tie to a Facebook profile that is recognizable as such by the Open Graph.


Q: How to add label into form builder (not in twig)? I have this code, but it doesn't work:
$builder->add('name','text',array(
    'label'  => 'Due Date',
));

the problem i have in fosuserbundle, i have overring form
<?php
namespace Acme\UserBundle\Form\Type;

use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilder $builder, array $options)
    {

        // add your custom field
        $builder->add('name','text',array(
    'label'  => 'Due Date',
));
        parent::buildForm($builder, $options);
    }

    public function getName()
    {
        return 'acme_user_registration';
    }
}

but not work, not give me any error and set the label "fos_user_registration_form_name"

A: You see label as fos_user_registration_form_name, because FOSUserBundle uses translations files to translate all texts in it.
You have to add your translations to file called like Resources/translations/FOSUserBundle.nb.yml (example for norwegian) or you can modify translations file coming with the bundle (copying it to Acme\UserBundle is a better way).


Q: PLSQL procedure error I get the below error while executing code
create or replace
function contact_restriction_function(obj_schema varchar2, obj_name varchar2)
return varchar2 is
    v_contact_info_visible hr_user_access.contact_info_visible%type;
    begin
    -- Here you can put any business logic for filtering
    select nvl(max(contact_info_visible),'N')
    into v_contact_info_visible
    from hr_user_access
    where user_name = user;

    -- SQL filter / policy predicate
    return ''''||v_contact_info_visible||''' = ''Y'' ';
end;
/

after show erros command i got this

 show errors
Errors for FUNCTION CONTACT_RESTRICTION:

LINE/COL ERROR
-------- -----------------------------------------------------------------
3/1      PLS-00103: Encountered the symbol "?" when expecting one of the
         following:
         begin function pragma procedure subtype type
          current cursor delete
         exists prior external language

This is the remaining code:
begin
  dbms_rls.add_policy(object_schema => 'HR' ,
                      object_name => 'EMPLOYEES' ,
                      policy_name => 'Contact_Restriction_Policy' ,
                      policy_function => 'contact_restriction_function' ,
                      sec_relevant_cols=>'EMAIL,PHONE_NUMBER'Contact Info ,
                      sec_relevant_cols_opt=>dbms_rls.all_rows);
end;

below is the actual code which i am executing before show errors:
create or replace function contact_restriction(obj_schema varchar2, obj_name varchar2)
  return varchar2
is
  v_contact_info_visible IN user_access.contact_info_visible%type;
begin
  select nvl(max(contact_info_visible),'N')
    into v_contact_info_visible
    from user_access where username = user;

  return 'v_contact-info_visible ='|| 'Y';
end;

A: Your original question shows an error message referring to "?", but the code yout posted a as comment would raise a similar error for `"IN"' instead:
2/24   PLS-00103: Encountered the symbol "IN" when expecting one of the following:

That is because you've used IN for a local variable; but IN, OUT and IN OUT are only applicable to stored procedure parameters. You could have declared the function with an explicit IN for example, though it is the default anyway:
create or replace function contact_restriction(obj_schema IN varchar2, ...

So that needs to be removed from the v_contact_info_visible declaration. You've linked to an example you're working from, but you've removed a lot of important quotes from that, which will still cause it to fail when executed as a part of a VPD; because v_contact_info_visible will be out of scope to the caller. And you have a typo, with a hyphen instead of an underscore.
You need something like:
create or replace function contact_restriction(obj_schema varchar2,
  obj_name varchar2)
return varchar2 is
  v_contact_info_visible user_access.contact_info_visible%type;
begin
  select nvl(max(contact_info_visible),'N')
  into v_contact_info_visible
  from user_access
  where username = user;
  return ''''||v_contact_info_visible ||''' =''Y''';
end;
/

When called, that will return a string which is either 'N'='Y' or 'Y'='Y'. VPD will include that as a filter in the original query, which will either prevent any rows being returned (in the first case) or have no effect and allow all rows that match any other existing conditions to be returned (in the second case).

A: The syntax of the function header is incorrect. It should be:
create or replace function contact_restriction(obj_schema IN varchar2, obj_name IN varchar2)
  return varchar2
is


Q: MY SQL Partitioning advice We are currently deciding on a partitioning scheme for a table in our MySQL database. We have multiple shards and we route all of a single users records to one shard. We also want to partition the table itself by userid. We are somewhat new to partitioning and would like some feedback as to which type of partition to use and how often we will likely need to maintain the partition.
We did some simple tests using partitioning by key, linear key, hash and linear hash. In our tests it seems like hash is the fastest option for insertion and it also seems to give us the best distribution using randomly generated userids. While reading the documentation, however, we read that linear hash is better if you want to merge or optimize partitions but we noticed it is a lot slower on insertion. We don’t really understand why we would ever need to merge or optimize partitions so we aren’t sure how much of a consideration this should be.
Also… we are planning to use the maximum number of partitions (1000 I think) because we don’t see any negative to this approach and it should give us the best performance by limiting the number of records per partition to the maximum degree. Is there anything we should be considering when deciding on the number of partitions or is ok to simply use 1000 partitions?
Does anybody have any advice on this?

A: So for anybody who may be interested about this topic , here is my experience :
We finally decided not to use MYSQL portioning and instead using database sharding.
The reason for that is: no matter how good you implement the portioning there is still the fact that data needs to indexed and brought into the memory when needed and for our system which is handling up to 500,000 user's emails this can simply become a major hardware issue over the time as people receive mail and will force you to buy more expensive hardware .
Also there is another hidden cost in MYSQL which is the altering tables schema which can simply become impossible if you have a big table and limited resources. After using MSSQL and Oracle in real world scenario I was NOT really impressed by the way MYSQL handles metadata updates and indexing.
So the short answer would be do not use portioning for you database unless you are sure that you won't have major schema changes to your table/indexes and also your table will not grow too big.
Although I have to say if you  design a good index for your system(be very careful with primary keys because that is your clustered index in MYSQL and your queries will be much more efficient if you query on primary key index) you may not really need portioning at all (right now on one of our installations we have a table with +450,000,000 records and it is very fast when you use the primary key index to query the data)
Another point is if there is a chronology in your data and you always have a date range to query it is good idea to use partitioning if your database does not grow too big and if you are intending to delete the old data after a while (like a log rotation,...) partitioning may be the best option because you can simply drop the partition instead of writing a delete process.
Hope this will help you making the right decision.


Q: Converting IF statement to VBA with Variables I am trying to convert the following IF statement into text that will be filled into a cell through VBA:
=IF(XLOOKUP(N7,'EDL Filter'!R2:R660,'EDL Filter'!AA2:AA660)="YES","Port Specific",XLOOKUP(N7,'EDL Filter'!R2:R660,'EDL Filter'!AB2:AB660) )

I've tried splitting it up as I have with other Xlookup statements below:
ActiveCell = "=IF(XLookUp(N" & SafetyRow2 & ",'EDL Filter'!R2:R660,'EDL Filter'!AA2:AA660)=""Yes"",""Port Specific"", Xlookup(N" & SafetyRow2 & ",'EDL Filter'!AB2:AB660))"

However, I keep getting Run-time Error '1004': Application-defined or object-defined error.
The variables have been defined and used earlier in my code without issue, but I am still new to VBA so I might be missing something obvious.


Q: MongoDB: Remove JSON from Array in a Document I want to remove json from an array in a document.
My document is this:
{
    "_id" : ObjectId("5c2f9a15a372ef8825b18736"),
    "class_section" : [
        {
            "class_id" : "1",
            "section_id" : "A"
        },
        {
            "class_id" : "2",
            "section_id" : "A"
        }
    ],
    "registered_time" : ISODate("2019-01-04T17:38:29.753Z"),
    "__v" : 0
}

I need this following after removing "class_id": "2" and "section_id": "A" with both the conditions
{
    "_id" : ObjectId("5c2f9a15a372ef8825b18736"),
    "class_section" : [
        {
            "class_id" : "1",
            "section_id" : "A"
        }
    ],
    "registered_time" : ISODate("2019-01-04T17:38:29.753Z"),
    "__v" : 0
}

How can I do this in MongoDB?

A: Try updating the document by using $pull operator
collection.update(
  {},
  { $pull: { "class_section": { class_id: '2' } } }
);

Please refer to mongo documentation of $pull operator here


Q: React Native Voice error on some Android phones In one of the devices (Redmi 8A), I have the output of
Voice.getSpeechRecognitionServices() ==> ["com.xiaomi.mibrain.speech"] and voice recognising is not working.
Voice.start() ==> undefined but
Voice.isAvailable() ==> true
Voice.isRecognizing() ==> true
but none of the following events are triggered,
Voice.onSpeechResults
Voice.onSpeechStart
Voice.onSpeechEnd
Voice.onSpeechError
Voice.onSpeechPartialResults

I tried again after installing Google App and now the device returns ["com.google.android.googlequicksearchbox", "com.xiaomi.mibrain.speech"] for Voice.getSpeechRecognitionServices() but voice is still not working. Permission is granted and I can record and play using @react-native-community/audio-toolkit.
In the logcat:
SpeechRecognizer: bind to recognition service failed
ActivityManager: Unable to start service Intent { act=android.speech.RecognitionService cmp=com.miui.voiceassist/com.xiaomi.mibrain.speech.asr.AsrService } U=0: not found

Have anyone faced the similar issue and solved this? Any suggestions?
The device is running:

*

*Android Version 9

*MIUI 11.0.3

*Redmi 8A

A: Found out that even if you have Google services, some android phones can be configured to use other voice recognising services and it can break the flow as React Native Voice is using Google Services.
You can check which Voice services a particular Android Phone is using as following:
Settings > App Management > Default App > Assistive App and Voice Input > Assistive App
Hope this is helpful for those who might be facing the same issues.


Q: How to use Commands to react to a ListBox I'm trying to learn Commanding and have set up a simple wpf project to use a custom command.   I have a ListBox and a Button on a Window.  When the ListBox has the focus and an Item is selected, I want the Button to be enabled, otherwise it should be disabled.
I define a CustomCommand in a separate CustomCommands class:
Public Shared ReceivedFocus As New RoutedCommand

and in my Window I set it up as follows:
<CommandBinding
    Command="{x:Static local:CustomCommands.ReceivedFocus}"
    CanExecute="CanActivate"
    Executed="ChangeSelection">
</CommandBinding>

and use the command for the ListBox as follows:
<ListBox
    x:Name="lstInactive">
    <i:Interaction.Triggers>
        <i:EventTrigger
            EventName="GotFocus">
            <i:InvokeCommandAction
                Command="{x:Static local:CustomCommands.ReceivedFocus}"
            </i:InvokeCommandAction>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListBox>

and, finally, the CanActivate routine is:
Private Sub CanActivate(sender As Object, e As CanExecuteRoutedEventArgs)
        If lstInactive.SelectedIndex >= 0 Then
            e.CanExecute = True
        Else
            e.CanExecute = False
        End If
End Sub

This is not working.  The major problem is that I don't understand how to relate the CanExecute value to the Button.  Should I ignore the CanExecute value in the CanActivate routine and instead just set the Enabled property of the Button?  If so, what is the value of the CanExecute paramter of the CanExecuteRoutedEventArgs?
A second problem is that the GotFocus event is not firing until I select an item in the ListBox a second time.
Or maybe I don't have a grasp on Commanding at all and this is not the right approach.  This small project is not important in itself, it is intended to make sure I understand Commanding after reading numerous articles about it before I start to use Commands in "real" projects.  Sadly, at this stage it is clear I don't.

A:
This is not working. The major problem is that I don't understand how to relate the CanExecute value to the Button.

Bind its Command property to the same command:
<Button Content="Button" Command="{x:Static local:CustomCommands.ReceivedFocus}" />

The Button should then be enabled or disabled based on the value that you set the CanExecute property to in your CanActivate event handler.
You probably also want to listen to the SelectionChanged event. This works as expected:
<StackPanel>
    <StackPanel.CommandBindings>
        <CommandBinding
                Command="{x:Static local:CustomCommands.ReceivedFocus}"
                CanExecute="CanActivate"
                Executed="ChangeSelection">
        </CommandBinding>
    </StackPanel.CommandBindings>

    <ListBox x:Name="lstInactive">
        <ListBoxItem>first</ListBoxItem>
        <ListBoxItem>second</ListBoxItem>
        <ListBoxItem>third</ListBoxItem>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{x:Static local:CustomCommands.ReceivedFocus}">
                </i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ListBox>

    <Button Content="Button" Command="{x:Static local:CustomCommands.ReceivedFocus}" />
</StackPanel>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void CanActivate(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = lstInactive.SelectedIndex >= 0;
    }

    private void ChangeSelection(object sender, ExecutedRoutedEventArgs e)
    {

    }
}


Q: Problems with tbb in native dll called from multi-threaded .net application? We have a native .dll that does some HPC type calculations using Threading Building Blocks 4.4 to manage parallelism.  This .dll is called from a .Net desktop program that is itself multi-threaded.  I'm a novice at tbb, and I was wondering if this kind of set-up was inviting some issues.  My use of tbb is pretty basic-- I'm just calling parallel_reduce to do one particular calculation.  I'm not explicitly setting up the tbb threadpool; I'm relying on the default initialization for that.
When we do system tests we are seeing some intermittent process hangs.  We are not seeing these when we test the native dll in isolation, so I expect a minimal example that demonstrates the problem would be difficult to construct.  I'm hoping someone more familiar with tbb than I might be able to suggest if there is likely to be an intrinsic problem in this usage scenario.
Everything is running on Windows 10 on x86-64 platform, by the way.

A: The answer to my question appears to be that there is no problem; Threading Building Blocks can work fine in this scenario.  Eliminating the parallel_reduce didn't change the behavior, and further investigation shows that the problem was confined to the managed code; didn't have anything to do with TBB at all.


Q: Dynamically creating Expression Blend controls in WPF C# I have created a button in Expression Blend 4. I want to dynamically create instances of this button at run time.
The code for the button is below:
    <Button Content="Button" HorizontalAlignment="Left" Height="139" Margin="46,107,0,0" VerticalAlignment="Top" Width="412" Grid.ColumnSpan="2">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black"/>
                <GradientStop Color="White" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>

In addition to the supplying the code can you put comments in explaining what you are doing so that I can learn the general principle.
I know this is a simple question so I have been reading up places such as: Expression blend & WPF, Is there a way to "extract" WPF controls of Expression Blend?, and http://social.msdn.microsoft.com/forums/en-US/wpf/thread/ffa981b8-9bba-43a2-ab5e-8e59bc10fc0d/ unfortunately none of these have helped.

A: In your WPF application you should have a App.xaml file, in there you can add Styles that are to be used thoughout your UI.
Example:
<Application x:Class="WpfApplication8.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <!--The style for all your buttons, setting the background property to your custom brush-->
        <Style TargetType="{x:Type Button}"> <!--Indicate that this style should be applied to Button type-->
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black"/>
                        <GradientStop Color="White" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style>

    </Application.Resources>
</Application>

Or if you dont want to apply to all buttons, you can give your Style a Key so you can apply to certain Buttons in your UI
<Application x:Class="WpfApplication8.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <!--Add a x:Key value so you can use on certain Buttons not all-->
        <Style x:Key="MyCustomStyle" TargetType="{x:Type Button}">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black"/>
                        <GradientStop Color="White" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style>

    </Application.Resources>
</Application>

To use this Style on a Button, just add a binding to the Style property of the Button
  <Button Style="{StaticResource MyCustomStyle}" />

this will apply the Style just to this Button
Or if you really want to do it in code behind you can just add the Brush you want to the background
   Button b = new Button
   {
       Background = new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
   };

its very easy to translate xaml to code because xaml uses the exact same property names, like the code brush I posted above:
new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))

is ....
Brush(firstColor,secondColor,StartPoint EndPoint)

Xaml just accesses properties in the button, they will all have the same names in C#.


Q: Capturing Self in a double block with ARC I recently learned this trick for when I have to reference self within a block.
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{

    HMFInventoryBatchItemsController *strongSelf = safeSelf;
    if (strongSelf) {
        [strongSelf doSomethingElse];
    }
}];

But I've been wondering, what if I have a block within a block? Do I need to do the same thing again?
__weak MyObject *safeSelf = self;
    [self doWithCompletionBlock:^{

        HMFInventoryBatchItemsController *strongSelf = safeSelf;
        if (strongSelf) {

            __weak MyObject *saferSelf = strongSelf;
            [strongSelf doAnotherThingWithCompletionBlock:^{

                HMFInventoryBatchItemsController *strongerSelf = saferSelf;
                if (strongerSelf) {
                    [strongerSelf doSomethingElse];
                }
            }];
        }
   }];

Or is this fine
__weak MyObject *safeSelf = self;
    [self doWithCompletionBlock:^{

        HMFInventoryBatchItemsController *strongSelf = safeSelf;
        if (strongSelf) {

            [strongSelf doAnotherThingWithCompletionBlock:^{

                    [strongSelf doSomethingElse];

            }];
        }
   }];

A: The good answer is, it depends. It's in general unsafe to do:
__weak MyObject *safeSelf = self;

[self doWithCompletionBlock:^{
      [safeSelf doAnotherThingWithCompletionBlock:^{
              [safeSelf doSomethingElse];
       }];
}];

The reason for that, is that when you call -doAnotherThingWithCompletionBlock if that method thinks it holds a reference on self, which a selector usually assumes, and it dereferences self to access ivars, then you will crash, because you actually don't hold a reference.
So whether you need to take a new weak reference or not depends on the lifetime semantics you need/want.
EDIT:
By the way, clang even has a warning about that issue that you can enable in Xcode with the CLANG_WARN_OBJC_RECEIVER_WEAK setting (CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK is also useful while we're at it)

A: __block MyObject *safeSelf = self;

    [self doWithCompletionBlock:^{
          [safeSelf doAnotherThingWithCompletionBlock:^{
                  [safeSelf doSomethingElse];
           }];
   }];

Hope it will do what it should normally does. Tell the compiler not to retain the __weak MyObject* no matter in which block scope it is. The fact is i didn't tested. Meanwhile I'll be surprised if it will actually retain MyObject *


Q: C++ and undefined reference to XML_Parser i have the following problem, i need use expat.h library, i include the library normally:
#include <expat.h>

But when i try to create a object
XML_Parser Parser = XML_ParserCreate(NULL);

Eclipse keppler return undefined reference to XML_ParserCreate . I check the library and is included.
I work with ubuntu 13.04 and g++ compiler.
any idea?

A: Probably you didn't link with the library. You should add this -lexpat to the compiler`s command line. For example:
g++ main.cc -lexpat -o exe

A more advanced (and more easy to use, when you get up to speed) option would be to use pkg-config as e.g. $(pkg-config --libs expat).


Q: How can i iterate Arraylist of an object in Kotlin? I have a arrayList of an object , and i cannot iterate my list forward or reward , i  don't want to display my message in these case but it does .
private fun handleLivePopUp() { // vous êtes en direct
       val id =  presenter.programItems?.indexOf(presenter.currentProgram)
        // val it =         presenter.programItems?.listIterator()
       // val previous = if (id == 0) presenter.programItems!!.size - 1 else id?.minus(1)

       if (id != null){

           if(id == 0){ //si liste == +1 ou liste == -1 on affiche pas
               binding.playerController.startOverImg.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_startover))
               binding.playerController.startOverToast.visibility = View.GONE
               binding.playerController.startOverLiveToast.visibility = View.VISIBLE
               // presenter.programItems!!.size - 1

           } else if(id == id - 1 || id == id + 1){
               binding.playerController.startOverImg.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_startover))
               binding.playerController.startOverLiveToast.visibility = View.GONE  // apparait visible à chaque swipe
               binding.playerController.startOverToast.visibility = View.GONE

           }
       }

This is the code i'm trying to do


Q: login using ssh on multiple user accounts using the same id_rsa and id_rsa.pub i have an id_rsa and id_rsa.pub . say i have 5 users on the same machine. i want to use the same id_rsa and id_rsa.pub to ssh between users without password. is it possible ? As i figure it out if user1 wants to do ssh user2@localhost .../home/user2/.ssh must have a file named authorized_keys with the content of id_rsa.pub. and /home/user1/.ssh must have the id_rsa file. so by doing this user1 can do ssh user2@localhost.
But if user2 wants to do ssh user1@localhost then user1 must have the authorized_keys having the contents of id_rsa.pub and user2 must have the id_rsa file
to sum it up user1 has : authorized_key, id_rsa and user2 has the same files.
what happens on my machine is: user1 can do ssh user2@localhost but user2 cannot do user1@localhost.
is there something missing ? is there something i do not understand ? is it possible to ssh between users using the same id_rsa and the same id_rsa.pub ?

A: File permissions on a user's /home/user/.ssh directory must be 700, and the /home/user/.ssh/authorized_keys must be 600.  Meanwhile, it is essential that all files in each .ssh directory are owned by the user in whose home directory they reside.  To change ownership recursively, you can:
chown -R username:username /home/username/.ssh

If you have multiple users and need to do this for each of them, you can use this loop:
for SSHUSER in user1 user2 user3 user4 user5; do
  # Add the authorized_keys file if it doesn't already exist
  touch /home/$SSHUSER/.ssh/authorized_keys

  # Set its permissions
  chmod 600 /home/$SSHUSER/.ssh/authorized_keys

  # Set directory permissions
  chmod 700 /home/$SSHUSER/.ssh

  # Set ownership for everything
  chown -R $SSHUSER:$SSHUSER /home/$SSHUSER/.ssh
done;


Q: How should this be done? (returing a collection of values) I am writing a weather API to connect to the NOAA's XML METARS in C# NETMF. Before, this API was written in PHP, where I was able to use an associative array to return the weather parameters. For example, the return of the getWX() function might have been
Array(
"temp_f" => "70.0",
"windchil" => "65.0",
"wind_dir" => "90"
);

I am trying to replicate that same functionality in my CSharp version, but I am not sure how to go about doing it. Since I am using NETMF, I cannot use a hashtable.
Should I use a struct instead?
In case anyone wants to see the code behind the original PHP API, it is here: http://www.chrisseto.com/wordpress/?p=17
I am trying to get the CSharp version to be as similar as possible.
Thanks!


Q: How to Apply Masked SVG Patterns using Coord System of ObjectBoundingBox I am writing inline SVG code for a data visualization and I'm trying to apply a <mask> which I filled with a <pattern> to multiple SVG <rect> elements.
I can't find a combination of patternUnits, patternContentUnits, maskUnits and maskContentUnits that makes the mask filling 100% of each rect it gets applied to without stretching the pattern. Is it even possible? The pattern itself is not that complicated and should look like this: correct pattern dimensions applied
Due to performance optimization I wan't the <defs> tag to live in a separate svg at root level of my component.

#my-defs {
  position: absolute;
  top: -1000px;
  left: -1000px;
}

#my-svg {
  width: 200px;
  height: 3em;
}

#my-svg rect {
  width: 100%;
  height: 80%;
}
<svg id="my-defs">
  <defs>
    <pattern id="diagonal-hatch-pattern" patternUnits="userSpaceOnUse" width="4" height="4">
      <path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" stroke="white" strokeWidth="1" />
    </pattern>
    <mask id="diagonal-hatch-mask" x="0" y="0" width="1" height="1" maskContentUnits="objectBoundingBox">
      <rect fill="url(#diagonal-hatch-pattern)" x="0" y="0" width="1" height="1" />
    </mask>
  </defs>
</svg>

<svg id="my-svg">
  <rect fill="steelblue" mask="url(#diagonal-hatch-mask)" />
</svg>

A: I could get it to work by changing maskContentUnits back to its default value of userSpaceOnUse but that doesn't feel right because of the static dimensions i would have to assign to the mask shape. It would be much better if the rect in my mask would scale to each object the mask gets applied to.
So, if anyone has a better solution, I would be very thankful...

#my-defs {
  position: absolute;
  top: -1000px;
  left: -1000px;
}

#my-svg {
  width: 200px;
  height: 3em;
}

#my-svg rect {
  width: 100%;
  height: 80%;
}
<svg id="my-defs">
  <defs>
    <pattern id="diagonal-hatch-pattern" patternUnits="userSpaceOnUse" width="4" height="4">
      <path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" stroke="white" strokeWidth="1" />
    </pattern>
    <mask id="diagonal-hatch-mask" x="0" y="0" width="1" height="1" maskContentUnits="userSpaceOnUse">
      <rect fill="url(#diagonal-hatch-pattern)" x="0" y="0" width="9000" height="9000" />
    </mask>
  </defs>
</svg>

<svg id="my-svg">
  <rect fill="steelblue" mask="url(#diagonal-hatch-mask)" />
</svg>


Q: Jquery document on change: can I use variable as selector? I am very new to javascript and jQuery.  In my view, I have a List of QuoteDetails, as follows:

    @for (int i = 0; i < Model.QuoteDetail.Count; i++)
    {

            @Html.HiddenFor(model => model.QuoteDetail[i].QuoteId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.HiddenFor(model => model.QuoteDetail[i].QuoteDetailId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.EditorFor(model => model.QuoteDetail[i].ProductId, new { htmlAttributes = new { @id = "PId", @class = "form-control", style = "width: 75px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].ProductName, new { htmlAttributes = new { @id = "Product", @class = "form-control", style = "width: 300px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control", style = "width: 95px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].ListPrice, new { htmlAttributes = new { @id = "Lprice", @class = "form-control", style = "width: 95px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].Discount, new { htmlAttributes = new { @class = "form-control", style = "width: 100px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].Price, new { htmlAttributes = new { @id = "Pr", @class = "form-control", style = "width: 100px" } })
            @Html.ValidationMessageFor(model => model.QuoteDetail, "", new { @class = "text-danger" })
    }

When either the Amount or Discount is changed by the user, I want to recalculate the Price.  I am trying to solve it with the following javascript/jQuery:

Is there a way to use variables with indices as jQuery selectors in the document.on change?  Any help will be much appreciated.

A: Give your elements class names, e.g
@Html.EditorFor(m=> m.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control amount"} })

and change the container to

(ditto for discount, listprice and price)
Then your script becomes
$('.amount, .discount').change(function() {
    // Get container
    var row = $(this).closest('.row');
    // Get values
    var amount = Number(row.find('.amount').val());
    var listprice = Number(row.find('.listprice').val());
    var discount = Number(row.find('.discount').val());
    // Validate
    if (isNaN(amount) || isNaN(listprice) || isNaN(discount))
    {
        return; // may want to display an error message?
    }
    // Calculate
    var finalPrice = amount * listprice * ((100 - discount) / 100)
    // Update
    row.find('.price').val(finalPrice);
})

A few things to note:

*

*Duplicate id attributes are invalid html - remove all your new {
@id = ".." code.

*Because of your class names, you can now style the widths - e.g.
.price { width: 95px; }

*Convert the values to a Number and check
that the value is valid using isNaN before doing the calculation

*Since Price is a calculated field, it should not be editable in the
view (or have a setter in the model. Use a
 or similar
element to display it (and then use
row.find('.price').text(finalPrice); to set it

Note also that .on() is not necessary unless your dynamically adding those elements after the view has been first generated.


Q: How do you do calculations using various variables in a toplevel window? I'm creating a calculator app for my company which will be used for the calculation of certain parameters.Since there are various parameters with their respective formulas,I decided to create toplevel windows for each parameter-all linked to respective buttons.  But I can't get the functions to work in the toplevel windows.
I've used def calculate(): to no avail
I expect it to work, since it works in a normal window, but it fails in a toplevel window.
def open():
    ldl_window = Toplevel(root)
    ldl_window.geometry('500x500')

def calculate():

    tc = eval(totalChol.get())
    hdl=eval (hdLipo.get())
    tg=eval (trig.get ())
    ldl =tc-((hdl/2)+tg)
    output_label.configure(text = 'LDL: {:.1f}'.format(ldl))
    totalChol.delete(0,END)
    hdLipo.delete(0,END)
    trig.delete(0,END)

    output_label = Label(font=('Verdana', 16), bg='grey',fg='white')
    tc_label = Label(ldl_window,text='TC',font=('Verdana', 15))
    tc_label.grid(row=0, column=0)
    hdl_label = Label(ldl_window,text='HDL',font=('Verdana', 15))
    hdl_label.grid(row=1, column=0)
    tg_label = Label(ldl_window,text='TG',font=('Verdana', 15))
    tg_label.grid(row=2, column=0)

    totalChol = Entry(ldl_window,font=('Verdana', 15), width=4)
    totalChol.grid(row=0, column=1)
    hdLipo= Entry(ldl_window,font=('Verdana', 15), width=4)
    hdLipo.grid(row=1,column=1)
    trig= Entry(ldl_window,font=('Verdana', 15), width=4)
    trig.grid (row=2,column=1)

    calc_button = Button(ldl_window,text='CALC', font=
    ('CALIBRI',15),command=calculate,bg='blue',fg='white')
    calc_button.grid(row=3, column=0)

    output_label.grid(row=3, column=1)

    btn = Button(root, text = "Calculate LDL", command = open,
    bg='blue',fg='white',font=('CALIBRI', 12))
    btn.grid(row=3, column=0)


Q: extracting string patterns that repeat to a separate column or columns Hi I have not seen a similar solution to this problem I am having. I am trying to make a regrex pattern to extract the characters following the word major within { } and place them in a major column. However, the major repeats in row 2 and I need to extract and combine all characters within both { } following major. Ideally I would do this for minor and incidental attributes as well. Not sure what I am getting wrong here. Thanks!
test <- data.frame(lith=c("major{basalt} minor{andesite} incidental{dacite rhyolite}",
          "major {andesite flows} major {dacite flows}",
          "major{andesite} minor{dacite}",
          "major{basaltic andesitebasalt}"))

test %>%
  mutate(major = str_extract_all(test$lith, "[major].*[{](\\D[a-z]*)[}]") %>%
           map_chr(toString))

What I am looking for:
                         major    minor     incidental
1                       basalt andesite dacite ryolite
2 andesite flows, decite flows     <NA>           <NA>
3      basaltic andesitebasalt     <NA>           <NA>

A: First, (almost) never use test$ within a dplyr pipe starting with test %>%. At best it's just a little inefficient; if there are any intermediate steps that re-order, alter, or filter the data, then the results will be either (a) an error, preferred; or (b) silently just wrong. The reason: let's say you do
test %>%
  filter(grepl("[wy]", lith)) %>%
  mutate(major = str_extract_all(test$lith, ...))

In this case, the filter reduced the data from 4 rows to just 2 rows. However, since you're using test$lith, that's taken from the contents of test before the pipe started, so here test$lith is length-4 where we need it to be length-2.
Alternatively (and preferred),
test %>%
  filter(grepl("[wy]", lith)) %>%
  mutate(major = str_extract_all(lith, ...))

Here, the str_extract_all(lith, ...) sees only two values, not the original four.

On to the regularly-scheduled answer ...
I'll add a row number rn column as an original row reference (id of sources). This is both functional (for things to work internally) and in case you need to tie it back to the original data somehow. I'm inferring that you group the values together as strings instead of list-columns, though it's easy enough to switch to the latter if desired.
library(dplyr)
library(stringr) # str_extract_all
library(tidyr) # unnest, pivot_wider
test %>%
  mutate(
    rn = row_number(),
    tmp = str_extract_all(lith, "\\b([[:alpha:]]+) ?\\{([^}]+)\\}"),
    tmp = lapply(tmp, function(z) strcapture("^([^{}]*) ?\\{(.*)\\}", z, list(categ="", val="")))
  ) %>%
  unnest(tmp) %>%
  mutate(across(c(categ, val), trimws)) %>%
  group_by(rn, categ) %>%
  summarize(val = paste(val, collapse = ", ")) %>%
  pivot_wider(rn, names_from = "categ", values_from = "val") %>%
  ungroup()
# # A tibble: 4 x 4
#      rn incidental      major                        minor
#   <int> <chr>           <chr>                        <chr>
# 1     1 dacite rhyolite basalt                       andesite
# 2     2 NA              andesite flows, dacite flows NA
# 3     3 NA              andesite                     dacite
# 4     4 NA              basaltic andesitebasalt      NA