text:
Q: Why is Forge returning code 403 for Data Connector API This clientId is not authorized to perform the operation Why is Forge returning code 403 for Data Connector API This clientId is not authorized to perform the operation. The token call comes back correctly but I get 403 on the gethubs {"warnings":[{"Id":null,"HttpStatusCode":"403","ErrorCode":"BIM360DM_ERROR","Title":"Unable to get hubs from BIM360DM EMEA.","Detail":"You don't have permission to access this API","AboutLink":null,"Source":null,"meta":null}]}}
And getcon as well "{"detail":"This clientId is not authorized to perform the operation.","status":403,"type":"error","title":"Forbidden","id":69852363,"errors":[{"detail":"This clientId is not authorized to perform the operation.","title":"Forbidden","type":"error"}]}"
These are the calls from App script using, what I think is, 3-legged code grant.
function getToken() {
var formData = {
'client_id': 'ClientID',
'client_secret': 'ClientSecret',
'grant_type': 'client_credentials',
'scope': 'user-profile:read user:read user:write viewables:read
data:create data:read data:write data:search bucket:read     bucket:create
bucket:update code:all account:read account:write',
'prompt':'login'
};  var response =

  UrlFetchApp.fetch('https://developer.api.autodesk.com/authentication/v1/a uthenticate', {
method: 'POST',
payload: formData
});
var token = JSON.parse(response.getContentText());
console.log(token);
return token.access_token;
}

function getHubs() {
var token = getToken();
console.log(token);
var header = {"Authorization" : "Bearer " + token};
console.log(header);

var options = {
"method" : "get",
"headers" : header
};

var response = UrlFetchApp.fetch('https://developer.api.autodesk.com/project/v1/hubs',     options);

var hubs = JSON.parse(response.getContentText());
console.log(JSON.stringify(hubs));
}
function getDConn() {
  var token = getToken();
  console.log(token);
  var header = {"Authorization" : "Bearer " + token,"Content-Type": "application/json" };
  console.log(header);

  var options = {
  "method" : "post",
      "headers" : header,
      "description": "AccountExtract",
      "isActive": true,
      "scheduleInterval": "ONE_TIME",
      "reoccuringInterval": null,
      "effectiveFrom": "2022-10-06T10:00:00.106Z",
      "effectiveTo":  "2022-10-06T10:00:00.106Z",
      "serviceGroups": "locations",
      "callbackUrl": null,
      "sendEmail": true,
      "projectId": null
    };

    //Google Account ID
      var response = UrlFetchApp.fetch('https://developer.api.autodesk.com/data-      connector/v1/accounts/ACCOUNTID/requests', options);

    var hubs = JSON.parse(response.getContentText());
    console.log(JSON.stringify(hubs));


text:
Q: Hydrogen radial wave function in Feynman I'm reading the classical Feynman's lectures on hydrogen atom, and I want to calculate the radial component of the wave function with the formula (19.53)
$$
F_{n,l}(\rho)=\frac{e^{-\alpha\rho}}{\rho}\sum_{k=l+1}^n a_k \rho^k
$$
for $n=2$ and $l=1$.
So I have $\alpha=1/n=1/2$ and
$$
F_{2,1}(\rho)=\frac{e^{-\rho/2}}{\rho}a_2 \rho^2
$$
where $a_2$  should be given by the formula (19.50):
$$
a_{k+1} =\frac{2(\alpha k-1)}{k(k+1)-l(l+1)} a_k
$$
but, for $k+1=2$ and $l=1$ the denominator becomes $0$.
It seems that I have some stupid mistake, but I don't see where. Someone can help me?

A: I think this is just a simple arithmetic error. It's  k = l + 1 so k = 2 (for the l = 1 case) , not k + 1 = 2 (which is the forbidden k = l).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel Redirect BadMethodCallException Really not sure what's up here:
http://laravel.io/bin/E8yMx#2
As it's explained, in the UserController, when I call a Redirect::action to the SessionController, I get thrown the exception.
I've tried recompiling but it's still not working. Any ideas?

A: Ow well, you get this type of error because Laravel resourcefull route "store" expects you to receive data from POST. I think that redirect is achieved via headers() or something like that, so it sends a GET request and you get the error. You should use curl in this case, or you should move your common logic elsewhere than controller, for ex : repositories.

A: As @Vit explained, store expect POST verb. You can use IoC to solve your issue:
return App::make('SessionController')->store();

But I really don't recommend it: what you are trying to do is known as HMVC, and as Taylor Otwell said

This pattern often indicates poor application design, and controllers that are much too complicated

What you should do is to:

Extract the logic into a third class that can be injected into any controller


text:
Q: How can I use PHP to get the nth item in a JSON object? Ok, so the twitter daily trends list is 20 trends long. Let's say I want to get the 7th trend on the list. Here's my longwinded way of doing it...
// We want the 7th item in the array
$trendArray = 7;

// Get an array (?) of the latest twitter trends
$jsonurl = "http://search.twitter.com/trends/daily.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
$allTrends = $json_output->trends;

// Cycle through to the 7th in the list
foreach ( $json_output->trends as $trendslist ) {
    foreach ( $trendslist as $trend ) {
            $loop += 1;
            if ($loop == $trendArray) {
                $theTrend = $trend->name;
                break;
            }
    }
    break; // Exit after we've looped once
}

echo $theTrend;

I suspect I'm confusing objects and arrays, but I'm sure there is a much simpler way of doing this than with those two for/each loops because
$theTrend = $json_output->trends[6]->name;

Gives me this error:
Fatal error: Cannot use object of type stdClass as array

Thanks for your help!

A: $json_output = json_decode($json);

must be:
$json_output = json_decode($json,true);

(You have to tell json to convert the stdClass to arrays)
EDIT: See http://php.net/manual/en/function.json-decode.php


text:
Q: Getting the Keyboard Layout in WPF C# I need to get the Current Windows Keyboard Layout for my WPF application to map each key correctly and handle AZERTY as well as QWERTY and QWERTZ (and so on...)
I noticed a problem since I am working with a French layout (azerty) but my windows is displayed in English.
I tried various methods to get the layout correctly but without results :
var test1 = InputLanguageManager.Current.CurrentInputLanguage;

and
var test2 = CultureInfo.CurrentCulture;

I tried by having ENG language with AZERTY layout, ENG language with QWERTY layout and FRA language with AZERTY layout but the output from my tests were always different. I could get the language displayed correctly (en-GB) but not the layout.

A: The following PowerShell1 script declares Get-KeyboardLayoutForPid function which reliably gets the Current Windows Keyboard Layout for any process2.
if ( $null -eq ('Win32Functions.KeyboardLayout' -as [type]) ) {
    Add-Type -MemberDefinition @'
        [DllImport("user32.dll")]
        public static extern IntPtr GetKeyboardLayout(uint thread);
'@ -Name KeyboardLayout -Namespace Win32Functions
}

Function Get-KeyboardLayoutForPid {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$False, ValueFromPipeline=$False)]
        [int]$Id = $PID,
        # used formerly for debugging
        [parameter(Mandatory=$False, DontShow=$True)]
        [switch]$Raw
    )

    $InstalledInputLanguages = [System.Windows.Forms.InputLanguage]::InstalledInputLanguages
    $CurrentInputLanguage    = [System.Windows.Forms.InputLanguage]::DefaultInputLanguage # CurrentInputLanguage
    $CurrentInputLanguageHKL = $CurrentInputLanguage.Handle # just an assumption
    ### Write-Verbose ('CurrentInputLanguage: {0}, 0x{1:X8} ({2}), {3}' -f $CurrentInputLanguage.Culture, ($CurrentInputLanguageHKL -band 0xffffffff), $CurrentInputLanguageHKL, $CurrentInputLanguage.LayoutName)

    Function GetRealLayoutName ( [IntPtr]$HKL ) {
    $regBase = 'Registry::' +
                'HKLM\SYSTEM\CurrentControlSet\Control\Keyboard Layouts'
    $LayoutHex = '{0:x8}' -f ($hkl -band 0xFFFFFFFF)
    if ( ($hkl -band 0xFFFFFFFF) -lt 0 ) {
        $auxKeyb = Get-ChildItem -Path $regBase |
            Where-Object {
            $_.Property -contains 'Layout Id' -and
                (Get-ItemPropertyValue -Path "Registry::$($_.Name)" `
                    -Name 'Layout Id' `
                    -ErrorAction SilentlyContinue
                ) -eq $LayoutHex.Substring(2,2).PadLeft(4,'0')
        } | Select-Object -ExpandProperty PSChildName
    } else {
        $auxKeyb = $LayoutHex.Substring(0,4).PadLeft(8,'0')
    }
    $KbdLayoutName  = Get-ItemPropertyValue -Path (
        Join-Path -Path $regBase -ChildPath $auxKeyb
    ) -ErrorAction SilentlyContinue -Name 'Layout Text'
    $KbdLayoutName
    # Another option: grab localized string from 'Layout Display Name'
    } # Function GetRealLayoutName

    Function  GetKbdLayoutForPid {
    Param (
        [parameter(Mandatory=$True, ValueFromPipeline=$False)]
        [int]$Id,
        [parameter(Mandatory=$False, DontShow=$True)]
        [string]$Parent = ''
    )
    $Processes = Get-Process -Id $Id
    $Weirds  = @('powershell_ise','explorer') # not implemented yet

    $allLayouts = foreach ( $Proces in $Processes ) {
        $LayoutsExtra = [ordered]@{}
        $auxKLIDs = @( for ( $i=0; $i -lt $Proces.Threads.Count; $i++ ) {
            $thread = $Proces.Threads[$i]
            ## The return value is the input locale identifier for the thread:
            $LayoutInt = [Win32Functions.KeyboardLayout]::GetKeyboardLayout( $thread.Id )
            $LayoutsExtra[$LayoutInt] = $thread.Id
        })
        Write-Verbose ('{0,6} ({1,6}) {2}: {3}' -f $Proces.Id, $Parent,
            $Proces.ProcessName, (($LayoutsExtra.Keys |
                Select-Object -Property @{ N='Handl';E={('{0:x8}' -f ($_ -band 0xffffffff))}} |
                Select-Object -ExpandProperty Handl) -join ', '))
        foreach ( $auxHandle in $LayoutsExtra.Keys ) {
            $InstalledInputLanguages | Where-Object { $_.Handle -eq $auxHandle }
        }
        $ConHost = Get-WmiObject Win32_Process -Filter "Name = 'conhost.exe'"
        $isConsoleApp = $ConHost | Where-Object { $_.ParentProcessId -eq $Proces.Id }
        if ( $null -ne $isConsoleApp ) {
            GetKbdLayoutForPid -Id ($isConsoleApp.ProcessId) -Parent ($Proces.Id -as [string])
        }
    }
    if ( $null -eq $allLayouts ) {
        # Write-Verbose ('{0,6} ({1,6}) {2}: {3}' -f $Proces.Id, $Parent, $Proces.ProcessName, '')
    } else {
        $allLayouts
    }
    } # GetKbdLayoutForPid

    $allLayoutsRaw = GetKbdLayoutForPid -Id $Id
    if ( $null -ne $allLayoutsRaw ) {
        if ( ([bool]$PSBoundParameters['Raw']) ) {
            $allLayoutsRaw
        } else {
            $retLayouts = $allLayoutsRaw |
                Sort-Object -Property Handle -Unique |
                Where-Object { $_.Handle -ne $CurrentInputLanguageHKL }
            if ( $null -eq $retLayouts ) { $retLayouts = $CurrentInputLanguage }
            $RealLayoutName = $retLayouts.Handle |
                ForEach-Object { GetRealLayoutName -HKL $_ }
            $ProcessAux = Get-Process -Id $Id
            $retLayouts | Add-Member -MemberType NoteProperty -Name 'ProcessId' -Value "$Id"
            $retLayouts | Add-Member -MemberType NoteProperty -Name 'ProcessName' -Value ($ProcessAux | Select-Object -ExpandProperty ProcessName )
            # $retLayouts | Add-Member -MemberType NoteProperty -Name 'WindowTitle' -Value ($ProcessAux | Select-Object -ExpandProperty MainWindowTitle )
            $retLayouts | Add-Member -MemberType NoteProperty -Name 'RealLayoutName' -Value ($RealLayoutName -join ';')
            $retLayouts
        }
    }
<#

.Synopsis
Get the current Windows Keyboard Layout for a process.

.Description
Gets the current Windows Keyboard Layout for a process. Identify the process
using -Id parameter.

.Parameter Id
A process Id, e.g.
- Id property of System.Diagnostics.Process instance (Get-Process), or
- ProcessId property (an instance of the Win32_Process WMI class), or
- PID property from "TaskList.exe /FO CSV", …

.Parameter Raw
Parameter -Raw is used merely for debugging.

.Example
Get-KeyboardLayoutForPid

This example shows output for the current process (-Id $PID).
Note that properties RealLayoutName and LayoutName could differ (the latter is wrong; a bug in [System.Windows.Forms.InputLanguage] implementation?)

ProcessId      : 2528
ProcessName    : powershell
RealLayoutName : United States-International
Culture        : cs-CZ
Handle         : -268368891
LayoutName     : US

.Example
. D:\PShell\tests\Get-KeyboardLayoutForPid.ps1  # activate the function

Get-Process -Name * |
    ForEach-Object { Get-KeyboardLayoutForPid -Id $_.Id -Verbose }

This example shows output for each currently running process, unfortunately
even (likely unusable) info about utility/service processes.

The output itself can be empty for most processes, but the verbose stream
shows (hopefully worthwhile) info where current keboard layout is held.

Note different placement of the current keboard layout ID:
- console application      (cmd, powershell, ubuntu): conhost
- combined GUI/console app (powershell_ise)         : the app itself
- classic  GUI apps        (notepad, notepad++, …)  : the app itself
- advanced GUI apps        (iexplore)               : Id ≘ tab
- "modern" GUI apps        (MicrosoftEdge*)         : Id ≟ tab (unclear)
- combined GUI/service app (explorer)               : indiscernible
- etc…                     (this list is incomplete).

For instance, iexplore.exe creates a separate process for each open window
or tab, so their identifying and assigning input languages is an easy task.

On the other side, explorer.exe creates the only process, regardless of
open visible window(s), so they are indistinguishable by techniques used here…

.Example
gps -Name explorer | % { Get-KeyboardLayoutForPid -Id $_.Id } | ft -au

This example shows where the function could fail in a language multifarious environment:

ProcessId ProcessName RealLayoutName Culture     Handle LayoutName
--------- ----------- -------------- -------     ------ ----------
5344      explorer    Greek (220);US el-GR   -266992632 Greek (220)
5344      explorer    Greek (220);US cs-CZ     67699717 US

- scenario:
  open three different file explorer windows and set their input languages
  as follows (their order does not matter):
    - 1st window: let default input language   (e.g. Czech, in my case),
    - 2nd window: set different input language (e.g. US English),
    - 3rd window: set different input language (e.g. Greek).
- output:
  an array (and note that default input language window isn't listed).

.Inputs
No object can be piped to the function. Use -Id pameter instead,
named or positional.

.Outputs
[System.Windows.Forms.InputLanguage] extended as follows:
                                     note the <…> placeholder

Get-KeyboardLayoutForPid | Get-Member -MemberType Properties

   TypeName: System.Windows.Forms.InputLanguage

Name           MemberType   Definition
----           ----------   ----------
ProcessId      NoteProperty string ProcessId=<…>
ProcessName    NoteProperty System.String ProcessName=powershell
RealLayoutName NoteProperty string RealLayoutName=<…>
Culture        Property     cultureinfo Culture {get;}
Handle         Property     System.IntPtr Handle {get;}
LayoutName     Property     string LayoutName {get;}

.Notes
To add the `Get-KeyboardLayoutForPid` function to the current scope,
run the script using `.` dot sourcing operator, e.g. as
. D:\PShell\tests\Get-KeyboardLayoutForPid.ps1

Auhor:     https://stackoverflow.com/users/3439404/josefz
Created:   2019-11-24
Revisions:

.Link

.Component
P/Invoke

<##>

} # Function Get-KeyboardLayoutForPid

if ( -not ('System.Windows.Forms.InputLanguage' -as [type]) ) {
    Add-Type -AssemblyName System.Windows.Forms
}

The Get-KeyboardLayoutForPid function contains a Comment-Based Help placed at the end of its body. I hope that its principle is implementable in C# easy.
The main idea of my approach:

*

*Suppose that the current keyboard layout (CurrentInputLanguage) for a given process is the (user-dependant) default one (DefaultInputLanguage).

*Collect keyboard layouts associated with every thread of given process (allLayoutsRaw). Note this trick for a console application: collect keyboard layouts associated with every thread of child conhost process as well.

*If there is a keyboard layout different from DefaultInputLanguage in the allLayoutsRaw collection then it's the sought-after one (retLayouts).

1 Does not work in PowerShell Core (pwsh.exe).
2 Might fail for explorer process in a language multifarious environment, see an example of failing scenario in the Comment-Based help.

A: I am not sure of the ask - whether you want to know the current keyboard layout or you want to set the keyboard layout.
In both cases, InputLanguageManager should help.
You can try setting input language manager to appropriate cultureInfo object.
This should change the keyboard layout for your WPF application
InputLanguageManager.Current.CurrentInputLanguage = new CultureInfo("fr-FR");


text:
Q: how to construct an active high pass filter on breadboard i am going to have an experiment on active high pass filters and i would like someone to tell me how could i construct / carry the experiment please i don't want be embarrassed.
so tell me please what equipment/device are we going to use and the procedure in general.
Regards

A: Depends what you mean by high-pass (kilohertz? megahertz? Gigahertz?) and what you mean by breadboard (white plastic object with lotsa-holes - better be kilohertz)
In general, keep wires short and tidy, but if dealing with the white plastic lotsa-holes type, short wires will only help a little at higher frequencies, where the vast amounts of stray capacitance will significantly impede the function of the filter - at which point you might want to move to a prototype that's built by soldering things onto (or above - look for "dead-bug" examples) a circuit board with a ground plane underlying everything. Sometimes you can cut a few islands into the copper coated board, or you can add separate islands or strips on top of the copper-coated board.


text:
Q: Check if a certain user has a certain attribute from a imported CSV file in Powershell I have the following shutdown script:
    Stop-Process -ProcessName Thunderbird* -Force -ErrorAction 'silentlycontinue'
Stop-Process -ProcessName Outlook* -Force -ErrorAction 'silentlycontinue'
$personname= ([adsi]"WinNT://$env:userdomain/$env:username,user").fullname
$res=Test-Path "\\cd2012\backup\$personname"
if ($res -eq $False)
{
    New-Item -ItemType directory -Path "\\cd2012\backup\$personname"

    Import-Csv \\cd2012\backup\lista.csv -Encoding UTF8 -Delimiter ";" -Header Name,User,Attribute

                if  ($_.Attribute -ne "T" -and $_.User -eq $env:username)
                    {
                        & c:\windows\system32\Robocopy.exe "$env:LOCALAPPDATA\Microsoft\Outlook\" "\\cd2012\backup\$personname" /E /MT:20 /R:50 /W:10 /V /ETA
                    }
                else
                    {
                        & c:\windows\system32\Robocopy.exe "$env:APPDATA\Thunderbird\Profiles\" "\\cd2012\backup\$personname" /E /MT:20 /R:50 /W:10 /V /ETA

                    }
                Set-ItemProperty -Path "\\cd2012\backup\$personname" -Name LastWriteTime -Value $(Get-Date)

}
else
{
    $wts=Get-Item "\\cd2012\backup\$personname" | Foreach {$_.LastWriteTime}

        if ($wts -gt (Get-Date).AddDays(2))
        {
                Import-Csv \\cd2012\backup\lista.csv -Encoding UTF8 -Delimiter ";" -Header Name,User,Attribute

                if  ($_.Attribute -ne "T" -and $_.User -eq $env:username)
                    {
                        & c:\windows\system32\Robocopy.exe "$env:LOCALAPPDATA\Microsoft\Outlook\" "\\cd2012\backup\$personname" /E /MT:20 /R:50 /W:10 /V /ETA
                    }
                else
                    {
                        & c:\windows\system32\Robocopy.exe "$env:APPDATA\Thunderbird\Profiles\" "\\cd2012\backup\$personname" /E /MT:20 /R:50 /W:10 /V /ETA

                    }
                Set-ItemProperty -Path "\\cd2012\backup\$personname" -Name LastWriteTime -Value $(Get-Date)

          }

}

The CSV file contains the following
Bob;User1;
John;User2;
Mike;User3;T
George:User4;T
This script basically makes backup copies of folders every 2 days. The issue I am having is checking the username and attribute when it comes to deciding if the client has Outlook or Thunderbird. If the user has the "T" attribute, I know he has Thunderbird, so I should copy from the Thunderbird location. If he does not, I should copy from the Outlook location.
I know all my clients have the same default location because I am the only the configures it.

A: You could simplify your script to something like this:
Stop-Process -ProcessName Thunderbird* -Force -ErrorAction 'silentlycontinue'
Stop-Process -ProcessName Outlook* -Force -ErrorAction 'silentlycontinue'

$personname= ([adsi]"WinNT://$env:userdomain/$env:username,user").fullname

$robocopyExe = join-Path $env:windir 'system32\Robocopy.exe'
$backupFolder = Join-Path '\\cd2012\backup\' $personname

# ensure the backup target is present
New-Item -ItemType directory -Path $backupFolder -Force | out-null

$thunderbirdDir = Join-Path $env:APPDATA 'Thunderbird\Profiles'
$outlookDir = Join-Path $env:LOCALAPPDATA 'Microsoft\Outlook'

if (Test-Path $thunderbirdDir)
{
    & $robocopyExe $thunderbirdDir $backupFolder /E /MT:20 /R:50 /W:10 /V /ETA /minage:2
}
if (Test-Path $outlookDir)
{
    & $robocopyExe $outlookDir $backupFolder /E /MT:20 /R:50 /W:10 /V /ETA /minage:2
}

Note: The two day copy skip is controlled using  Robocopy /minage Parameter.


text: Q: find the distance between two nodes in an hierarchy in DBpedia using SPARQL I want to fire a query using virtuso sparql server on dbpedia. Here I have two resources as an actor as "dbpedia:Aamir_Khan" and have an owl:class Actors. I want to find the distance between the Aamir khan page to the Actor class. In general I want to find the distance between two nodes in an hierarchy in dbpedia. I am new to this. I have seen several examples But none of them are directly using dbpedia resources. Please any one help in reference to an example using specific dbpedia ontology.


text:
Q: How can the typo3 backend page tree be constructed asynchronously in typo3 v9.x? This concerns the typo3 v9 main page tree in the backend view.
I have a very large page tree with about 20.000 page entities. The query takes a long time...
In my Typo3 v9.5.5 environment, the data is retrieved in a single slow query.
How can Typo3 build the page tree in several fast queries level by level?
In the older Typo3 version (8.7.24) this also works with the method getNextTreeLevel() I think.

A: The core team is working on it.
There are 2 patches pending:
https://review.typo3.org/c/Packages/TYPO3.CMS/+/62329 - this patch makes page tree less bandwidth
https://review.typo3.org/c/Packages/TYPO3.CMS/+/62086 - this adds asynchronous tree rendering (it's a work in progress, as needs some tuning regarding workspaces support)

A: The new behaviour is like this by design in TYPO3 9.
There is a slack-channel discussing that issue: https://typo3.slack.com/messages/CK20S7EKS
And a bug-ticket on forge: https://forge.typo3.org/issues/88474
Out of that there will come a patch for the core.
The only help for now is the extensions: https://github.com/bueroparallel/bp_pagetree (discussed and reviewed in the slack channel). This speed up the tree load but just loads up to a defined nesting level what results in not all pages are automatic included in the filter results. But for now (and hopefully just for a small time period) the best solution!


text:
Q: Selecting a list of sub elements in XML that may or may not exist What I have is an XML we receive from a web service which represents a list of questions.  The questions are broken down by type which indicates how they should be displayed on the web.  For instance:
<step id="109025">
  <stepinf enabled="Yes" errors="0" id="First Name" mandatory="Yes" name="sti_115511" type="FIL">
    <field_label>First Name</field_label>
    <screen_value></screen_value>
  </stepinf>
  <stepinf enabled="Yes" errors="0" id="Last Name" mandatory="Yes" name="sti_115513" type="FIL">
    <field_label>Last Name</field_label>
    <screen_value></screen_value>
  </stepinf>
  <stepinf enabled="Yes" errors="0" id="State" mandatory="Yes" name="sti_109257" type="STE">
    <field_label>State</field_label>
    <screen_value></screen_value>
    <options_list>
      <option label="AK">AK - Alaska</option>
      <option label="AL">AL - Alabama</option>
      <option label="AR">AR - Arkansas</option>
      <option label="AS">AS - American Samoa (Terr.)</option>
      <option label="AZ">AZ - Arizona</option>
      ...
    </options_list>
  </stepinf>
</step>

The type "STE" indicates that it will display on the web as a select box.
I am populating a List<> of a custom type I created by doing the following:
var stepinfList = (from stepinf in xdoc.Descendants("stepinf")
    select new Question
    {
       TextID = stepinf.Attribute("id").Value,
       Type = stepinf.Attribute("type").Value,
       Name = stepinf.Attribute("name").Value,
       Label = stepinf.Element("field_label").Value,
       Required = stepinf.Attribute("mandatory").Value,
       ErrorCount = int.Parse(stepinf.Attribute("errors").Value)
    }).ToList();

Where I am getting lost at is I have no idea how to get the option sub-elements into my results.  I tried creating a property in the Question type named Options which I defined as an IDictionary and then utilized a sub-select in my LINQ query and the ToDictionary extension.
Options = (from option in xdoc.Element("options_list").Elements("option")
    select option)
    .ToDictionary(x => x.Attribute("label").Value, x => x.Value)

This didn't work as I think it bombs on the stepinf records that do not have child option_list elements.  Anyway, I get "Object reference not set to an instance of an object" on the LINQ statement when I run the page.
I'm afraid this is above my current LINQ skill set so any help would be greatly appreciated.

A:
This didn't work as I think it bombs
  on the stepinf records that do not
  have child option_list elements.

Your assessment is correct, so you need to check whether option_list exists before querying it. Check if it's null and return the dictionary or return null accordingly.
Try this:
Options = stepinf.Element("options_list") == null ? null :
              stepinf.Element("options_list").Elements("option")
                     .ToDictionary(x => x.Attribute("label").Value, x => x.Value)


text:
Q: Default to the T-SQL Pane view within Visual Studio 2012 Database Project When working with a Database Project in Visual Studio 2012, VS defaults to the "Design-View" pane when you add or edit a table. While you can work in split-screen mode, the T-SQL pane defaults to the bottom pane.
As I prefer to work with T-SQL directly as opposed to the designer, I constantly am switching to make the T-SQL pane the top-most editor in order to work with the object. Unfortunately, VS does not remember this preference, so each and every time I work with a table I must change to make the T-SQL pane appear on top as opposed to beneath the designer pane.
I've looked to see if there is a setting under Tools --> Options to control this behavior, but so far I have been unable to find a setting that does so. I've done a few google searches on the topic as well, but haven't found anything helpful for this particular case.
This is more of an annoyance than anything else for me, but as I am finding myself constantly switching panes I wonder if anyone knows of a setting, either within VS or the registry or some other config file that would force VS to either remember my preference or default to the T-SQL Pane on top of the Designer Pane?

A: If you want to get rid of the designer completely, try the following:

*

*Right-click on the file, and select Open With...

*Select Microsoft SQL Server Data Tools, T-SQL Editor,

*Click on Set as Default

*Click OK.

Next time you'll be able to simply double clicking the file to open it in T-SQL.


text:
Q: SQL Inner Join request doesn't work I'm new in mysql and php and I have a problem with a query. I want to get nearby locations which I am calculating with the Harversine formula. This all is working, but now I want to show the specific stores which are associated with the locations. This is the relevant part:
$query = sprintf("SELECT 'Location.id', latitude, longitude, ( 6371 * acos( cos( radians('%s') ) * cos( radians( latitude ) ) * cos( radians( longitude )
 - radians('%s') ) + sin(radians('%s') ) * sin( radians( latitude ) ) ) ) AS distance
    FROM(SELECT id, latitude, longitude FROM Location WHERE latitude Between '%s' AND '%s' AND longitude Between '%s' AND '%s') AS cut
    JOIN Store ON 'Location.storeID' = 'Store.id'
    WHERE 6371 * acos( cos( radians('%s') ) * cos( radians( latitude ) ) * cos( radians( longitude )
     - radians('%s') ) + sin(radians('%s') ) * sin( radians( latitude ) ) ) < '%s' ORDER BY distance",

Without the JOIN statement, this works fine. But if I use the JOIN statement, I get an empty array. Does anyone know why? Is the statement maybe in the wrong place?
These are my tables:
Location

Store

I will be thankful for any help!


text:
Q: Need macro to transfer Word data into Excel I am very new to VBA and need help ! I have VB macro in Excel that grabs the data from a Word document and imports it into Excel worksheet. Currently, the code in macro has expression that clears the active worksheet and places the new records. However, I need only to update active sheet with new records, or add new records. So, trying to figure out how to accomplish it within the existing code.
Here is the macro:
Sub getWordFormData()
Dim wdApp As New Word.Application
Dim myDoc As Word.Document
Dim CCtl As Word.ContentControl
Dim myFolder As String, strFile As String
Dim myWkSht As Worksheet, i As Long, j As Long

myFolder = "C:\Users\zsirotilo\Documents\Retention DB\Interviews"
Application.ScreenUpdating = False

If myFolder = "" Then Exit Sub
Set myWkSht = ActiveSheet
ActiveSheet.Cells.Clear

Range("A1") = "Company Name"
Range("A1").Font.Bold = True
Range("C1") = "Date of Interview"
Range("C1").Font.Bold = True
Range("D1") = "Type of Company by Number(see Case Notes)"
Range("D1").Font.Bold = True

i = myWkSht.Cells(myWkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(myFolder & "\*.docx", vbNormal)

While strFile <> ""
i = i + 1

Set myDoc = wdApp.Documents.Open(Filename:=myFolder & "\" & strFile,
AddToRecentFiles:=False, Visible:=False)

With myDoc
j = 0
For Each CCtl In .ContentControls
j = j + 1
myWkSht.Cells(i, j) = CCtl.Range.Text
Next
myWkSht.Columns.ColumnWidth = 25
End With
myDoc.Close SaveChanges:=False
strFile = Dir()
Wend
wdApp.Quit
Set myDoc = Nothing: Set wdApp = Nothing: Set myWkSht = Nothing
Application.ScreenUpdating = True

End Sub

A: It should work by removing the line ActiveSheet.Cells.Clear, because this is the line that removes the content of the cells.
The line i = myWkSht.Cells(myWkSht.Rows.Count, 1).End(xlUp).Row is used to know the last row with content to write the new content from then. So it will work as long as the last row has content on the first column.
To avoid to read the same files over and over, it's needed to move the already exported files to another folder. My idea is this:

*

*Create a folder, for example:C:\Users\zsirotilo\Documents\Retention DB\Exported.

*Add the line exportedFolder = "C:\Users\zsirotilo\Documents\Retention DB\Exported" after the line that defines the variable myFolder.

*After the line myDoc.Close SaveChanges:=False add the following lines:
    FileCopy myDoc, exportedFolder & "\" & strFile 'copy word file to Exported folder
    Kill myDoc 'deletes the word file

Make a backup of the Word files on  C:\Users\zsirotilo\Documents\Retention DB\Interviews before testing because it will delete the files.


text:
Q: SQL: how to make an if statement I'm fairly new to MS SQL, so bear with me please.
I have a table with a bunch on info about customers, where I want to add columns and input values of either "yes" or "no" depending on the result of some values from the table.
Basically, I need something like this
SELECT customer_no, reg_no, @result_101, @result_301
      IF(reg_no*100)+other_number = 101
      THEN @result_101 = 'yes'
      ELSE @result_101 = 'no'

      IF(reg_no*100)+other_number = 301
      THEN @result_301 = 'yes'
      ELSE @result_301 = 'no'
FROM customer_table

Is it possible for the customer to get 'yes' in both columns, as they have several "other_number"?
I can't really figure out how to work this out with the CASE statement - because it will just create double rows, so each customer will show up twice on the result set, like
customer_no      reg_no      @result_101     @result_301
01               0101         yes             no
01               0101         no              yes
02               0101         yes             no
02               0101         no              yes

and I need them to be gathered into one single row.

A: What you're looking for is the case expression:
SELECT
  customer_no, reg_no,
  result_101 = CASE
                WHEN (reg_no*100)+other_number = 101 THEN 'yes'
                ELSE 'no'
               END,
  result_301 = CASE
                WHEN (reg_no*100)+other_number = 301 THEN 'yes'
                ELSE 'no'
               END
FROM customer_table

I removed the @ sign from your column names as @ is used for variables but if you really want it you can enclose it in brackets: [@result_101]
If you want to avoid duplicate rows you probably need to use some aggregate function with the case expression.

A: You can use IIF for a simpler and cleaner solution:
Like this:
SELECT

  customer_no,
  reg_no,
  IIF (reg_no * 100 + other_number = 101, 'yes', 'no') AS reg_101,
  IIF (reg_no * 100 + other_number = 301, 'yes', 'no') AS reg_301

FROM customer_table

This will only work if you are using MS-SQL 2012 or higher


text:
Q: Dynamic template for single custom post I am trying to create a dynamic template for all custom post types I create.
I understand I can put the post type slug in "Template Post Type:" in the header comments of my template but how can I populate this dynamically?
eg. this is how I would like my header comments to work but I obviosuly can't use a variable in the comments .
<?php
$custom_post_types = 'post, page, my_custom_post_type1, my_custom_post_type2';

/**
 Template name: Home
 Template Post Type:  $custom_post_types
*/
?>


text:
Q: Can I pass a unique_ptr's reference to a function? Can I pass a unique_ptr's reference to a function? If not why should I avoid it?
Ex:
void func(unique_ptr<Clss>& ref);

main() {
   unique_ptr<Clss> a = std::make_unique<Clss>();
   fn(a);
}

A:
Can I pass a unique_ptr's reference to a function?

Yes, a unique_ptr is class like any other.
You should do this when you want to mutate an existing unique_ptr from a function (e.g. calling .reset() on it).
If only you want to access the object inside unique_ptr<T>, take T& or const T& in your function interfaces, so that they can be used independently of unique_ptr.

A: According to Herb Sutter:
https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/
Passing unique_ptr by reference is for in/out unique_ptr parameters.
void f( unique_ptr<widget>& ); // (d)

This should only be used to accept an in/out unique_ptr, when the function is supposed to actually accept an existing unique_ptr and potentially modify it to refer to a different object. It is a bad way to just accept a widget, because it is restricted to a particular lifetime strategy in the caller.
Thanks @sgvd

A: See this code snippet, two ways of passing unique_ptr as function parameter. fun1 will take ownership of the object ( hence should be forwarded from the caller) but func2 commits thats the reference unique_ptr object will be passed as reference and will not be modified by the function.
void func1(unique_ptr<Clss>&& moved_obj) // this function takes ownership
{
    //do something with the moved_obj

    moved_obj.reset();
}

void func2(const unique_ptr<Clss>& ref_obj) // this function takes reference
{
   unique_ptr<Clss> new_obj = std::make_unique<Clss>(*(ref_obj));
}

int main() {

   unique_ptr<Clss> a = std::make_unique<Clss>();
   func1(std::move(a));

   unique_ptr<Clss> b = std::make_unique<Clss>();
   func2(b);

    return 0;
}

A: I see those valid meaningful signatures:
void take_ownership(std::unique_ptr<Clss>);
// or void take_ownership(std::unique_ptr<Clss>&&);

void use(/*const*/ Clss*);
// or void use(/*const*/ Clss&);

std::unique_ptr<Clss> create(/*args..*/);

void might_take_ownership(std::unique_ptr<Clss>&);

The later might make sense, but it is more difficult to reason with (as any I/O argument).
If you can, prefer one of the other.

A: Passing a std::unique_ptr to a function is perfectly fine as long as you respect the same rules you would when passing a regular reference to a function:

*

*the underlying std::unique_ptr and the object it points to must live at least as long as the function will use the reference;

*in case of multi-threading, barriers must be put in place.


text:
Q: Connection Strings - MVC Entity Framework - Database First Can anyone suggest how I could programatically switch debug and live connection strings?
I've seen other people have passed an EntityConnection to the constructor from the controller like this :
private XYZDatabase db = new XYZDatabase(ConfigurationManager.
ConnectionStrings["XYZDatabase-TEST"].ConnectionString);

but it still requires manually changing it? is there a way to use
System.Net.Dns.GetHostName() or similar
to switch it automatically?
Thanks

A: Ayende has a post that addresses this issue.
http://ayende.com/blog/135169/frictionless-development-web-config-and-connection-strings

A: In my software I just have 2 connection strings of the same name in my app.config and comment/uncomment to switch between configurations.
Another method is that you could create a static property in your solution (.asax file?) and just use that to swap between XYZDatabase-TEST and XYZDatabase when you are fetching ConnectionStrings.

A: Add connection string to your Web.config like:
<connectionStrings>
    <add name="XYZDatabase-TEST" connectionString="Server=.\SQLEXPRESS;Database=XYZDatabase-TEST";integrated security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Then open you Web.Release.config and add
<connectionStrings>
    <add name="XYZDatabase-TEST"
        connectionString="Data Source=OTHERSERVER;Initial Catalog=XYZDatabase-TEST;Persist Security Info=True;User ID=sa;Password=password" providerName="System.Data.SqlClient"
        xdt:Transform="SetAttributes"
        xdt:Locator="Match(name)"/>
</connectionStrings>

Now, everytime you will publish you application to deployment server using Release configuration it will use the connection string from web.release.config
Note that this transformation will not work locally when you debug. You must publish to run the web.config transformation.


text: Q: IIS Redirect Files IIS comes with asp files that help redirect requests based on if they are local or external. Thinking that I had these saved in another location, I deleted them from the folder that contained my website. Does anyone know where to get them or how to get them back? I already tried running the installation again, but that did not seem to do anything. The files had names having to do with local and external; I cannot remember the exact names.


text:
Q: Calling string from another sub I want to use a string that I declared previously into a function (there's a reason why I want it to be a function). But the function isn't recognising the string, my question is how I could modify the code below to make it work? Any help is appreciated. Thank you in advance.
Sub encryption

Dim text As String = wraper.DecryptData(ciphertext)

End sub

and...
Public Function CallResults() As String

Dim instructions As String = text '//'text' isn't being recognised
Return instructions

End function

A: Declare the variable text at class-level:
Dim text As String

Sub encryption

   text = wraper.DecryptData(ciphertext)

End sub

Public Function CallResults() As String

   Dim instructions As String = text
   Return instructions

End function

A: You can also add a Module to the project that has the text variable declared in it (variable is global to the project.
However it would be better design to have the function accept a variable that it can act upon:
Public Function CallResults(Dim text As String)

   Dim instructions As String = text
   Return instructions

End function

A: Public Function CallResults() As String

Dim instructions As String = encryption '//'text' isn't being recognised
Return instructions

End function

would do it. @Ahmed Salman Tahir's answer would be more efficient if you are getting it more than once as it would cache the result of encryption.


text:
Q: linux android emulator not show in adb devices after restart adb server I using android emulator in linux(Ubuntu16.04), The adb server seems not working normal.
root@ubuntu:~/santi/opengl# adb -P 15770 devices
List of devices attached
emulator-5770   device

root@ubuntu:~/santi/opengl# adb -P 15770 root
root@ubuntu:~/santi/opengl# adb -P 15770 kill-server
root@ubuntu:~/santi/opengl# adb -P 15770 devices
* daemon not running. starting it now on port 15770 *
* daemon started successfully *
List of devices attached

root@ubuntu:~/santi/opengl#

Thus the problem, when I restart adb server, the emulator not in adb devices again!  Only if I restart the emulator, it shows again in adb devices.
The ADB version: Android Debug Bridge version 1.0.32

adb devices
adb root
adb kill-server
adb devices

A: Unbelievable! Above problem was caused by the emulator specified start port. As I start emulator with command:
emulator -avd template -gpu mesa -no-window -port 5680

The above port if > 5680, then device wont show after restart adb server, otherwise port <= 5680 it shows and definitely shows okay!


text:
Q: ruby: class instance variables vs instance variables my idea is to create a community wiki for people that come from a java background because reading a lot of explanations, I couldn't comprehend anything until I actually tried a couple of things and the pieces of the puzzle started to find their places. But I first need to make sure I'm getting it right. Coming from such background it was very confusing for me to find out that @variable may mean 2 very different things.
Here is an example:
class Test
  @ins = "gah"
  def self.ins
    puts @ins
  end

  def initialize()
    @ins = "wtf?"
  end
  def ins2
    puts @ins
  end
end

As far as I understand, the first @ins is an instance variable of the object representing the class Test. The second @ins is an instance variable in an object of class Test.
Now things start to make some sense to me. Here a couple of examples:
[14] pry(main)> test.ins2
wtf?

We are calling a method of an object and it returns the object's instance variable.
[15] pry(main)> test.ins
NoMethodError: undefined method `ins' for #<Test:0x000000017d9348 @ins="wtf?">

We are trying to call a class method through an object, this method is of the class so we are getting NoMethodError
[16] pry(main)> Test.ins
gah

We are calling a class method so it properly sees the instance variable of the class object.
[17] pry(main)> Test.ins2
NoMethodError: undefined method `ins2' for Test:Class

We are calling an object method through the class which is incorrect so throwing NoMethodError.
All of the above was performed with ruby 2.0. So what am I asking?

*

*Am I getting it right?

*Am I getting the ruby terminology correct?

*Any real usage of class instance variables that make sense in a properly designed app? Or are these simply the better @@class variables?

A: *

*First, to understand instance variables, one need to know this - classes are objects.
All classes are instances of Class(read the doc) which inherits from Object. That's why classes are objects.

*Then, every instance variables(ids marked with @, like @ins) are defined in self.
When self is a class, they are instance variables of classes(class instance variables).
When self is a object, they are instance variables of objects(instance variables).

*In different code scopes, the self represents different things.
class Test
  # class scope, uncomment following line to see the value of self
  # p self
  @ins = "gah"
  def self.ins
    # class scope
    # p self
    puts @ins
  end

  def initialize()
    # object scope
    # p self
    @ins = "wtf?"
  end
  def ins2
    # object scope
    # p self
    puts @ins
  end
end

A:
it was very confusing for me to find out that @variable may mean 2 very different things.

No, it doesn't. Classes are objects just like any other object. They can have instance variables just like any other object. They can have instance methods just like any other object. In fact, unlike Java, which has three different kinds of "methods" (instance methods, static methods and constructors), in Ruby, there is exactly one kind of method: instance methods.
The beauty of having classes being objects is precisely that @variable always means exactly the same thing.
There is no such thing as a class instance variable: it's just a normal instance variable like any other. The object happens to be an instance of Class, but that doesn't change the nature of the instance variable. An instance variable of an object of class String is not a string instance variable, it's just an instance variable. Likewise, an instance variable of an object of class Class is just an instance variable.
There is no such thing as a class method: it's just a normal singleton method of an object which happens to be an instance of Class. (Acually, there's no such thing as a singleton method either: it's just a normal instance method of the object's singleton class.)
Note: Rubyists may use the term "class method" in casual conversation. But that doesn't mean that class methods actually exist, it only means that "instance method of the class object's singleton class" is a mouthful. The important thing is: because classes are objects, they work exactly like all other objects. They can have instance methods (defined in class Class or inherited from Module, Object, Kernel or BasicObject), they can have "singleton methods" (which really are instance methods of their respective singleton classes), they can have instance variables.
They can also have class variables (@@variables) … those are weird. Ignore them :-)

A: Everything looks right to me.
A class variable will be passed down through inheritance while an instance variable on a class will not. (src: Ruby class instance variable vs. class variable)
As far as design goes, I tend to prefer avoiding class variables altogether (I'd rather use a singleton), but if I had to choose one I would probably choose a class variable over a class instance variable to avoid confusion.


text:
Q: How to understand Variational Autoencoder As new to variational autoencoder, there are some simple details perplex me. The basic idea of VAE is to use an encoder to map some unknown distribution (e.g. mnist images) to a specific distribution like Gaussian, and then decode this latent distribution back to the original distribution. In Kingma's paper, I feel confused about these simple facts:

*

*The paper assume p(x|z) to be a Gaussian distribution. But in my opinion, p(x|z) is what the decoder does to map the latent variable z to the original distribution(e.g. mnist images). Thus, p(x|z) actually represents the original distribution. Why can we just simply assume it to be a Gaussian distribution?

*The cost function of VAE is composed of the reconstruction error and regularization error. But I don't know what's the effect of regularization error and what if we just use the reconstruction error?

*The encoder of VAE outputs the mean u and s.t.d for the Gaussian distribution and then we sample z from it. But why don't we just let the encoder output z in Gaussian just as what we do in GAN(In GAN, we use a generator to directly output variable in the distribution we want)?

A: Below are my answers to your questions. An excellent explanation of variational autoencoder can be found at in this blog.

*

*Variational autoencoder assumes the marginal likelihood of data as
$$p(x) = \int dz p(x|z)p(z)$$
i.e. a continuous mixture of Gaussian. This mixture is a universal approximator for any distributions.

*The effect of regularization error is to make the posterior distribution of latent variable $p(z|x)$ look like a unit Gaussian. The reason we need a regularization error (aside from the fact that it comes naturally from the derivation) is we want to limit the range of latent variables so that similar data lead to similar latent variables. For example, suppose we have many different images of number "9", without the regularization error nothing can prevent the network from mapping these images to completely different value far away in the latent space, while the regularization error will make it more favorable to map these images to values close in the latent space. So you can see its similarity with other regularization techniques in neural network in here.

*The random sample for GAN is drawn from the prior distribution of latent variable $p(z)$, and the random sample for variational autoencoder is drawn from the posterior distribution of latent variable $p(z|x)$. If you simply want to generate an image $x$, then you do not need $p(z|x)$. You can just draw from
$p(z)$ as you did in GAN and pass $z$ through the decoder network.


text:
Q: How can get json interface of the smart contract I export JSON interface from compile.js file but deploy.js file not work
it shows error as

RuntimeError: abort(Error: You must provide the JSON interface of the contract when instantiating a contract object.). Build with -s ASSERTIONS=1 for more info.

here is compile.js
  const path = require('path');
const fs = require('fs');
const solc = require('solc');

const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');
const source = fs.readFileSync(lotteryPath, 'utf-8');

//console.log(solc.compile(source,1));

var input = JSON.stringify({
    language: 'Solidity',
    sources: {
        'lottery.sol': {
            content: source
        }
    },
    settings: {
        outputSelection: {

            // Enable the metadata and bytecode outputs of every single contract.
            "*": {
                "*": ["metadata", "evm.bytecode"]
            },
            // Enable the abi and opcodes output of MyContract defined in file def.
            "def": {
                "Lottery": ["abi"]
            },

        }
    }
})

const output = JSON.parse(solc.compile(input));

const interface = output.contracts['lottery.sol'].Lottery.abi;
const bytecode = output.contracts['lottery.sol'].Lottery.evm.bytecode.object;

module.exports = {
    interface,
    bytecode,
};

after that export this to deploy.js file

const HDwalletProvider = require("truffle-hdwallet-provider");
const Web3 = require("web3");
const {interface,bytecode}= require('./compile.js');

const provider = new HDwalletProvider(
    '',
    'https://ropsten.infura.io/v3/9ba5113757f648aaaab4d53e65898119'
);

const web3 = new Web3(provider);

const deploy = async()=>{
    const accounts = await web3.eth.getAccounts();
    console.log(accounts);
    console.log("contract is deployed by manager with address",accounts[0]);

    const result = await new web3.eth.Contract(interface)
     .deploy({data : '0x'+bytecode})
     .send({gas : '2000000' , from : accounts[0]});

     console.log('contract deployed to address ', result.options.address);
}

deploy();

finally, show error
JSON interface error
Please help me,I am just a beginner at web3.js.I follow old tutorial to know the workflow
But it does not match with updated versions
here is depend
 "dependencies": {
    "next": "^11.1.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "solc": "^0.8.6",
    "truffle-hdwallet-provider": "^1.0.17",
    "web3": "^1.5.2"
  }

I need someone help to get deployed address to set here
lottery.js file
 import web3 from './web3.js';
const address = '';
const abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"enterLottery","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"participants","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pickWinner","outputs":[],"stateMutability":"nonpayable","type":"function"}];

export default new web3.eth.Contract(abi,address);

A: in compile.js
var output = JSON.parse(solc.compile(JSON.stringify(input))); // an object
// it spits out bytecode and interface

module.exports = output.contracts["Lottery.sol"]["Lottery"];

in deploy.js
    const { abi, evm } = require("./compile");

A: compile.js
const path = require("path");
const fs = require("fs");
const solc = require("solc");

const inboxPath = path.resolve(__dirname, "contracts", "Example.sol");
const source = fs.readFileSync(inboxPath, "utf8");

const input = {
  language: "Solidity",
  sources: {
    "Example.sol": {
      content: source,
    },
  },
  settings: {
    outputSelection: {
      "*": {
        "*": ["*"],
      },
    },
  },
};

const output = JSON.parse(solc.compile(JSON.stringify(input)));

module.exports = output.contracts["Example.sol"]["Example"];

here is my mocha test file example.test.js:
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const web3 = new Web3(ganache.provider());
const { abi, evm } = require("../compile");

let accounts;
let exampleContract;
beforeEach(async () => {
  // Get a list of all accounts
  accounts = await web3.eth.getAccounts();

  // Use one of those accounts to deploy the contract
  exampleContract = await new web3.eth
    .Contract(abi)
    .deploy({
      data: evm.bytecode.object,
      arguments: ["Hi there"],
    })
    .send({ from: accounts[0], gas: 1000000 });
});

describe("Example", () => {
  it("deploys a contract", () => {
    console.log(exampleContract);
  });
});


text:
Q: How do I automatically put a formula into a cell when a value is changed in another cell? Basically, if any cell in column N is changed, I want to automatically populate the cell in column J using a formula to determine the correct input, which has nothing to do with the value in column N, just that one has been entered.  I don't want to use if statements in all the cells in column J because I also want the user to be able to enter values when the formula doesn't produce one.
This is what I have:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.HasFormula Then Exit Sub
        Application.EnableEvents = False
        Target = UCase(Target.Cells(1))
    Application.EnableEvents = True

    If Not Intersect(Target, Sheet4.Range("N:N")) Is Nothing Then
     If Target > 0 Then
        Application.EnableEvents = False
        Target.Offset(0, -4).Value = "=IF(I2=32,'176',IF(I2=42,'175',IF(I2=630, '190' ,'""')))"
      ' Reset EnableEvents
        Application.EnableEvents = True
    End If
    End If

End Sub

A: Several issues here

*

*In a code behind module, use the Me keyword to refer to the sheet in question

*I assume you want each formula to refer to cell on the row it's in

*User may update several cells at once via copy/paste, which can include cells in Column N and or Other columns

*I assume you are onlt intereseted in when the user inserts a value (not a formula) - this can be modified if required

Your code, refactored
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    On Error Resume Next
        Set rng = Intersect(Target, Me.Range("N:N")).SpecialCells(xlCellTypeConstants)
    On Error GoTo 0
    If Not rng Is Nothing Then
        Application.EnableEvents = False
        rng.Offset(0, -4).FormulaR1C1 = "=IF(RC[-1]=32,176,IF(RC[-1]=42,175,IF(RC[-1]=630,190,"""")))"
        ' Reset EnableEvents
        Application.EnableEvents = True
    End If
End Sub

A: Maybe something like this:
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim TargetCell As Range

    Application.EnableEvents = False
    For Each TargetCell In Target
        If Not Intersect(TargetCell, Sheet4.Range("N:N")) Is Nothing Then
            If TargetCell.Offset(0, -4).Value = "" Then
                TargetCell.Offset(0, -4).Value = "=IF(I2=32,176,IF(I2=42,175,IF(I2=630, 190 ,"""")))"
            End If
        End If
    Next
    Application.EnableEvents = True

End Sub

A: If your intent is to use the formula in column J only if it will produce a result,
then perhaps:
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.HasFormula Then Exit Sub

On Error GoTo ResetEvents
    Application.EnableEvents = False

    Target = UCase(Target.Cells(1))

    If Intersect(Target, Sheet4.Range("N:N")) Is Nothing Then GoTo ResetEvents

    If Target > 0 Then
        Target.Offset(0, -4).Value = BuildColumnJContent(Target)
    End If

ResetEvents:
    Application.EnableEvents = True
End Sub

Private Function BuildColumnJContent(ByVal Target As Range) As String
    Dim cellID As String
    cellID = "I" & Target.Row
    Select Case Sheet4.Range(cellID)
        Case 32, 42, 630
            BuildColumnJContent = "=IF(" & cellID & "=32,176,IF(" & cellID & "=42,175,IF(" & cellID & "=630, 190 ,"""")))"
        Case Else
            BuildColumnJContent = ""
    End Select
End Function


text:
Q: How to update fwupdmgr itself I am trying to update my firmware on Ubuntu 18.04. When I try to see updates with
$ fwupdmgr get-updates
I see the following:
$ fwupdmgr get-updates
Not compatible with org.freedesktop.fwupd version 1.0.9, requires >= 1.2.5
No upgrades for UEFI Device Firmware, current is 192.47.1524: 192.47.1524=same
Not compatible with org.freedesktop.fwupd version 1.0.9, requires >= 1.1.0
Not compatible with org.freedesktop.fwupd version 1.0.9, requires >= 1.1.3

This suggests to me that my fwupdmgr version (which is 1.0.9) needs to be upgraded to at least 1.2.5 to apply all of the available updates.
How can I update fwupdmgr?

A: You can install the fwupd snap to get a newer version:
sudo apt remove fwupd
snap install fwupd

You will get 1.3.6 at the time of writing
That's what I did at least (I'm also on 18.04), to be able to install the latest firmware updates on my Thinkpad X1 Carbon Gen6.

A: If possible upgrade to 19.10 and you would have 1.2.10

Package fwupd

bionic (18.04LTS) (admin): Firmware update daemon    1.0.6-2ubuntu1
eoan (19.10) (admin): Firmware update daemon    1.2.10-1ubuntu2

In case that is not an option you could try to install the debian install file from 19.10 either manually through dpkg or the software center and then pick all the dependencies needed as instructed during the attempt to install. The list of requirements is pretty long.
Next best thing is to install it from source and use that version.
Main components of the compilation instructions:
# apt build-dep fwupd
# meson build

I don't believe it to be a good idea to do this other then from a newer version of Ubuntu. We are talking about updating device drivers. Those are also connected to the kernel so upgrading from within 18.04 might have you end up installing things from 19.10 anyways.

A: snap install fwupd didn't work for me on 18.04 but sudo snap install fwupd --candidate --classic did. This installed 1.3.8 because updates on a T480 don't seem to work any more with version 1.2.x that comes with 18.04.


text:
Q: storing multiple lines of output in ruby returned from shellout I want to store a multi line output in ruby and i am not able to get the exact way for this.
Below is my use case:

I am running a shell command in ruby as follows:
 files = Mixlib::ShellOut.new('lsblk -o -d name --noheadings').run_command.stdout.split (/\n/)
 puts "files value is '#{files}'

"
Here, the lsblk command in shell gives two rows as "vda and vdb" as
  output, but when ran in ruby, it is displaying only first value i.e. vda

please let know if i am missing something here or is it like i should use some other structure to hold such multi line output from shell.

A: 1) Fix your command. lsblk -o --noheadings returns lsblk: unknown column: --noheadings
2) Use split() not strip ()
3) Always use double-quotes for intra-string interpolation. Change puts 'files value is #{files}' to puts "files value is #{files}"
A working example would be:
files = Mixlib::ShellOut.new('lsblk').run_command.stdout.split(/\n/)
puts "files value is #{files}"

P.S. I like to use regex when matching new lines instead of strings. e.g. split(/\n/)


text:
Q: Why tailwindcss support does not work in PhpStorm 2019.3.4? In PhpStorm 2019.3.4 I work with tailwindcss 2 In laravel 8 app and I installed tailwindcss plugins
I found : Tailwind Formatter, Tailwind CSS Smart Completions, Tailwind Intellisense
But I do not see any tailwindcss support in my PhpStorm in many cases when I need it. In blade.php file having line like
  ...
  <div class="my-2 w-100 admin_content_text_color">
</div>
  ...

adding " px" in end of class definitions I want to see autocomplete hint on existing tailwind
classes
Simialr in my custom resources/css/app.css
.editor_form_inactive_tab {
    @apply text-gray-400y;
}

entering "text-red-" I do not see any autocomplete hint I expect.
In my webpack.mix.js I have :
mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        require("tailwindcss"),
    ]);

Seems none of installed plagins I wrote above nned any additive options in setting ?
Thanks!

A: Official Tailwind support has been introduced in PhpStorm 2020.3 (see https://blog.jetbrains.com/webstorm/2020/11/webstorm-2020-3/), you can't expect it to work in v.2020.2. Please consider upgrading


text:
Q: Removing a vagrant file I see .nfs0000000000b869e300000001 I removed a file and now I see:
$ ls
total 64
-rw-rw-r-- 1 502 17229 Sep 17 16:42 page_object_methods.rb
drwxrwxr-x 7 502   238 Sep 18 18:41 ../
-rw-rw-r-- 1 502 18437 Sep 18 18:41 new_page_object_methods.rb
-rw-r--r-- 1 502 16384 Sep 18 18:42 .nfs0000000000b869e300000001
drwxrwxr-x 5 502   170 Sep 21 13:48 ./
13:48:11 *vagrant* ubuntu-14 selenium_rspec_conversion

and if I try to remove it:
$ rm .nfs0000000000b869e300000001
rm: cannot remove '.nfs0000000000b869e300000001': Device or resource busy

What does this indicate?  What should I do

A: User @mtak on another question suggests:
You could try runningfuser /path/to/.nfsto check which process is using the .nfs file. – mtak May 2 '14 at 9:13
^^^^^ That works ^^^^^
And kill off the offending process to cause it to release the file handle.
e.g.
$ rm -rf ~/Downloads
rm: cannot remove '/nfshome/x/Downloads': Directory not empty
$ ls -alstr ~/Downloads
total 38864
  972 -rw-r--r--   1 x users   988438 Dec 20  2016 .nfs00000000018d307a00000369
31812 -rw-r--r--   1 x users 32503812 Dec 20  2016 .nfs00000000018d307f0000036b
  636 drwx--x--x 134 x y   647168 Aug 28 10:37 ..
  240 drwxr-xr-x   2 x y   241664 Aug 28 10:43 .
$ rm -rf ~/Downloads
rm: cannot remove '/na-homes/x/Downloads/.nfs00000000018d307a00000369': Device or resource busy
rm: cannot remove '/na-homes/x/Downloads/.nfs00000000018d307f0000036b': Device or resource busy

$ fuser /nfshome/x/Downloads/.nfs00000000018d307400000367
/nfshome/x/Downloads/.nfs00000000018d307400000367:  8231m
$ ps -elf |grep 8231
0 S x     1493 15153  0  80   0 - 28177 pipe_w 10:55 pts/39   00:00:00 grep --color=auto 8231
0 S x     8231  7660  0  99   - - 481464 poll_s Jul19 ?       00:06:01 /usr/libexec/tracker-extract
$ kill 8231
$ kill 8231 # kill twice to check first kill worked, . .
            # escalate to kill -9 8231 if first kill didn't work, . .
            # use sudo or root or other user to kill if ownership prevents kill working.
-bash: kill: (8231) - No such process
$ rm -rf ~/Downloads

$ ls -alstr ~/Downloads/
ls: cannot access /nfshome/x/Downloads/: No such file or directory

YAY! Success.
YMMV of course.
It might be a different process sitting with the file open.
The tracker-extract process was restarted automatically after I killed it.
What is this tracker-extract thing ?
(I see this on centos/redhat)
https://stackoverflow.com/questions/26737900/tracker-extract-and-tracker-store-processes-consuming-huge-amount-of-ram
extra/tracker 1.2.3-1 (gnome)
    All-in-one indexer, search tool and metadata database

A: A file can be deleted while it's open by a process. When this happens, the directory entry is deleted, but the file itself (the inode and the content) remain behind; the file is only really deleted when it has no more links and it is not open by any process.
NFS is a stateless protocol: operations can be performed independently of previous operations. It's even possible for the server to reboot, and once it comes back online, the clients will continue accessing the files as before. In order for this to work, files have to be designated by their names, not by a handle obtained by opening the file (which the server would forget when it reboots).
Put the two together: what happens when a file is opened by a client, and deleted? The file needs to keep having name, so that the client that has it open can still access it. But when a file is deleted, it is expected that no more file by that name exists afterwards. So NFS servers turn the deletion of an open file into a renaming: the file is renamed to .nfs… (.nfs followed by a string of letters and digits).
You can't delete these files (if you try, all that happens is that a new .nfs… appears with a different suffix). They will eventually go away when the client that has the file open closes it. (If the client disappears before closing the file, it may take a while until the server notices.)

A: As NFS is "stateless", there need to be a way to emulate the UNIX method of opening a file and then remove it keeping an open filehandle.
Any NFS file operation causes the chain:
open(); seek-last-off(); doit(); close();
to be run and this is the reason why NFS survives a server reboot.
Once the process on the client that opened the old file terminates, the file will disappear.
Correctly implemented fileservers will run a script each night that removes all such files that are older than a week. The reason is that in case the client reboots while holding such a file, the file would stay forever.

A: Some other process is likely still using the file (that is, has an open filehandle to it). Either ignore the file, or use lsof or the like to try to find what process has that file open (or reboot everything!).

A: I faced a similar situation, but in my case I am not able to delete a file created by my own program. I was sure of this because it was present in a directory created by my program. I did not know where and when I ran that program.
Solution: I simply exited from all my terminals. I logged in again and simply deleted the file.
P.S. My answer is only valid for the scenerio I have specified.


text:
Q: facebook c# sdk page tab application First of all, sorry for my newbie question...
I am google-ing for something like that for days, but still no luck.
I can't find any examples for using the Facebook C# SDK
with Facebook Page Tab applications.
Unfortunately most examples are for Facebook Canvas applications
and I can't make them work with a Page Tab application.
I really need to see a working example of the following:

*

*Get whether the User Liked my page, or not.

*If the User Liked my page, show an "authorize" link/button.

*On clicking the "authorize" link/button, ask for User's permission to:
 access his info, post to his wall, etc.
(using facebook's usual dialogs for that)

*After the User accepts, redirect him to the "member's only" page.
(...inside the tab application frame. not a canvas-type frame)

*Whenever an "authorized" User comes back to my tab app,
he should be automaticaly redirected to the same "member's only" page.
(I suppose if I have an example for the previous steps,
I won't have a problem figuring this out)

A: Building app for canvas is the same as making it for Page tab. The only difference is the so called "fangate" (liker/non-likers).
This can be used out of the box only on page tabs and the only thing you need is to decode the signed request passed by facebook.
There is good explanation for doing this with C# here:
Decode Signed Request Without Authentication


text:
Q: How to capture output of a command window that is started by another application? Problem
I use a GUI application that writes debug output to a command window (only there, no other log). When the application crashes, the command window disappears together with all the output.
Question
How can I capture the output of the command window in a text file?
What I've tried
As I found no way of interacting with the command window, I resorted to screen recording. This is far from ideal as I cannot select or copy the text easily.

A: Since prog.exe > file.txt works for all but the last output, we now know that
the GUI program uses standard output that can be captured under the right conditions.
You will need to use PowerShell with the cmdlet is called
Tee-Object
whose alias is tee (in the spirit of Linux).
This command outputs both to a file and also passes it to the standard output.
The PowerShell command to use may look like:
Start-Process -FilePath "\path\prog.exe" | tee -filepath \path\file.txt

This will send the output to \path\file.txt as well as to the console.

A: Maybe there is a way to just "get" the data from the cmd window somehow. Like read it out from the memory or something. But I never seen such methods. I would simply use AutoHotkey.
Example: https://autohotkey.com/board/topic/9953-how-to-capture-intire-cmdexe-text/
1) Find cmd window by Title. AutoHotkey has a tool called "Window Spy". https://amourspirit.github.io/AutoHotkey-Snippit/WindowSpy.html Use this tool to get the title/window details so you can later "look" for it.
2) You basically just need the sequence to capture current output. Such as:
Alt+Space;E;S; # mark everything
Alt+Space;E;Y; # copy
2) Make the script run periodically. See loop and sleep keywords.
You can even toggle the script via a variable:
F12::
stopit = 0
While stopit = 0
{
    Loop, 70
    {

        Click
        if stopit = 1
        {
                exit
        }
    }
    Sleep, 2000

}
return

F10::
    stopit = 1
return

Source - user: left1000, via: https://autohotkey.com/board/topic/54-loop-until-key-is-pressed/
3) Just write out the content you grab into a text file. https://www.autohotkey.com/docs/commands/FileAppend.htm
I believe this could be copy-pasted together from the Autohotkey docs and Google within ~5-15 minutes. I cannot provide you a complete example / script because I don't know what application is this, I cannot test the script, etc. So this is as much as I can help in this case.


text:
Q: Displaying a table from a list I have created following table from DynamoDB service in Amazon Web Services:

which I want to display on an ASP.NET application. The problem is that it returns a NullReferenceException, and I can't event debug it. I have created a ViewModel as follows:
  public class DynamoDB
  {
    public int userNO { get; set; }

    public string firstName { get; set; }

    public string lastName { get; set; }
  }

and an extra class to access the DynamoDB table from AWS:
public class DynamoContext
{
    Credentials.Credentials credentials = new Credentials.Credentials();

    public IEnumerable<DynamoDB> GetProducts()
    {
        IEnumerable<DynamoDB> products = null;
        RegionEndpoint region = RegionEndpoint.GetBySystemName("eu-central-1");
        AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials.AccessKey, credentials.SecretAccessKey, region);

        DynamoDBContext context = new DynamoDBContext(client);
        products = context.Scan<DynamoDB>();

        return products;
    }
}

and a controller which has to access this IEnumerable and convert it to a List of objects.
public class DynamoController : Controller
{
    //
    DynamoContext dc = new DynamoContext();
    [HttpGet]
    public ActionResult Index()
    {
        List<DynamoDB> objList = dc.GetProducts().ToList();
        return View("users", objList);
    }
}

and finally my View which has to display the table on the Index page:
@{
ViewBag.Title = "Home Page";
}

@model List<FinalApplication.Models.DynamoDB>

Home Monitoring Application

    @foreach (FinalApplication.Models.DynamoDB objUser in Model)
    {

            @objUser.userNO.ToString()
            @objUser.firstName
            @objUser.lastName

    }

When running the application in Google Chrome, it returns following exception:

I have even set some breakpoints in the DynamoContext class, to check whether it gets any data from AWS, but the Exception occurs even before they are triggered. How can I check where the issue is ?.

A: Add IEnumerable on the top of your view, above than viewbag
@model IEnumerable<FinalApplication.Models.DynamoDB>

and remove that line @model List<FinalApplication.Models.DynamoDB>

A: in view try to use IEnumerable instead of List


text:
Q: Is it possible to take screenshot of a webbrowser control behind other controls? I am able to take a screenshot of the win form at the location of the webbrowser control and save this screen capture. This method requires that the webbrowser to be on top.
But if the webbrowser is behind another control, how can I accomplish this?

A: You may probably want to look at headless webbrowsers like http://phantomjs.org/ it expicitly states ability to take screenshots while being headless (=not shown on screen)


text: Q: Azure cost managment data exported directly into databricks Is there any way to export azure cost management data directly in databricks and flatten tags which is string column as json object into df columns.


text: Q: Rigour papers on the topic of benchmarking classifiers Being motivated by the paper On Comparing Classifiers: Pitfalls to Avoid and a Recommended Approach, I would like to ask for any rigour papers on the topic of benchmarking classifiers?


text:
Q: How to rename dictionary keys to follow sequential order? My code processes dictionaries, and most dictionaries come in the following format:
#Default
d = {0:'a', 1: 'b', 2:'c', 3:'d', 4: 'e', 5:'f', 6:'g', 7:'h', 8:'i', 9:'j', 10:'k'}

In some cases however, dictionaries miss key-value pairs and come in a following format:
d1 = {0:'a', 1: 'b', 2:'c', 3:'d', 4: 'e', 6:'g', 7:'h', 8:'i', 9:'j', 10:'k'}
d2 = {1: 'b', 2:'c', 4: 'e', 6:'g', 7:'h', 8:'i', 9:'j'}

How would I rearrange the keys in these dictionaries to follow sequential format as seen in the expected output below?
expected1 = {0:'a', 1: 'b', 2:'c', 3:'d', 4: 'e', 5:'g', 6:'h', 7:'i', 8:'j', 9:'k'}
expected2 = {0: 'b', 1:'c', 2: 'e', 3:'g', 4:'h', 5:'i', 6:'j'}

A: A simple dictionary comprehension:
d2 = {i: v for i, v in enumerate(d2.values())}

As said by Ma0 in comments, a list would be more adequate. You can retrieve the list as d1.values().


text:
Q: Yocto / Bitbake: How to do something with every binary build by the system? Use Case:
I am developing a IoT Linux system for my Raspberry Pi. Read Only rootfs is not an option, because I want to upgrade executables on the fly. What I thought is my solution: I develop a tool which can sign ELF-Files (Linux executables and libraries). It signes the sections with some pub/priv key, saves the signature into a section and checks the file before executing it (like DigSig but with the help of openssl-lib). The library loader(glibc) is also modified to check all linux ".so"-libraries before loading it. At the end I want to publish the project and my solution under an open source license. Currently it is not finish and far away from stability.
Develoment state:

*

*ELF-File Sign tool is finished.

*Kernel is modified (new security module / own syscall function to check elf-binary signature).

*Glibc is modified and patched for my local source.

*Quemu is patched to support my new syscall.

*Yocto environment is set up. And the image runs on my RaspberryPi 2 test machine.

So far so good. I have the feeling I am very close to my solution.
Now I need to:
Make Yocto / bitbake enable that ALL ELF-Files are signed after the build process. Best would be if the rpm-files have already the signed ELF-files included. And the signing process would be done by one recipe for all the other packages. (So I do not want to create a post installation script which modifies only the files on the root folder).
After searching hours in google and checking the documentation of yocto I have no solution. It would be very great if someone can help me.

A: I think you can customize package.bbclass in poky/meta/classes, in particular, split_and_strip_files function helps to strip every files
oe.utils.multiprocess_exec(sfiles, oe.package.runstrip)
You can add signing then add your custom tools in poky/meta/lib/oe/package.py


text:
Q: Fast children zombies in the original Dawn of the dead Near the start of Dawn when they stop to refuel the helicopter one of the characters is attacked by two zombified children that appear to be moving much faster than any of the other zombies.
Was this just a production goof due to using child actors, are they not actually moving faster or would there be some in universe reason that children zombies would move faster?

A: Here is the clip you referenced. at time 3:34

The children seem to be trotting, almost running.  It is never explained in the movie, but my guess is that having a lower center of gravity they have less trouble balancing and can move quicker.


text:
Q: PHP - Decode JSON array and use in foreach loop I am using an API and decoded the JSON array into a PHP array, but it isn't giving me the specific values when I use a foreach loop.  Here is a snippet of the original JSON array:
"playerCredentials": {
    "observerEncryptionKey": "blahblah",
    "dataVersion": 0,
    "playerId": 8675309,
    "serverPort": 0,
    "observer": true,
    "summonerId": 0,
    "championId": 0,
    "observerServerIp": "111.111.111.111",
    "gameId": 123456789,
    "observerServerPort": 4388,
    "lastSelectedSkinIndex": 0
  },

then, I ran this code:
$array = json_decode($json_array, true);

which then turned the above into:
    { ["playerCredentials"]=> array(11)
    {
    ["observerEncryptionKey"]=> string(32) "blahblah"
    ["dataVersion"]=> int(0)
    ["playerId"]=> int(8675309)
    ["serverPort"]=> int(0)
    ["observer"]=> bool(true)
    ["summonerId"]=> int(0)
    ["championId"]=> int(0)
    ["observerServerIp"]=> string(14) "111.111.111.111"
    ["gameId"]=> int(123456789)
    ["observerServerPort"]=> int(4338)
    ["lastSelectedSkinIndex"]=> int(0)
    }

however, when I run this foreach loop:
foreach($array['playerCredentials'] as $stats) {
echo $stats['playerId'];
}

all I get as a return is 82 (I don't even know where that comes from).  However, if I run this:
foreach($array['playerCredentials'] as $stats) {
    echo $stats."
";
}

I get all of the information in the whole array:
blahblah
0
8675309
0
true
0
0
111.111.111.111
123456789
4338
0

How can I just get one piece of it?
{
  "playerCredentials": {
    "observerEncryptionKey": "blahblah",
    "dataVersion": 0,
    "playerId": 8675309,
    "serverPort": 0,
    "observer": true,
    "summonerId": 0,
    "championId": 0,
    "observerServerIp": "111.111.111.111",
    "gameId": 1347503269,
    "observerServerPort": 8088,
    "lastSelectedSkinIndex": 0
  },
  "dataVersion": 0,
  "gameName": "match-1347503269",
  "reconnectDelay": 0,
  "game": {
    "practiceGameRewardsDisabledReasons": {
      "array": []
    },
    "glmSecurePort": 0,
    "queuePosition": 0,
    "playerChampionSelections": {
      "array": [
        {
          "spell1Id": 4,
          "spell2Id": 7,
          "championId": 25,
          "summonerInternalName": "nameone",
          "selectedSkinIndex": 0,
          "dataVersion": 0
        },
        {
          "spell1Id": 12,
          "spell2Id": 4,
          "championId": 13,
          "summonerInternalName": "nametwo",
          "selectedSkinIndex": 0,
          "dataVersion": 0
        }
]

A: In your loops, $stats is referring to the value of each element in the array. I think you're looking for $array['playerCredentials']['playerId'];. If you want to iterate over all properties of a player, you could do this:
foreach ($array['playerCredentials'] as $key => $value) {
    printf('%s => %s
', $key, $value);
}

A: You can try like this
<?php
$json_array ='{
    "playerCredentials": {
        "observerEncryptionKey": "blahblah",
        "dataVersion": 0,
        "playerId": 8675309,
        "serverPort": 0,
        "observer": true,
        "summonerId": 0,
        "championId": 0,
        "observerServerIp": "111.111.111.111",
        "gameId": 123456789,
        "observerServerPort": 4388,
        "lastSelectedSkinIndex": 0
    }
}';

$array = json_decode($json_array, true);

foreach($array as $playerCredentials) {
echo $playerCredentials['playerId'];
}

Output

8675309

demo

A: You could do it like this if using PHP > 5.4:
<?php
$json='{
    "playerCredentials": {
        "observerEncryptionKey": "blahblah",
        "dataVersion": 0,
        "playerId": 8675309,
        "serverPort": 0,
        "observer": true,
        "summonerId": 0,
        "championId": 0,
        "observerServerIp": "111.111.111.111",
        "gameId": 123456789,
        "observerServerPort": 4388,
        "lastSelectedSkinIndex": 0
    }
}';

$playerCredentials = json_decode($json, true)["playerCredentials"];

foreach($playerCredentials as $key => $value) {
    echo "key: ".$key."\n";
    echo "value: ".$value."\n";
}

Here's a demo: https://eval.in/137205
Or, if using PHP < 5.4, you wouldn't be able to nest the array access with json_decode, so you'd just do it like this:
<?php
$json='{
    "playerCredentials": {
        "observerEncryptionKey": "blahblah",
        "dataVersion": 0,
        "playerId": 8675309,
        "serverPort": 0,
        "observer": true,
        "summonerId": 0,
        "championId": 0,
        "observerServerIp": "111.111.111.111",
        "gameId": 123456789,
        "observerServerPort": 4388,
        "lastSelectedSkinIndex": 0
    }
}';

$result = json_decode($json, true);

foreach($result["playerCredentials"] as $key => $value) {
    echo "key: ".$key."\n";
    echo "value: ".$value."\n";
}

Here's a demo: https://eval.in/137209


text:
Q: C++ STL Map : Map.count(element) takes less time than Map[element] I was trying this problem on leetcode,
https://leetcode.com/problems/naming-a-company/description/ .
I've observed the following
My Code :
long long distinctNames(vector<string>& ideas) {
        unordered_map<string,bool> isPresent;
        vector<vector<long long>> dp(26,vector<long long>(26,0));
        int n = ideas.size();
        long long ans = 0;

        for(int i = 0; i < n; i++)
        isPresent[ideas[i]] = true;

        for(int i = 0; i < n; i++)
        {
            char x = ideas[i][0];
            string ts = ideas[i];

            for(int j = 0; j < 26; j++)
            {
                char y = 'a' + j;
                ts[0] = y;
                if(!isPresent[ts])
                    dp[x-'a'][j]++;
            }

        }

        for(int i = 0; i < 26; i++)
        {
            for(int j = 0; j < 26; j++)
            {
                if(i==j) continue;
                ans += (dp[i][j] * dp[j][i]);
            }
        }

        return ans;

    }

This code was getting TLE (85/89).
But, in the same code, if I replace
!isPresent[ts]

with
!isPresent.count(ts)

Same code runs much faster and passes.
Anyone can explain why ?

A: isPresent[ts] returns a reference to a map value object (so you can write isPresent[ts] = something. So if ts is not present in the map, then  isPresent[ts] must default construct a map entry so that it has something to return a reference to. This is the reason that map::operator[] is not const.
isPresent.count(ts) has no such problems. If the ts key is not present then the map is unchanged.

A: operator[] on std::unordered_map inserts a default constructed element if none is yet present (which is also why the operator doesn't work on a const object.) Insertion potentially requires allocating memory or other somewhat slow things. Calling count does not, nor would e.g. find.


text:
Q: io.emit fails to emit to all clients I am trying to implement a "leave game" feature in a simple socket.io game and I cannot figure out why io.emit notifies only the socket of the client leaving the game. Here is my socket.js code:
io.on("connection", sock => {

    sock.on('joinGame', name => {
       inc++
       if(name === 'guest') name = name + inc.toString()
       addToGame(inc, name) // adds player to a new Map()
       io.emit('joinedGame', name)
    })

    sock.on('findPlayersInGame', () => {
       getAllPlayersInGame(io, threeOrMore)
     // check to see if the client is notified when a new user joins
       io.emit('newPlayerJoined', 'new player joined')
    })

    sock.on('leaveGame', name => {
       io.emit('leftGame', uniquePlayers)
    })

On the client, I am handling the socket communication along with my state management in a MobX store. Here is my GameStore.js code:
export class GameStore {
constructor(aGame) {
    extendObservable(this, {
        players: [],
        game: aGame,
        menuVisibility: true,
        play: action((id, username) => {
            this.menuVisibility = false
            username === undefined ? this.game.setName("guest") : this.game.setName(username)

            // join game with given username
            sock.emit('joinGame', this.game.playerName)

            // after joining, if the username is 'guest' change name to unique guest name provided by server
            sock.on('joinedGame', name => {
                if(this.game.playerName === 'guest') this.game.setName(name)
                console.log(this.game.playerName + " joined the game")
            })
            // populate player list with all players in game room
            this.loadPlayers()
        }),
        quitGame: action(() => {
            //this.menuVisibility = true
            sock.emit('leaveGame', this.game.playerName)
            sock.on('leftGame', players => { // this should be logged to all clients
                console.log('updated player list', players)
                this.players = players
            })
        }),
        loadPlayers: action(() => {
            sock.emit('findPlayersInGame', this.game.playerName)
            sock.on('loadPlayers', players => {
                console.log('loading players...')
                this.players = players
            })
            sock.on('newPlayerJoined', player => {
                console.log(player)
            })
        })
    })
  }
}

When I dispatch the quitGame action, the socket only emits to the client that is leaving the game. I need to update the player list in my store after someone leaves the game, but I cannot figure out why the other clients are not getting the message that someone left the game. io.emit seems to be working fine when a player joins a game.

A: It looks like you don't register the leftGame message handler until this client leaves the game.  Thus, none of the other clients who are still in the game yet have a handler for that message.  They are probably receiving the message, but don't yet have a handler for it so you don't see it.
Move this code:
        sock.on('leftGame', players => { // this should be logged to all clients
            console.log('updated player list', players)
            this.players = players
        })

so that it registers the event handler when the client wants to start receiving these messages (likely at startup).


text:
Q: How to download a file using jQuery I have a html button that calls a Jquery function. This function calls a [web Method] in my code-behind.  This Server-code will create (if need be) a file to be downloaded.  I return to the JQuery call the URL of my downloadable file.
This works when the file is an AVI file.
When I try to do it with an ogg file it is played in the browser Window.
How can I force a download from JQuery instead of playing the file?
My Code:
[Web Method]
public static ArrayList DownloadClip(string ClipValue, string SessionID,string Extension)
{
ListItem _item2 = new ListItem();
_item2.Text = 'MediaFilename';
_item2.Value = "OK";
_arr.Add(_item2);
return _arr;
}

[In ASP.NET Mark-Up Page]
This is just the code snippet that is for this part..
success: function (msg) {
$.each(msg.d, function () {
 if (this['Text'] == "ERROR") {
  $theDiv.html(this['Value']);
  return;
 }
 else {
  url = this['Text'];
  window.location = url;
 }
}

Thanks

A: As far as I know, there is no way to do this client-side. If you search around for a way of forcing a download server-side you'll probably have more success.


text:
Q: Ubuntu is kde styled after install AND removal I installed kubuntu-desktop and every thing was fine.  Then later when I actually logged in to Kde, I decided that I  still like Unity better so I ran sudo apt-get purge kubuntu-desktop && sudo apt-get autoremove.  After that bits and pieces of my Ubuntu/Unity have been Kde styled.  All browsers have Kde icons and some applications show 'About Kde' in their menus, all text fields have that 'bluesh glow' around them, etc.

What is still left of Kubuntu?
Note: I saw this question and this question, but both where outdated and didn't work.

A: Remove from your $HOME directory any file that is of the form.gtkrc  After removing such files, go back into your Appearance settings and change your theme to Ambiance or Radiance, apply, then move onto your preferred theme.

A: Please check the setting of Ubuntu in System Setting.
TO ensure you run the correct version, you should
   + Install unity GUi
   + Change setting
   + Reset computer again to change setting
I guess you change on an account but check on other account

A: I tried this under ubuntu 14.04. It removes all remaining traces of kde and reinstalls ubuntu-desktop.
sudo apt-get remove libkde3support4 k3b-data ntrack-module-libnl-0 libkrosscore4 libgpgme++2 libqapt2 oxygen-icon-theme libktexteditor4 libtaskmanager4abi5 kdenetwork-filesharing libkblog4 libchm1 plasma-widgets-addons libkimap4 plasma-netbook libkdeui5 libkdeclarative5 ttf-oxygen-font-family gtk3-engines-oxygen user-manager gpgsm libakonadi-kcal4 kdepim-kresources libruby1.9.1 plymouth-theme-kubuntu-logo libqt4-sql-mysql libmailtransport4 kde-telepathy-filetransfer-handler kde-zeroconf libkpimtextedit4 konsole liblastfm1 libqjson0 libtag-extras1 libkdecorations4abi1 libkdcraw23 libkpeople3 kdepimlibs-kio-plugins libqrencode3 libkparts4 libakonadiprotocolinternals1 libbalooxapian4 akonadi-server nepomuk-core-data libqca2 kubuntu-notification-helper kdemultimedia-kio-plugins libntrack0 kde-runtime-data cdparanoia libplasma-geolocation-interface4 quassel-data libkemoticons4 libmessagecomposer4 libweather-ion6 cdrdao libnepomukquery4a bluedevil libakonadi-notes4 libkmediaplayer4 libksieveui4 muon-discover libmicroblog4 libnetworkmanagerqt1 libqt4-qt3support libkcddb4 amarok-utils libmailcommon4 libktpcommoninternalsprivate7 libprocessui4a katepart libmusicbrainz5-0 libkwineffects1abi4 libreoffice-base libkdepim4 kaddressbook soprano-daemon libmessageviewer4 libkwinglesutils1 libsoprano4 libqapt2-runtime vcdimager libcln6 libvirtodbc0 libbaloopim4 okular libqca2-plugin-ossl libkonq5abi1 ubuntu-release-upgrader-qt python3-pyqt4 libkephal4abi1 libksba8 kdesudo libqoauth1 gnupg-agent libxerces-c3.1 kde-telepathy-data kdelibs5-plugins kcalc libqmobipocket1 systemsettings libkolabxml1 libsyndication4 libkjsapi4 libplasmagenericshell4 libksane0 libkprintutils4 knotes libkactivities6 libincidenceeditorsng4 lightdm-kde-greeter libreoffice-sdbc-firebird libiso9660-8 kubuntu-docs amarok gwenview libkcalcore4 virtuoso-opensource-6.1-common libkmbox4 virtuoso-opensource-6.1-bin libakonadi-contact4 libakonadi-socialutils4 plasma-widget-kimpanel kde-touchpad python3-dbus.mainloop.qt libqtscript4-gui python3-pykde4 plasma-widget-menubar libxcb-record0 libkcompactdisc4 kde-config-telepathy-accounts libkabc4 libkunitconversion4 okular-extra-backends plymouth-theme-kubuntu-text libcryptsetup4 ktorrent-data libknewstuff3-4 kde-workspace-kgreet-plugins kde-config-tablet gstreamer0.10-qapt akregator libxcb-xtest0 libnepomukutils4 odbcinst1debian2 kate libkmanagesieve4 libprocesscore4abi1 libqtscript4-network libksane-data ibus-qt4 ttf-dejavu-core libyaml-0-2 libkxmlrpcclient4 plasma-nm libpam-ck-connector libqgpgme1 print-manager libksignalplotter4 libkipi-data klipper libakonadi-kmime4 gtk2-engines-oxygen kde-telepathy-text-ui libkhtml5 libkcal4 libkmime4 ksysguardd kontact libmailimporter4 libakonadi-calendar4 libprison0 libsendlater4 libntrack-qt4-1 libsignon-qt1 libkldap4 libkfile4 kubuntu-settings-desktop libpoppler-qt4-4 kamera libbaloofiles4 libtelepathy-qt4-2 libnoteshared4 libakonadi-kde4 libreoffice-kde icoutils libgrantlee-gui0 socat libkdepimdbusinterfaces4 audiocd-kio libmodemmanagerqt1 liboath0 libmessagecore4 libqtglib-2.0-0 kde-baseapps-bin kubuntu-driver-manager libattica0.4 libmygpo-qt1 libkdesu5 libknewstuff2-4 dragonplayer libdlrestrictions1 libgps20 kde-telepathy-send-file libstreams0 libkidletime4 libkateinterfaces4 libknotifyconfig4 qapt-deb-installer libtemplateparser4 about-distro dolphin kinfocenter libplasmaclock4abi4 amarok-common kaccessible libqtscript4-uitools libxcb-composite0 libkcalutils4 libreoffice-java-common usb-creator-kde libkdecore5 kdelibs-bin plasma-desktop skanlite kmag kdegraphics-strigi-analyzer nepomuk-core-runtime plasma-scriptengine-javascript libperl4-corelibs-perl qapt-batch kde-wallpapers-default libloudmouth1-0 libqaccessibilityclient0 libktnef4 libflac++6 libnepomuk4 libkleo4 odbcinst pam-kwallet libstreamanalyzer0 libkdcraw-data docbook-xsl libkntlm4 libopenconnect2 software-properties-kde ktorrent krdc kmousetool kde-workspace-data libqtscript4-core partitionmanager cryptsetup libvcdinfo0 libboost-thread1.54.0 libkfbapi1 libxcb-damage0 ruby1.9.1 libkcmutils4 libkpimidentities4 libreoffice-style-oxygen k3b libkworkspace4abi2 colord-kde libkfilemetadata4 kde-style-oxygen libdebconf-kde0 libktorrent-l10n libpolkit-qt-1-1 libkolab0 libepub0 libkdgantt2-0 kubuntu-settings-netbook libqtscript4-xml kubuntu-web-shortcuts libtelepathy-logger-qt4-1 libkactivities-models1 libkpimutils4 freespacenotifier pinentry-qt4 kde-config-gtk-style libkgapi2-2 baloo libkubuntu0 python3-sip kmix libkio5 libxml2-utils ksnapshot libktorrent5 libakonadi-kabc4 libpimcommon4 kde-config-whoopsie libkpgp4 khelpcenter4 oxygen-cursor-theme shared-desktop-ontologies libkexiv2-data libplasma3 muon-updater kde-config-pimactivity kde-telepathy libaccounts-qt1 kdepasswd libqtscript4-sql libkexiv2-11 libkontactinterface4 libmessagelist4 kde-telepathy-integration-module kdepim-runtime libkscreen1 && sudo apt-get install ubuntu-desktop


text:
Q: DomainContext not being generated in RIA Service for Silverlight 4 I have added my domain service but when I build my web project the DomainContext never gets generated. I am new to RIA Services and trying to learn but I am really stuck.
Here is my Domain Service
Option Compare Binary
Option Infer On
Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Linq
Imports System.ServiceModel.DomainServices.Hosting
Imports System.ServiceModel.DomainServices.Server
Imports Wellness.BL
Imports System.Collections.ObjectModel

'TODO: Create methods containing your application logic.

<EnableClientAccess()> _
Public Class EventScheduleService
    Inherits DomainService

    Public Function GetEventSchedule(ByVal ScheduleYear As Integer) As IEnumerable(Of Models.EventSchedule)
        Return DataServices.EventSchedulesDataService.GetEventSchedule(ScheduleYear)
    End Function

End Class

A: Maybe Models.EventSchedule, the class that is the base for your IEnumerable, is in a library that you have referenced in the Web project but can not be referenced in the client as it is not a Silverlight library?
I think that would prevent the EventScheduleDataContext from being generated in the client.
A simple test would be to change base of the IEnumerable to a class that lives in the Web project.

A: I had this problem also. My problem was that Visual Studio was set to Release mode. Setting it to Debug mode solved it.


text:
Q: Neural Network: Handling unavailable inputs (missing or incomplete data) Hopefully the last NN question you'll get from me this weekend, but here goes :)
Is there a way to handle an input that you "don't always know"... so it doesn't affect the weightings somehow?
Soo... if I ask someone if they are male or female and they would not like to answer, is there a way to disregard this input? Perhaps by placing it squarely in the centre? (assuming 1,0 inputs at 0.5?)
Thanks

A: You probably know this or suspect it, but there's no statistical basis for guessing or supplying the missing values by averaging over the range of possible values, etc.
For NN in particular, there are quite a few techniques avaialble. The technique i use--that i've coded--is one of the simpler techniques, but it has a solid statistical basis and it's still used today. The academic paper that describes it here.
The theory that underlies this technique is weighted integration over the incomlete data. In practice, no integrals are evaluated, instead they are approximated by closed-form solutions of Gaussian Basis Function networks. As you'll see in the paper (which is a step-by-step explanation, it's simple to implement in your backprop algorithm.

A: Neural networks are fairly resistant to noise - that's one of their big advantages. You may want to try putting inputs at (-1.0,1.0) instead, with 0 as the non-input input, though. That way the input to the weights from that neuron is 0.0, meaning that no learning will occur there.
Probably the best book I've ever had the misfortune of not finishing (yet!) is Neural Networks and Learning Machines by Simon S. Haykin. In it, he talks about all kinds of issues, including the way you should distribute your inputs/training set for the best training, etc. It's a really great book!