text:
Q: How to import data from Excel to mysql Database in Laravel? (php, laravel, mysql) [Update: csv file is succeed in importing data to mysql database, but xls/xlsx still got 'Undefined offset: 1' error]
When I input the Excel file and submit it to import, what I got is error 'Undefined offset: 1'
When I do dd($row) what I got is somehow working?

array:3 [▼   0 => 1   1 => "XI TKJ"   2 => "Kelas XI TKJ" ]
Screenshot of dd($row) result

Error:

Data in excel I want to input:

Apparently, there's already data on the table but I don't know if it would affect the result or not:

File that got the error -> jurusanImport.php(updated)
use App\jurusan;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithConditionalSheets;

class jurusanImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    use WithConditionalSheets;
    public function conditionalSheets(): array
    {
        return [
            'Worksheet 1' => new FirstSheetImport(),
            'Worksheet 2' => new SecondSheetImport(),
            'Worksheet 3' => new ThirdSheetImport(),
        ];
    }
    public function model(array $row)
    {
        dd($row);
        return new jurusan([
            'nama_jurusan' => $row[1],
            'deskripsi' => $row[2],
        ]);
    }
}

web.php
Route::post('/Admin/Jurusan/import_excel', 'AdminController@import_Jurusan')
    ->middleware('role:Admin');
Route::get('/admin/Jurusan/List', 'AdminController@showJurusanList')
    ->middleware('role:Admin');

AdminController.php
public function import_Jurusan(Request $request)
    {
    $user = Auth::user();
    $this->validate($request, [
        'file' => 'required|mimes:csv,xls,xlsx'
    ]);
    $file = $request->file('file');
    $nama_file = rand().$file->getClientOriginalName();
    $file->move('file_teacher',$nama_file);
    $import = new jurusanImport;
    $import->onlySheets('Worksheet 1');
    Excel::import($import, public_path('/file_teacher/'.$nama_file));
    Session::flash('sukses','Data Siswa Berhasil Diimport!');
    return redirect()->back();
    }
    public function showJurusanList(Request $request)
    {
        $user = Auth::user(); // Untuk Photo Profile
        $jurusan = jurusan::get(); // Show, atau Get All "Materi"
        return view('pages.admin.kelas.showjurusan', compact('jurusan', 'user') );
    }

Model jurusan.php
protected $fillable = [
    'nama_jurusan', 'deskripsi',
];

protected $table = 'jurusan';

How can I solve this?

A: You have multiple sheet in your xls file. You can check https://docs.laravel-excel.com/3.1/imports/multiple-sheets.html#selecting-sheets-by-worksheet-index
This is not your actual code. I am just sharing to you for reference.
namespace App\Imports;

use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithConditionalSheets;

class UsersImport implements WithMultipleSheets
{
    use WithConditionalSheets;

    public function conditionalSheets(): array
    {
        return [
            'Worksheet 1' => new FirstSheetImport(),
            'Worksheet 2' => new SecondSheetImport(),
            'Worksheet 3' => new ThirdSheetImport(),
        ];
    }
}

and in controller
$import = new UsersImport();
$import->onlySheets('Worksheet 1', 'Worksheet 3');

Excel::import($import, 'users.xlsx');


text:
Q: Apache kafka producer does not store data I am trying to access kafka deployed on AWS server with public IP , however when trying to connect it and send some data i receive no response and the server connection is closed.Following is my producer code --
public SensorDevice() {
    Properties props = new Properties();
    props.put("metadata.broker.list", "myip-xyz:9092");
    props.put("bootstrap.servers", "myip-xyz:9092");
     props.put("serializer.class", "kafka.serializer.StringEncoder");
    props.put("key.serializer",
            "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer",
            "org.apache.kafka.common.serialization.StringSerializer");
    // props.put("partitioner.class", "example.producer.SimplePartitioner");
    props.put("request.required.acks", "1");
    producer = new KafkaProducer<String, String>(props);

}

public void run() {

    Object objectData = new Object();

    ProducerRecord<String, String> data = new ProducerRecord<String, String>(
            topic, "mytopic", objectData.toString());
    System.out.println(data);
    Future<RecordMetadata> rs = producer.send(data,
            new org.apache.kafka.clients.producer.Callback() {

                @Override
                public void onCompletion(RecordMetadata recordMetadata,
                        Exception arg1) {
                    System.out.println("Received ack for partition="
                            + recordMetadata.partition() + " offset = "
                            + recordMetadata.offset());
                }
            });

    try {
        String msg = "";
        RecordMetadata rm = rs.get();
        msg = msg + " partition = " + rm.partition() + " offset ="
                + rm.offset();
        System.out.println(msg);
    } catch (Exception e) {
        System.out.println(e);
    }
    producer.close();

}

I have also tried adding advertise.host.name to server.properties config file.
Kafka shows following error --
>     [2015-04-24 09:06:35,329] INFO Created log for partition [mytopic,0] in /tmp/kafka-logs with properties {segment.index.bytes ->
> 10485760, file.delete.delay.ms -> 60000, segment.bytes -> 1073741824,
> flush.ms -> 9223372036854775807, delete.retention.ms -> 86400000,
> index.interval.bytes -> 4096, retention.bytes -> -1,
> min.insync.replicas -> 1, cleanup.policy -> delete,
> unclean.leader.election.enable -> true, segment.ms -> 604800000,
> max.message.bytes -> 1000012, flush.messages -> 9223372036854775807,
> min.cleanable.dirty.ratio -> 0.5, retention.ms -> 604800000,
> segment.jitter.ms -> 0}. (kafka.log.LogManager)
>     [2015-04-24 09:06:35,330] WARN Partition [mytopic,0] on broker 0: No checkpointed highwatermark is found for partition [mytopic,0]
> (kafka.cluster.Partition)
>     [2015-04-24 09:07:34,788] INFO Closing socket connection to /50.156.87.157. (kafka.network.Processor)

Please help me resolve this issue!

A: EC2 IP addresses are internal. You may face some issues when dealing with EC2 server running kafka and zookeeper. Try setting advertised.host.name and advertised.port variables in your server.properties file.
advertised.host.name should be IP address of the EC2 server.
advertised.port should be kafka port. By default it is 9092.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FileNotFoundException when loading assembly of ASP.NET Core MVC 5 project I'm trying to explore an assembly that belongs to an ASP.NET Core MVC project. The project was made with .NET 5.
The problem is, when I try to explore the assembly's types, it throws a FileNotFoundException with the following message: Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado.
Issuing a dotnet build command compiles the project without problems.
Exploring the corresponding .csproj file, I found that the Microsoft.AspNetCore.Mvc.Core dependency is not declared in the project file, but the SDK indicated in the project file's XML root is Microsoft.NET.Sdk.Web, and I understand that marks the project as an ASP.NET Core project, but I can't find a way to bring the necessary dependencies to load the assembly.
Code as follows.
Code that loads the assembly:
var reader_context = new ReaderLoadContext(artifact_dir);
var assembly_path = ""; //Path of the compiled assembly
var assembly = reader_context.LoadFromAssemblyPath(assembly_path);
//Here's where it crashes
var target_types = assembly.ExportedTypes.Where(t => t.BaseType != null && t.BaseType.Name == "ControllerBase").ToArray();

ReaderLoadContext's code:
public class ReaderLoadContext : AssemblyLoadContext
{
    private AssemblyDependencyResolver _resolver;

    public ReaderLoadContext(string readerLocation)
    {
        _resolver = new AssemblyDependencyResolver(readerLocation);
    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        var assembly_path = _resolver.ResolveAssemblyToPath(assemblyName);
        if (assembly_path != null)
        {
            return LoadFromAssemblyPath(assembly_path);
        }

        return null;
    }

    protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
    {
        var library_path = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
        if (library_path != null)
        {
            return LoadUnmanagedDllFromPath(library_path);
        }
        return IntPtr.Zero;
    }
}

A: Turns out this is a known limitation of AssemblyLoadContext and one of the solutions (more like an ugly workaround) is to add a reference to the missing framework in the application that explores the desired assembly. I added a PackageReference item in my app's .csproj file and now it properly loads the assembly I want to scan.
I don't know if I should mark this as an answer. In one hand, it does what I need it to. OTOH, it forces the developer to add all possible framework references beforehand just in case, and if Microsoft (or a 3rd party) releases another framework, it requires releasing a new version of the app.
So hopefully someone knows a more elegant solution.
Thanks to @deepak-msft and everyone else for the help.


text:
Q: Data Validation in Apps Script (Between Two Numbers) Trying to set a cell's data validation to be between two numbers namely, 1 and the balance of items in a budget.  It keeps giving the following error:

Oct 12, 2022, 9:41:14 PM Error Exception: The parameters
(number,String) don't match the method signature for
SpreadsheetApp.DataValidationBuilder.requireNumberBetween.
at applyQtyValidation(Code:242:8)
at getQtyValidationData(Code:233:3)
at onEdit(Code:59:7)

Please help...
//Global variables
var reqSheetName = "Material Requisition";

var colStructure = 1;

var colComponent = 2;

var colWorks = 3;

var colItem = 4;

var colQty = 5;

var colUnit = 6;

var colBalance = 7;

var colBudgetCode = 8;

var colDuplicate = 18;

var ss = SpreadsheetApp.getActiveSpreadsheet();

var wsBudget = ss.getSheetByName("Budget");

var wsRequisition = ss.getSheetByName(reqSheetName);

var rawData = wsBudget.getRange(5, 1, wsBudget.getLastRow(), 7).getValues();

var arrDetails = [];

function onEdit(e) {

  //variables needed
  var editedCell = e.range;
  var sheetName = editedCell.getSheet().getName();

  var r = editedCell.getRow();
  var c = editedCell.getColumn();
  var valFilter = editedCell.getValue();

  //Set order qty
  if (sheetName === reqSheetName && c === colItem && r > 11) {

    getQtyValidationData(r);
  }
}

function getQtyValidationData(r) {

  var minQty = 1;
  var maxQty = wsRequisition.getRange(r, colBalance).getValue();
  var cell = wsRequisition.getRange(r, colQty).getA1Notation();

  applyQtyValidation(minQty, maxQty, cell);
}

function applyQtyValidation(minQty, maxQty, cell) {

  var rule = SpreadsheetApp
    .newDataValidation()
    .requireNumberBetween(minQty, maxQty)
    .setAllowInvalid(false)
    .setHelpText("Select a number between " + minQty + " and " + maxQty)
    .build();

  wsRequisition.getRange(cell).setDataValidation(rule);
}

A: This is working:
function onEdit(e) {
  e.source.toast('Entry');
  const sh = e.range.getSheet();
  if (sh.getName() == "Sheet1" && e.range.columnStart == 4 && e.range.rowStart > 11) {
    e.source.toast('Gate1');
    sh.getRange(e.range.rowStart, 5).clearDataValidations();
    var maxQty = sh.getRange(e.range.rowStart, 7).getValue();
    var rule = SpreadsheetApp.newDataValidation().requireNumberBetween(1, maxQty).setHelpText(`Select a number between 1 and ${maxQty}`).setAllowInvalid(true).build();
    sh.getRange(e.range.rowStart, 5).setDataValidation(rule);
  }
}

I would have preferred to do it like this:
function onEdit(e) {
  e.source.toast('Entry');
  const sh = e.range.getSheet();
  if (sh.getName() == "Sheet1" && e.range.columnStart == 4 && e.range.rowStart > 11) {
    e.source.toast('Gate1');
    sh.getRange(e.range.rowStart, 5).clearDataValidations();
    var maxQty = sh.getRange(e.range.rowStart, 7).getValue();
    let list = [...Array.from(new Array(maxQty).keys(),x => String(Number(x+1)))];
    Logger.log(JSON.stringify(list));
    var rule = SpreadsheetApp.newDataValidation().requireValueInList(list).setHelpText(`Select a number between 1 and ${maxQty}`).setAllowInvalid(false).build();
    sh.getRange(e.range.rowStart, 5).setDataValidation(rule);
  }
}

Demo:


text:
Q: Do you remember this book about living in a tube-like meteor? I am searching for a book that I loved when I was a young teenager. In the book as I remember it, people live in a giant, tubelike meteor. There are intense, fascinating descriptions of how the ceiling is also the ground (because it curves up), so the people can look up and see rivers following and animals walking around above them. I also remember that there are alien fruits, which the people name after how they taste, not how they look - so if a fruit tastes like a cucumber but looks like a watermelon, they call it "cucumber." Pretty sure there are also benevolent aliens in the book, and that it's a series that was originally written by one author, then taken over by another. Thanks in advance for your help!

A: Might it be the Rama series by Arthur C. Clarke, and Gentry Lee?

The "Rama" of the title is an alien starship, initially mistaken for an asteroid categorised as "31/439". It is detected by astronomers in the year 2131 while it is still outside the orbit of Jupiter. Its speed (100,000 km/h – 62,137 m/h) and the angle of its trajectory clearly indicate it is not on a long orbit around the sun, but is an interstellar object. The astronomers' interest is further piqued when they realise the asteroid has an extremely rapid rotation period of four minutes and is exceptionally large. It is named Rama after the Hindu god, and an uncrewed space probe dubbed Sita is launched from the Mars moon Phobos to intercept and photograph it. The resulting images reveal that Rama is a perfect cylinder, 20 kilometres (12 mi) in diameter and 50 kilometres (31 mi) long, and almost completely featureless, making this humankind's first encounter with an alien spacecraft.
The solar survey vessel Endeavour is sent to study Rama, as it is the only ship close enough to do so in the brief period Rama will spend in the Solar System. Endeavour manages to rendezvous with Rama one month after it first comes to Earth's attention, when the alien ship is already inside Venus's orbit. The crew, led by Commander Bill Norton, enters Rama through a safety system consisting of triple airlocks, and explores the 16-km wide by 50-km long cylindrical world of its interior, but the nature and purpose of the starship and its creators remain enigmatic throughout the book. Rama's inner surfaces hold "cities" of geometric structures that resemble buildings and are separated by streets with shallow trenches. A band of water, dubbed the Cylindrical Sea, stretches around Rama's central circumference. Massive spires, which are theorised to be part of Rama's propulsion system, stand at its "southern" end. They also find that Rama's atmosphere is breathable.

While Arthur C. Clarke was the sole author for the first book, Gentry Lee co-wrote the next three books, and was the sole author for the fifth and sixth books.

A: Eon (1985) by Greg Bear.
An asteroid, not a meteor.
From Wikipedia:

Juno has been hollowed out along its long axis, subdivided into seven cylindrical chambers, and rotates to provide artificial gravity. The chambers are terraformed, with the second and third containing cities that have been maintained by automatic systems for centuries.

A: Sounds like Heart of the Comet by David Brin and Gregory Benford.


text:
Q: Optimizing a CTE hierarchy Update below
I have a table of accounts with a typical acct/parent account architecture to represent a hierarchy of accounts (SQL Server 2012). I created a VIEW using a CTE to hash out the hierarchy, and on the whole it works beautifully, and as intended. I can query the hierarchy at any level, and see the branches easily.
There is one business logic field that needs to be returned as a function of the hierarchy. A field in each account record describes the size of the business (we'll call it CustomerCount). The logic I need to report on needs to roll up the CustomerCount from the whole branch. In other words, given an account, I need to sum up the customercount values for that account along with every child in every branch below the account along the hierarchy.
I successfully calculated the field using a hierarchy field built within the CTE, which looks like acct4.acct3.acct2.acct1. The problem I'm running into is simply making it run fast. Without this one calculated field, the query runs in ~3 seconds. When I add in the calculated field, it turns into a 4 minute query.
Here is the best version I've been able to come up with that returns the correct results. I'm looking for ideas on how I can restructure this AS A VIEW without such huge sacrifices to performance.
I understand the reason this one goes slow (requires calculating a predicate in the where clause), but I can't think of another way to structure it and still get same results.
Here's some sample code to build a table and do the CTE pretty much exactly as it works in my environment.
Use Tempdb
go
CREATE TABLE dbo.Account
(
   Acctid varchar(1) NOT NULL
    , Name varchar(30) NULL
    , ParentId varchar(1) NULL
    , CustomerCount int NULL
);

INSERT Account
SELECT 'A','Best Bet',NULL,21  UNION ALL
SELECT 'B','eStore','A',30 UNION ALL
SELECT 'C','Big Bens','B',75 UNION ALL
SELECT 'D','Mr. Jimbo','B',50 UNION ALL
SELECT 'E','Dr. John','C',100 UNION ALL
SELECT 'F','Brick','A',222 UNION ALL
SELECT 'G','Mortar','C',153 ;

With AccountHierarchy AS

(                                                                           --Root values have no parent
    SELECT
        Root.AcctId                                         AccountId
        , Root.Name                                         AccountName
        , Root.ParentId                                     ParentId
        , 1                                                 HierarchyLevel
        , cast(Root.Acctid as varchar(4000))                IdHierarchy     --highest parent reads right to left as in id3.Acctid2.Acctid1
        , cast(replace(Root.Name,'.','') as varchar(4000))  NameHierarchy   --highest parent reads right to left as in name3.name2.name1 (replace '.' so name parse is easy in last step)
        , cast(Root.Acctid as varchar(4000))                HierarchySort   --reverse of above, read left to right name1.name2.name3 for sorting on reporting only
        , cast(Root.Name as varchar(4000))                  HierarchyLabel  --use for labels on reporting only, indents names under sorted hierarchy
        , Root.CustomerCount                                CustomerCount

    FROM
        tempdb.dbo.account Root

    WHERE
        Root.ParentID is null

    UNION ALL

    SELECT
        Recurse.Acctid                                      AccountId
        , Recurse.Name                                      AccountName
        , Recurse.ParentId                                  ParentId
        , Root.HierarchyLevel + 1                           HierarchyLevel  --next level in hierarchy
        , cast(cast(recurse.Acctid as varchar(40)) + '.' + Root.IdHierarchy as varchar(4000))   IdHierarchy --cast because in real system this is a uniqueidentifier type needs converting
        , cast(replace(recurse.Name,'.','') + '.' + Root.NameHierarchy as varchar(4000)) NameHierarchy  --replace '.' for parsing in last step, cast to make room for lots of sub levels down the hierarchy
        , cast(Root.AccountName + '.' + Recurse.Name as varchar(4000)) HierarchySort
        , cast(space(root.HierarchyLevel * 4) + Recurse.Name as varchar(4000)) HierarchyLabel
        , Recurse.CustomerCount                             CustomerCount

    FROM
        tempdb.dbo.account Recurse INNER JOIN
        AccountHierarchy Root on Root.AccountId = Recurse.ParentId
)

SELECT
    hier.AccountId
    , Hier.AccountName
    , hier.ParentId
    , hier.HierarchyLevel
    , hier.IdHierarchy
    , hier.NameHierarchy
    , hier.HierarchyLabel
    , parsename(hier.IdHierarchy,1) Acct1Id
    , parsename(hier.NameHierarchy,1) Acct1Name     --This is why we stripped out '.' during recursion
    , parsename(hier.IdHierarchy,2) Acct2Id
    , parsename(hier.NameHierarchy,2) Acct2Name
    , parsename(hier.IdHierarchy,3) Acct3Id
    , parsename(hier.NameHierarchy,3) Acct3Name
    , parsename(hier.IdHierarchy,4) Acct4Id
    , parsename(hier.NameHierarchy,4) Acct4Name
    , hier.CustomerCount

    /* fantastic up to this point. Next block of code is what causes problem.
        Logic of code is "sum of CustomerCount for this location and all branches below in this branch of hierarchy"
        In live environment, goes from taking 3 seconds to 4 minutes by adding this one calc */

    , (
        SELECT
            sum(children.CustomerCount)
        FROM
            AccountHierarchy Children
        WHERE
            hier.IdHierarchy = right(children.IdHierarchy, (1 /*length of id field*/ * hier.HierarchyLevel) + hier.HierarchyLevel - 1 /*for periods inbetween ids*/)
            --"where this location's idhierarchy is within child idhierarchy"
            --previously tried a charindex(hier.IdHierarchy,children.IdHierarchy)>0, but that performed even worse
        ) TotalCustomerCount
FROM
    AccountHierarchy hier

ORDER BY
    hier.HierarchySort

drop table tempdb.dbo.Account

11/20/2013 UPDATE
Some of the suggested solutions got my juices flowing, and I tried a new approach that comes close, but introduces a new/different obstacle. Honestly, I don't know if this warrants a separate post or not, but it's related to the solution of this problem.
What I decided was that what was making the sum(customercount) difficult is the identification of children in the context of a hierarchy that starts at the top and builds down. So I started by creating a hierarchy that builds from the bottom up, using the root defined by "accounts that are not parent to any other account" and doing the recursive join backwards (root.parentacctid = recurse.acctid)
This way I could just add the child customer count to the parent as the recursion happens. Because of how I need reporting, and levels, I am doing this bottom up cte in addition to the top down, then just joining them via account id. This approach turns out to be much faster than the original outer query customercount, but I ran into a few obstacles.
First, I was inadvertently capturing duplicative customer count for accounts that are parent to multiple children. I was double or triple counting customer count for some acctid's, by the number of children there were. My solution was to create yet another cte which counts how many nodes an acct has, and divide the acct.customercount during recursion, so when I add up the whole branch the acct is not being double counted.
So at this point, the results of this new version are not correct, but I know why. The bottomup cte is creating duplicates. When the recursion passes, it looks for anything in the root (bottom level children) that is child to an account in the account table. On the third recursion, it picks up the same accounts it did in the second and puts them in again.
Ideas on how to do a bottom up cte, or does this get any other ideas flowing?
Use Tempdb
go

CREATE TABLE dbo.Account
(
    Acctid varchar(1) NOT NULL
    , Name varchar(30) NULL
    , ParentId varchar(1) NULL
    , CustomerCount int NULL
);

INSERT Account
SELECT 'A','Best Bet',NULL,1  UNION ALL
SELECT 'B','eStore','A',2 UNION ALL
SELECT 'C','Big Bens','B',3 UNION ALL
SELECT 'D','Mr. Jimbo','B',4 UNION ALL
SELECT 'E','Dr. John','C',5 UNION ALL
SELECT 'F','Brick','A',6 UNION ALL
SELECT 'G','Mortar','C',7 ;

With AccountHierarchy AS

(                                                                           --Root values have no parent
    SELECT
        Root.AcctId                                         AccountId
        , Root.Name                                         AccountName
        , Root.ParentId                                     ParentId
        , 1                                                 HierarchyLevel
        , cast(Root.Acctid as varchar(4000))                IdHierarchy     --highest parent reads right to left as in id3.Acctid2.Acctid1
        , cast(replace(Root.Name,'.','') as varchar(4000))  NameHierarchy   --highest parent reads right to left as in name3.name2.name1 (replace '.' so name parse is easy in last step)
        , cast(Root.Acctid as varchar(4000))                HierarchySort   --reverse of above, read left to right name1.name2.name3 for sorting on reporting only
        , cast(Root.Acctid as varchar(4000))                HierarchyMatch
        , cast(Root.Name as varchar(4000))                  HierarchyLabel  --use for labels on reporting only, indents names under sorted hierarchy
        , Root.CustomerCount                                CustomerCount

    FROM
        tempdb.dbo.account Root

    WHERE
        Root.ParentID is null

    UNION ALL

    SELECT
        Recurse.Acctid                                      AccountId
        , Recurse.Name                                      AccountName
        , Recurse.ParentId                                  ParentId
        , Root.HierarchyLevel + 1                           HierarchyLevel  --next level in hierarchy
        , cast(cast(recurse.Acctid as varchar(40)) + '.' + Root.IdHierarchy as varchar(4000))   IdHierarchy --cast because in real system this is a uniqueidentifier type needs converting
        , cast(replace(recurse.Name,'.','') + '.' + Root.NameHierarchy as varchar(4000)) NameHierarchy  --replace '.' for parsing in last step, cast to make room for lots of sub levels down the hierarchy
        , cast(Root.AccountName + '.' + Recurse.Name as varchar(4000)) HierarchySort
        , CAST(CAST(Root.HierarchyMatch as varchar(40)) + '.'
            + cast(recurse.Acctid as varchar(40))   as varchar(4000))   HierarchyMatch
        , cast(space(root.HierarchyLevel * 4) + Recurse.Name as varchar(4000)) HierarchyLabel
        , Recurse.CustomerCount                             CustomerCount

    FROM
        tempdb.dbo.account Recurse INNER JOIN
        AccountHierarchy Root on Root.AccountId = Recurse.ParentId
)

, Nodes as
(   --counts how many branches are below for any account that is parent to another
    select
        node.ParentId Acctid
        , cast(count(1) as float) Nodes
    from AccountHierarchy  node
    group by ParentId
)

, BottomUp as
(   --creates the hierarchy starting at accounts that are not parent to any other
    select
        Root.Acctid
        , root.ParentId
        , cast(isnull(root.customercount,0) as float) CustomerCount
    from
        tempdb.dbo.Account Root
    where
        not exists ( select 1 from tempdb.dbo.Account OtherAccts where root.Acctid = OtherAccts.ParentId)

    union all

    select
        Recurse.Acctid
        , Recurse.ParentId
        , root.CustomerCount + cast ((isnull(recurse.customercount,0) / nodes.nodes) as float) CustomerCount
        -- divide the recurse customercount by number of nodes to prevent duplicate customer count on accts that are parent to multiple children, see customercount cte next
    from
        tempdb.dbo.Account Recurse inner join
        BottomUp Root on root.ParentId = recurse.acctid inner join
        Nodes on nodes.Acctid = recurse.Acctid
)

, CustomerCount as
(
    select
        sum(CustomerCount) TotalCustomerCount
        , hier.acctid
    from
        BottomUp hier
    group by
        hier.Acctid
)

SELECT
    hier.AccountId
    , Hier.AccountName
    , hier.ParentId
    , hier.HierarchyLevel
    , hier.IdHierarchy
    , hier.NameHierarchy
    , hier.HierarchyLabel
    , hier.hierarchymatch
    , parsename(hier.IdHierarchy,1) Acct1Id
    , parsename(hier.NameHierarchy,1) Acct1Name     --This is why we stripped out '.' during recursion
    , parsename(hier.IdHierarchy,2) Acct2Id
    , parsename(hier.NameHierarchy,2) Acct2Name
    , parsename(hier.IdHierarchy,3) Acct3Id
    , parsename(hier.NameHierarchy,3) Acct3Name
    , parsename(hier.IdHierarchy,4) Acct4Id
    , parsename(hier.NameHierarchy,4) Acct4Name
    , hier.CustomerCount

    , customercount.TotalCustomerCount

FROM
    AccountHierarchy hier inner join
    CustomerCount on customercount.acctid = hier.accountid

ORDER BY
    hier.HierarchySort

drop table tempdb.dbo.Account

A: Edit: this is second attempt
Based on @Hannah Vernon's answer, here is a way to bypass the use of CTE inside an inline subquery, which is like self-joining the CTE and I presume is the reason for the poor efficiency. It uses analytic functions available only in the 2012 version of SQL-Server. Tested at SQL-Fiddle
This part can be skipped from reading, it's a copy-paste from Hannah's answer:
;With AccountHierarchy AS
(
    SELECT
        Root.AcctId                                         AccountId
        , Root.Name                                         AccountName
        , Root.ParentId                                     ParentId
        , 1                                                 HierarchyLevel
        , cast(Root.Acctid as varchar(4000))                IdHierarchyMatch
        , cast(Root.Acctid as varchar(4000))                IdHierarchy
        , cast(replace(Root.Name,'.','') as varchar(4000))  NameHierarchy
        , cast(Root.Acctid as varchar(4000))                HierarchySort
        , cast(Root.Name as varchar(4000))                  HierarchyLabel          ,
        Root.CustomerCount                                  CustomerCount

    FROM
        account Root

    WHERE
        Root.ParentID is null

    UNION ALL

    SELECT
        Recurse.Acctid                                      AccountId
        , Recurse.Name                                      AccountName
        , Recurse.ParentId                                  ParentId
        , Root.HierarchyLevel + 1                           HierarchyLevel
        , CAST(CAST(Root.IdHierarchyMatch as varchar(40)) + '.'
            + cast(recurse.Acctid as varchar(40))   as varchar(4000))   IdHierarchyMatch
        , cast(cast(recurse.Acctid as varchar(40)) + '.'
            + Root.IdHierarchy  as varchar(4000))           IdHierarchy
        , cast(replace(recurse.Name,'.','') + '.'
            + Root.NameHierarchy as varchar(4000))          NameHierarchy
        , cast(Root.AccountName + '.'
            + Recurse.Name as varchar(4000))                HierarchySort
        , cast(space(root.HierarchyLevel * 4)
            + Recurse.Name as varchar(4000))                HierarchyLabel
        , Recurse.CustomerCount                             CustomerCount
    FROM
        account Recurse INNER JOIN
        AccountHierarchy Root on Root.AccountId = Recurse.ParentId
)

Here we order the rows of the CTE using the IdHierarchyMatch and we calculate row numbers and a running total (from the next row up to the end.)
, cte1 AS
(
SELECT
    h.AccountId
    , h.AccountName
    , h.ParentId
    , h.HierarchyLevel
    , h.IdHierarchy
    , h.NameHierarchy
    , h.HierarchyLabel
    , parsename(h.IdHierarchy,1) Acct1Id
    , parsename(h.NameHierarchy,1) Acct1Name
    , parsename(h.IdHierarchy,2) Acct2Id
    , parsename(h.NameHierarchy,2) Acct2Name
    , parsename(h.IdHierarchy,3) Acct3Id
    , parsename(h.NameHierarchy,3) Acct3Name
    , parsename(h.IdHierarchy,4) Acct4Id
    , parsename(h.NameHierarchy,4) Acct4Name
    , h.CustomerCount
    , h.HierarchySort
    , h.IdHierarchyMatch
        , Rn = ROW_NUMBER() OVER
                  (ORDER BY h.IdHierarchyMatch)
        , RunningCustomerCount = COALESCE(
            SUM(h.CustomerCount)
            OVER
              (ORDER BY h.IdHierarchyMatch
               ROWS BETWEEN 1 FOLLOWING
                        AND UNBOUNDED FOLLOWING)
          , 0)
FROM
    AccountHierarchy AS h
)

Then we have one more intermediate CTE where we use the previous running totals and row numbers - basically to find where the end points for the branches of the tree structure:
, cte2 AS
(
SELECT
    cte1.*
    , rn3  = LAST_VALUE(Rn) OVER
               (PARTITION BY Acct1Id, Acct2Id, Acct3Id
                ORDER BY Acct4Id
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    , rn2  = LAST_VALUE(Rn) OVER
               (PARTITION BY Acct1Id, Acct2Id
                ORDER BY Acct3Id, Acct4Id
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    , rn1  = LAST_VALUE(Rn) OVER
               (PARTITION BY Acct1Id
                ORDER BY Acct2Id, Acct3Id, Acct4Id
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    , rcc3 = LAST_VALUE(RunningCustomerCount) OVER
               (PARTITION BY Acct1Id, Acct2Id, Acct3Id
                ORDER BY Acct4Id
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    , rcc2 = LAST_VALUE(RunningCustomerCount) OVER
               (PARTITION BY Acct1Id, Acct2Id
                ORDER BY Acct3Id, Acct4Id
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    , rcc1 = LAST_VALUE(RunningCustomerCount) OVER
               (PARTITION BY Acct1Id
                ORDER BY Acct2Id, Acct3Id, Acct4Id
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
FROM
    cte1
)

and finally we build the last part:
SELECT
    hier.AccountId
    , hier.AccountName
    ---                        -- columns skipped
    , hier.CustomerCount

    , TotalCustomerCount = hier.CustomerCount
        + hier.RunningCustomerCount
        - ca.LastRunningCustomerCount

    , hier.HierarchySort
    , hier.IdHierarchyMatch
FROM
    cte2 hier
  OUTER APPLY
    ( SELECT  LastRunningCustomerCount, Rn
      FROM
      ( SELECT LastRunningCustomerCount
              = RunningCustomerCount, Rn
        FROM (SELECT NULL a) x  WHERE 4 <= HierarchyLevel
      UNION ALL
        SELECT rcc3, Rn3
        FROM (SELECT NULL a) x  WHERE 3 <= HierarchyLevel
      UNION ALL
        SELECT rcc2, Rn2
        FROM (SELECT NULL a) x  WHERE 2 <= HierarchyLevel
      UNION ALL
        SELECT rcc1, Rn1
        FROM (SELECT NULL a) x  WHERE 1 <= HierarchyLevel
      ) x
      ORDER BY Rn
      OFFSET 0 ROWS
      FETCH NEXT 1 ROWS ONLY
      ) ca
ORDER BY
    hier.HierarchySort ;

And a simplification, using the same cte1 as the code above. Test at SQL-Fiddle-2. Please note that both solutions work under the assumption that you have a maximum of four levels in your tree:
SELECT
    hier.AccountId
    ---                      -- skipping rows
    , hier.CustomerCount

    , TotalCustomerCount = CustomerCount
        + RunningCustomerCount
        - CASE HierarchyLevel
            WHEN 4 THEN RunningCustomerCount
            WHEN 3 THEN LAST_VALUE(RunningCustomerCount) OVER
                   (PARTITION BY Acct1Id, Acct2Id, Acct3Id
                    ORDER BY Acct4Id
                    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
            WHEN 2 THEN LAST_VALUE(RunningCustomerCount) OVER
                   (PARTITION BY Acct1Id, Acct2Id
                    ORDER BY Acct3Id, Acct4Id
                    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
            WHEN 1 THEN LAST_VALUE(RunningCustomerCount) OVER
                   (PARTITION BY Acct1Id
                    ORDER BY Acct2Id, Acct3Id, Acct4Id
                    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
          END

    , hier.HierarchySort
    , hier.IdHierarchyMatch
FROM cte1 AS hier
ORDER BY
    hier.HierarchySort ;

A third approach, with only one CTE, for the recursive part and then only window aggregate functions (SUM() OVER (...)), so it should work in any version from 2005 upwards. Test at SQL-Fiddle-3 This solution assumes, like the previous ones, that there are 4 levels maximum in the hierarchy tree:
;WITH AccountHierarchy AS
(
    SELECT
          AccountId      = Root.AcctId
        , AccountName    = Root.Name
        , ParentId       = Root.ParentId
        , HierarchyLevel = 1
        , HierarchySort  = CAST(Root.Acctid AS VARCHAR(4000))
        , HierarchyLabel = CAST(Root.Name AS VARCHAR(4000))
        , Acct1Id        = CAST(Root.Acctid AS VARCHAR(4000))
        , Acct2Id        = CAST(NULL AS VARCHAR(4000))
        , Acct3Id        = CAST(NULL AS VARCHAR(4000))
        , Acct4Id        = CAST(NULL AS VARCHAR(4000))
        , Acct1Name      = CAST(Root.Name AS VARCHAR(4000))
        , Acct2Name      = CAST(NULL AS VARCHAR(4000))
        , Acct3Name      = CAST(NULL AS VARCHAR(4000))
        , Acct4Name      = CAST(NULL AS VARCHAR(4000))
        , CustomerCount  = Root.CustomerCount

    FROM
        account AS Root

    WHERE
        Root.ParentID IS NULL

    UNION ALL

    SELECT
          Recurse.Acctid
        , Recurse.Name
        , Recurse.ParentId
        , Root.HierarchyLevel + 1
        , CAST(Root.AccountName + '.'
            + Recurse.Name AS VARCHAR(4000))
        , CAST(SPACE(Root.HierarchyLevel * 4)
            + Recurse.Name AS VARCHAR(4000))
        , Root.Acct1Id
        , CASE WHEN Root.HierarchyLevel = 1
              THEN cast(Recurse.Acctid AS VARCHAR(4000))
              ELSE Root.Acct2Id
          END
        , CASE WHEN Root.HierarchyLevel = 2
              THEN CAST(Recurse.Acctid AS VARCHAR(4000))
              ELSE Root.Acct3Id
          END
        , CASE WHEN Root.HierarchyLevel = 3
              THEN CAST(Recurse.Acctid AS VARCHAR(4000))
              ELSE Root.Acct4Id
          END

        , cast(Root.AccountName as varchar(4000))
        , CASE WHEN Root.HierarchyLevel = 1
              THEN CAST(Recurse.Name AS VARCHAR(4000))
              ELSE Root.Acct2Name
          END
        , CASE WHEN Root.HierarchyLevel = 2
              THEN CAST(Recurse.Name AS VARCHAR(4000))
              ELSE Root.Acct3Name
          END
        , CASE WHEN Root.HierarchyLevel = 3
              THEN CAST(Recurse.Name AS VARCHAR(4000))
              ELSE Root.Acct4Name
          END
        , Recurse.CustomerCount
    FROM
        account AS Recurse INNER JOIN
        AccountHierarchy AS Root ON Root.AccountId = Recurse.ParentId
)

SELECT
      h.AccountId
    , h.AccountName
    , h.ParentId
    , h.HierarchyLevel
    , IdHierarchy =
          CAST(COALESCE(h.Acct4Id+'.','')
               + COALESCE(h.Acct3Id+'.','')
               + COALESCE(h.Acct2Id+'.','')
               + h.Acct1Id AS VARCHAR(4000))
    , NameHierarchy =
          CAST(COALESCE(h.Acct4Name+'.','')
               + COALESCE(h.Acct3Name+'.','')
               + COALESCE(h.Acct2Name+'.','')
               + h.Acct1Name AS VARCHAR(4000))
    , h.HierarchyLabel
    , h.Acct1Id
    , h.Acct1Name
    , h.Acct2Id
    , h.Acct2Name
    , h.Acct3Id
    , h.Acct3Name
    , h.Acct4Id
    , h.Acct4Name
    , h.CustomerCount
    , TotalCustomerCount =
          CASE h.HierarchyLevel
            WHEN 4 THEN h.CustomerCount
            WHEN 3 THEN SUM(h.CustomerCount) OVER
                   (PARTITION BY h.Acct1Id, h.Acct2Id, h.Acct3Id)
            WHEN 2 THEN SUM(h.CustomerCount) OVER
                   (PARTITION BY Acct1Id, h.Acct2Id)
            WHEN 1 THEN SUM(h.CustomerCount) OVER
                   (PARTITION BY h.Acct1Id)
          END
    , h.HierarchySort
    , IdHierarchyMatch =
          CAST(h.Acct1Id
               + COALESCE('.'+h.Acct2Id,'')
               + COALESCE('.'+h.Acct3Id,'')
               + COALESCE('.'+h.Acct4Id,'') AS VARCHAR(4000))
FROM
    AccountHierarchy AS h
ORDER BY
    h.HierarchySort ;

A 4th approach, that calculates as an intermediate CTE, the closure table of the hierarchy. Test at SQL-Fiddle-4. The benefit is that for the sums calculations, there is no resctriction on the number of levels.
;WITH AccountHierarchy AS
(
    -- skipping several line, identical to the 3rd approach above
)

, ClosureTable AS
(
    SELECT
          AccountId      = Root.AcctId
        , AncestorId     = Root.AcctId
        , CustomerCount  = Root.CustomerCount
    FROM
        account AS Root

    UNION ALL

    SELECT
          Recurse.Acctid
        , Root.AncestorId
        , Recurse.CustomerCount
    FROM
        account AS Recurse INNER JOIN
        ClosureTable AS Root ON Root.AccountId = Recurse.ParentId
)

, ClosureGroup AS
(
    SELECT
          AccountId           = AncestorId
        , TotalCustomerCount  = SUM(CustomerCount)
    FROM
        ClosureTable AS a
    GROUP BY
        AncestorId
)

SELECT
      h.AccountId
    , h.AccountName
    , h.ParentId
    , h.HierarchyLevel
    , h.HierarchyLabel
    , h.CustomerCount
    , cg.TotalCustomerCount

    , h.HierarchySort
FROM
    AccountHierarchy AS h
  JOIN
    ClosureGroup AS cg
      ON cg.AccountId = h.AccountId
ORDER BY
    h.HierarchySort ;

A: I believe this should make it faster:
;With AccountHierarchy AS
(
    SELECT
        Root.AcctId                                         AccountId
        , Root.Name                                         AccountName
        , Root.ParentId                                     ParentId
        , 1                                                 HierarchyLevel
        , cast(Root.Acctid as varchar(4000))                IdHierarchyMatch
        , cast(Root.Acctid as varchar(4000))                IdHierarchy
        , cast(replace(Root.Name,'.','') as varchar(4000))  NameHierarchy
        , cast(Root.Acctid as varchar(4000))                HierarchySort
        , cast(Root.Name as varchar(4000))                  HierarchyLabel          ,
        Root.CustomerCount                                  CustomerCount

    FROM
        tempdb.dbo.account Root

    WHERE
        Root.ParentID is null

    UNION ALL

    SELECT
        Recurse.Acctid                                      AccountId
        , Recurse.Name                                      AccountName
        , Recurse.ParentId                                  ParentId
        , Root.HierarchyLevel + 1                           HierarchyLevel
        , CAST(CAST(Root.IdHierarchyMatch as varchar(40)) + '.'
            + cast(recurse.Acctid as varchar(40))   as varchar(4000))   IdHierarchyMatch
        , cast(cast(recurse.Acctid as varchar(40)) + '.'
            + Root.IdHierarchy  as varchar(4000))           IdHierarchy
        , cast(replace(recurse.Name,'.','') + '.'
            + Root.NameHierarchy as varchar(4000))          NameHierarchy
        , cast(Root.AccountName + '.'
            + Recurse.Name as varchar(4000))                HierarchySort
        , cast(space(root.HierarchyLevel * 4)
            + Recurse.Name as varchar(4000))                HierarchyLabel
        , Recurse.CustomerCount                             CustomerCount
    FROM
        tempdb.dbo.account Recurse INNER JOIN
        AccountHierarchy Root on Root.AccountId = Recurse.ParentId
)

SELECT
    hier.AccountId
    , Hier.AccountName
    , hier.ParentId
    , hier.HierarchyLevel
    , hier.IdHierarchy
    , hier.NameHierarchy
    , hier.HierarchyLabel
    , parsename(hier.IdHierarchy,1) Acct1Id
    , parsename(hier.NameHierarchy,1) Acct1Name
    , parsename(hier.IdHierarchy,2) Acct2Id
    , parsename(hier.NameHierarchy,2) Acct2Name
    , parsename(hier.IdHierarchy,3) Acct3Id
    , parsename(hier.NameHierarchy,3) Acct3Name
    , parsename(hier.IdHierarchy,4) Acct4Id
    , parsename(hier.NameHierarchy,4) Acct4Name
    , hier.CustomerCount
    , (
        SELECT
            sum(children.CustomerCount)
        FROM
            AccountHierarchy Children
        WHERE
            Children.IdHierarchyMatch LIKE hier.IdHierarchyMatch + '%'
        ) TotalCustomerCount
        , HierarchySort
        , IdHierarchyMatch
FROM
    AccountHierarchy hier
ORDER BY
    hier.HierarchySort

I added a column in the CTE named IdHierarchyMatch which is the forward version of IdHierarchy to enable the TotalCustomerCount subquery WHERE clause to be sargable.
Comparing estimated subtree costs for the execution plans, this way should be approximately 5 times faster.

A: I gave it a shot as well. It ain't very pretty, but it seems to perform better.
USE Tempdb
go

SET STATISTICS IO ON;
SET STATISTICS TIME OFF;
SET NOCOUNT ON;

--------
-- assuming the original table looks something like this
-- and you cannot control it's indexes
-- (only widened the data types a bit for the extra sample rows)
--------
CREATE TABLE dbo.Account
    (
      Acctid VARCHAR(10) NOT NULL ,
      Name VARCHAR(100) NULL ,
      ParentId VARCHAR(10) NULL ,
      CustomerCount INT NULL
    );

--------
-- inserting the same records as in your sample
--------
INSERT  Account
        SELECT  'A' ,
                'Best Bet' ,
                NULL ,
                21
        UNION ALL
        SELECT  'B' ,
                'eStore' ,
                'A' ,
                30
        UNION ALL
        SELECT  'C' ,
                'Big Bens' ,
                'B' ,
                75
        UNION ALL
        SELECT  'D' ,
                'Mr. Jimbo' ,
                'B' ,
                50
        UNION ALL
        SELECT  'E' ,
                'Dr. John' ,
                'C' ,
                100
        UNION ALL
        SELECT  'F' ,
                'Brick' ,
                'A' ,
                222
        UNION ALL
        SELECT  'G' ,
                'Mortar' ,
                'C' ,
                153;

--------
-- now lets up the ante a bit and add some extra rows with random parents
-- to these 7 items, it is hard to measure differences with so few rows
--------
DECLARE @numberOfRows INT = 25000
DECLARE @from INT = 1
DECLARE @to INT = 7
DECLARE @T1 TABLE ( n INT );

WITH    cte ( n )
          AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY CURRENT_TIMESTAMP )
               FROM     sys.messages
             )
    INSERT  INTO @T1
            SELECT  n
            FROM    cte
            WHERE   n <= @numberOfRows;

INSERT  INTO dbo.Account
        ( acctId ,
          name ,
          parentId ,
          Customercount
        )
        SELECT  CHAR(64 + RandomNumber) + CAST(n AS VARCHAR(10)) AS Id ,
                CAST('item ' + CHAR(64 + RandomNumber) + CAST(n AS VARCHAR(10)) AS VARCHAR(100)) ,
                CHAR(64 + RandomNumber) AS parentId ,
                ABS(CHECKSUM(NEWID()) % 100) + 1 AS RandomCustCount
        FROM    ( SELECT    n ,
                            ABS(CHECKSUM(NEWID()) % @to) + @from AS RandomNumber
                  FROM      @T1
                ) A;

--------
-- Assuming you cannot control it's indexes, in my tests we're better off taking the IO hit of copying the data
-- to some structure that is better optimized for this query. Not quite what I initially expected,  but we seem
-- to be better off that way.
--------
CREATE TABLE tempdb.dbo.T1
    (
      AccountId VARCHAR(10) NOT NULL
                            PRIMARY KEY NONCLUSTERED ,
      AccountName VARCHAR(100) NOT NULL ,
      ParentId VARCHAR(10) NULL ,
      HierarchyLevel INT NULL ,
      HPath VARCHAR(1000) NULL ,
      IdHierarchy VARCHAR(1000) NULL ,
      NameHierarchy VARCHAR(1000) NULL ,
      HierarchyLabel VARCHAR(1000) NULL ,
      HierarchySort VARCHAR(1000) NULL ,
      CustomerCount INT NOT NULL
    );

CREATE CLUSTERED INDEX IX_Q1
ON tempdb.dbo.T1  ([ParentId]);

-- for summing customer counts over parents
CREATE NONCLUSTERED INDEX IX_Q2
ON tempdb.dbo.T1  (HPath) INCLUDE(CustomerCount);

INSERT  INTO tempdb.dbo.T1
        ( AccountId ,
          AccountName ,
          ParentId ,
          HierarchyLevel ,
          HPath ,
          IdHierarchy ,
          NameHierarchy ,
          HierarchyLabel ,
          HierarchySort ,
          CustomerCount
        )
        SELECT  Acctid AS AccountId ,
                Name AS AccountName ,
                ParentId AS ParentId ,
                NULL AS HierarchyLevel ,
                NULL AS HPath ,
                NULL AS IdHierarchy ,
                NULL AS NameHierarchy ,
                NULL AS HierarchyLabel ,
                NULL AS HierarchySort ,
                CustomerCount AS CustomerCount
        FROM    tempdb.dbo.account;

--------
-- I cannot seem to force an efficient way to do the sum while selecting over the recursive cte,
-- so I took it aside. I am sure there is a more elegant way but I can't seem to make it happen.
-- At least it performs better this way. But it remains a very expensive query.
--------
;
WITH    AccountHierarchy
          AS ( SELECT   Root.AccountId AS AcId ,
                        Root.ParentId ,
                        1 AS HLvl ,
                        CAST(Root.AccountId AS VARCHAR(1000)) AS [HPa] ,
                        CAST(Root.accountId AS VARCHAR(1000)) AS hid ,
                        CAST(REPLACE(Root.AccountName, '.', '') AS VARCHAR(1000)) AS hn ,
                        CAST(Root.accountid AS VARCHAR(1000)) AS hs ,
                        CAST(Root.accountname AS VARCHAR(1000)) AS hl
               FROM     tempdb.dbo.T1 Root
               WHERE    Root.ParentID IS NULL
               UNION ALL
               SELECT   Recurse.AccountId AS acid ,
                        Recurse.ParentId ParentId ,
                        Root.Hlvl + 1 AS hlvl ,
                        CAST(Root.HPa + '.' + Recurse.AccountId AS VARCHAR(1000)) AS hpa ,
                        CAST(recurse.AccountId + '.' + Root.hid AS VARCHAR(1000)) AS hid ,
                        CAST(REPLACE(recurse.AccountName, '.', '') + '.' + Root.hn AS VARCHAR(1000)) AS hn ,
                        CAST(Root.hs + '.' + Recurse.AccountName AS VARCHAR(1000)) AS hs ,
                        CAST(SPACE(root.hlvl * 4) + Recurse.AccountName AS VARCHAR(1000)) AS hl
               FROM     tempdb.dbo.T1 Recurse
                        INNER JOIN AccountHierarchy Root ON Root.AcId = Recurse.ParentId
             )
    UPDATE  tempdb.dbo.T1
    SET     HierarchyLevel = HLvl ,
            HPath = Hpa ,
            IdHierarchy = hid ,
            NameHierarchy = hn ,
            HierarchyLabel = hl ,
            HierarchySort = hs
    FROM    AccountHierarchy
    WHERE   AccountId = AcId;

SELECT  --HPath ,
        AccountId ,
        AccountName ,
        ParentId ,
        HierarchyLevel ,
        IdHierarchy ,
        NameHierarchy ,
        HierarchyLabel ,
        PARSENAME(IdHierarchy, 1) Acct1Id ,
        PARSENAME(NameHierarchy, 1) Acct1Name ,
        PARSENAME(IdHierarchy, 2) Acct2Id ,
        PARSENAME(NameHierarchy, 2) Acct2Name ,
        PARSENAME(IdHierarchy, 3) Acct3Id ,
        PARSENAME(NameHierarchy, 3) Acct3Name ,
        PARSENAME(IdHierarchy, 4) Acct4Id ,
        PARSENAME(NameHierarchy, 4) Acct4Name ,
        CustomerCount ,
        Cnt.TotalCustomerCount
FROM    tempdb.dbo.t1 Hier
        CROSS APPLY ( SELECT    SUM(CustomerCount) AS TotalCustomerCount
                      FROM      tempdb.dbo.t1
                      WHERE     HPath LIKE hier.HPath + '%'
                    ) Cnt
ORDER BY HierarchySort;

DROP TABLE tempdb.dbo.t1;
DROP TABLE tempdb.dbo.Account;


text:
Q: Tradeoff: Fetching less data vs having a simpler data model We have 2 vehicle types in our system Car and Bike. Both can be associated with a Report.
There are components in our system which operate on Report but when dealing with the report they need to check if the report is for a Bike or for a Car.
I'm trying to decide between these 2 options

*

*Create a report type for each i.e. a BikeReport and a CarReport. This allows me to do above check without fetching the associated vehicle but it makes the data model more complex.

*Create only 1 report type Report and fetch the associated vehicle when I need to know the vehicle type. This keeps the data model simple but requires more requests to the DB.

I suppose it will depend on whether I'm more comfortable with the additional DB requests or the more complicated data model but wanted to see what other people think.
Thanks

A: I think you have the wrong decision criteria in focus.
You are trying to make this decision based on a few additional queries which may be required to determine the vehicle type. This is first and foremost a performance argument. But performance should only become of interest when you have a real, measurable bottleneck, which you currently have not, otherwise you would not have asked here.
Here are the points you should really put into focus:

*

*How much code duplication would separating those two reports BikeReport and CarReport cause? Code duplication is a sign you should try a find a generic solution.

*Will not separating those two reports make you code become full of conditionals of the form if vehicle is Car ... else ...?  That's a point against a generic solution.

*Can you create two reports BikeReport and CarReport, but then refactor the duplicated code into a common place? For example, a common base class Report? So you get "the best of both worlds"?

*In case of a generic solution: can you replace the mentioned conditionals by polymorphism (using the strategy pattern, for example)?

*Is there a chance you will need to support more vehicle types with different report variants in the near future? If yes, do you need to let a second team make the extensions, which should be able to do this without touching your code? If that's not the case, your design can be kept significantly simpler than in the opposite case.
Consider also to start with a simple design first, and refactor as you go. None of your decisions is written in stone. Focus on avoiding duplicate code, and on avoiding complex conditionals.
And when you really notice performance issues in the future: those can be solved within the bounds of each design. Regardless of the solution you pick, some component will have to determine the vehicle type at some point in time. If you don't want to query the DB multiple times, cache the information somewhere once you got it (for example as a type flag in your generic Report, maybe implicitly as the type of a strategy object), and reuse that information later.

A: The question as stated is a bit vague.

trying to decide between these 2 options:

*

*Create a report type for each ...

*Create only 1 report type Report

Based on what you have disclosed so far, definitely go with option 2.
There are clearly commonalities among vehicles: num_people_carried, time departed, time returned, kilometers traveled.
There may be energy expenditure details to report on,
such as liters of petrol or KWh used,
which splits along some e-bike / plugin car axis.
Delegate that to per-class methods,
and consume generic aspects through inheritance.


text:
Q: Confused about when to escape metacharacters in pathnames I'm pretty confused about under which circumstances do I need to escape metacharacters in pathnames. Consider the following example:
I'm in the following working directory:
$ echo $PWD
/home/helpermethod/foo[b]ar/foo/bar

Now I want to strip off everything behind foo[b]ar. I'm using parameter substitution to perform this task:/home/helpermethod/foo[b]ar
$ path=$PWD
$ basename=foo[b]ar
$ stripped_path=${path%$basename/*}/$basename

This doesn't seem to work because the basename string needs to be properly escaped:
$ basename=foo\[b\]ar
$ stripped_path=${path%$basename/*}/$basename

Okay, now I have the stripped_path I was looking for
$ echo "$stripped_path"
/home/helpermethod/foo[b]ar

But if I now test if this is a valid directory
$ [[ -d $stripped_path ]]

the test command always returns false (i.e. a return value != 0). What's the problem here? Do I need to unescape the stripped_path?

A: stripped_path=${path%"$basename"/*}/$basename

Use double quotes to do literal string matching as opposed to pattern matching. One of the cases where you need to quote variables. Another case is in your:
echo $PWD

above which should have been:
echo "$PWD"

Or even better:
printf '%s\n' "$PWD"

Or
pwd


text:
Q: Split numbers from api with commas? import urllib.request,

urllib.parse, urllib.error
from bs4 import BeautifulSoup

url = "https://api.monzo.com/crowdfunding-investment/total"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

if 'invested_amount' in text:
    result = text.split(",")

invested = str(result[1])
investedn = invested.split(':')[1]

print(investedn)

Hi all. I'm trying to split investedn into thousands with commas. Anyone know how to do this?
Also, how can I remove the last four numbers from the string?
Thanks!

A: Simply use
"{:,}".format(number)

https://docs.python.org/3/library/string.html#format-specification-mini-language
e.g.
In [19]: "{:,}".format(17462233620)
Out[19]: '17,462,233,620'

A: Managed to fix!
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup

url = "https://api.monzo.com/crowdfunding-investment/total"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

if 'invested_amount' in text:
    result = text.split(",")

invested = str(result[1])
investedn = invested.split(':')[1]
plainnum = int(str(investedn)[:-4])
number = "{:,}".format(int(plainnum))

print(number)

I had messed up quite a bit, but figured it out.
Thanks!

A: The text you got back from that URL is not HTML. It is data encoded in JSON format, which is easy to parse:
import urllib.request
import json

url = "https://api.monzo.com/crowdfunding-investment/total"
json_text = urllib.request.urlopen(url).read()
json_text = json_text.decode('utf-8')
data = json.loads(json_text)
print(data)
print('Invested amount: {:,}'.format(data['invested_amount']))

Output:
{'invested_amount': 17529735495, 'share_price': 77145, 'shares_invested': 227231, 'max_shares': 2592520, 'max_amount': 199999955400, 'status': 'pending'}
Invested amount: 17,529,735,495

Notes

*

*json_text was an array of bytes, not a string. That is why I decode it using a guess of UTF-8.

*data is just a normal Python dictionary.

A: a = "17462233620"
b = ""
for i in range(len(a), 0 , -3):
  b = a[i-3:i]+","+b
b = "£" + a[0:i] + b[:-1]
print(b) # Output £17,462,233,620


text:
Q: Algorithms for Search tree vs building tree say I want to have an algorithm which gets a solution as quick as possible, which consists of starting from a state in a tree, and going through all possible states in a tree-like strucutre, why would it be necessary to first build a tree, and then traverse it, instead of building a tree, and if during building a solution node has been found, to stop building and immediately backtrack to the root, noting down the path to this leaf?
Basically, is there an BF algorithm to 'generate' a tree Breadth-First, rather than creating a tree first, and then search through it in a breadth-first manner?
Kind of like the animated results here:
Thank you for reading

A: There is no advantage in a search algorithm to build a tree and then search it, exactly due to the reasons you have mentioned. Furthermore, there is no search-related advantage that is gained by building a tree breadth-first or depth-first.
Usually, there are trees already present and we traverse them using the Breadth-First approach or the Depth-First approach. The reason why we choose one of these approaches is due to a property of the search-element or of the tree.
If you have seen cases where we construct a tree and then search it, it's for pedagogical purposes where you have to write a standalone program that constructs the tree and then traverses it. This is similar to creating a linked-list of numbers and performing a linear search, or constructing a Binary-Search-Tree and then searching for a value. Typically this approach tends to teach about creation and traversal of a data-structure packaged into one program.


text:
Q: Extension affects another web page I am having some problems creating Chrome extensions. The code affects all pages that are open in Chrome, how can I solve it?
My manifest.json:
{
    "manifest_version": 2,
    "name": "Merch Tools 41studio",
    "description": "report app",
    "version": "1.0",
    "background": {
        "scripts": ["assets/js/jquery.min.js", "assets/js/background.js"]
    },
    "browser_action": {
        "default_icon": "assets/image/icon.png",
        "default_popup": "popup.html"
    },
    "permissions": ["tabs"],
    "content_scripts": [{
        "matches": ["http://*/*", "https://*/*"],
        "js": ["assets/js/jquery.min.js", "assets/js/highcharts.js"]
    }]
}

A: You need to limit the list of domains your content scripts run on by changing the matches property in content_scripts. Having a "http://*/*","https://*/*" means the content script runs on all http and https websites. Rather you could specify a list of websites that you want the extension to run on.
{
  "manifest_version": 2,
  "name": "Merch Tools 41studio",
  "description": "report app",
  "version": "1.0",
  "background": {
    "scripts": ["assets/js/jquery.min.js", "assets/js/background.js"]
  },
  "browser_action": {
    "default_icon": "assets/image/icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs"],
  "content_scripts": [{
    "matches": ["http:/yoursite.com/*"], // Change this to the sites you want your extension to run on
    "js": ["assets/js/jquery.min.js", "assets/js/highcharts.js"]
  }]
}


text:
Q: android: Upgrade My Library from android to androidx but not found this class SlideCallback This is my code in old library
android.support.v17.leanback.transition.SlideCallback;
updated to
androidx.leanback.transition;
how can I convert this code?

import androidx.leanback.transition.*;

public class VGDetailsTitleTransitionHelper {

    final static  SlideCallback sSlideCallback = new SlideCallback() {
        @Override
        public boolean getSlide(View view, boolean appear, int[] edge, float[] distance) {
            edge[0] = TransitionHelper.SLIDE_TOP;
            Log.v("getSlide details", "" + view.getHeight());
            distance[0] = view.getHeight();
            return true;
        }
    };

}


text:
Q: Is it possible to maintain "boundness" of a method when passing it as an object outside its class I'm trying to write a library that will register an arbitrary list of service calls from multiple service endpoints to a container.  I intend to implement the service calls in classes written one per service.  Is there a way to maintain the boundedness of the methods from the service classes when registering them to the container (so they will still have access to the instance data of their owning object instance), or must I register the whole object then write some sort of pass through in the container class with __getattr__ or some such to access the methods within instance context?
container:
class ServiceCalls(object):
    def __init__(self):
        self._service_calls = {}
    def register_call(self, name, call):
        if name not in self._service_calls:
            self._service_calls[name] = call
    def __getattr__(self, name):
        if name in self._service_calls:
           return self._service_calls[name]

services:
class FooSvc(object):
    def __init__(self, endpoint):
        self.endpoint = endpoint
    def fooize(self, *args, **kwargs):
        #call fooize service call with args/kwargs utilizing self.endpoint
    def fooify(self, *args, **kwargs):
        #call fooify service call with args/kwargs utilizing self.endpoint

class BarSvc(object):
    def __init__(self, endpoint):
        self.endpoint = endpoint
    def barize(self, *args, **kwargs):
        #call barize service call with args/kwargs utilizing self.endpoint
    def barify(self, *args, **kwargs):
        #call barify service call with args/kwargs utilizing self.endpoint

implementation code:
foosvc = FooSvc('fooendpoint')
barsvc = BarSvc('barendpoint')
calls = ServiceCalls()
calls.register('fooize', foosvc.fooize)
calls.register('fooify', foosvc.fooify)
calls.register('barize', barsvc.barize)
calls.register('barify', barsvc.barify)
calls.fooize(args)

A: I think this answers your question:
In [2]: f = 1 .__add__

In [3]: f(3)
Out[3]: 4

You won't need the staticmethod function when adding these functions to classes, because they are effectively already "staticed".

A: I don't understand the use case for this -- it seems to me that the easy, simple, idiomatic way to accomplish this is to just pass in an object.
But:  program to the interface, not the implementation.  Only assume that the object has the method you need -- don't touch the internals or any other methods.

A: What you are trying to do will work fine, as you can see by running your own code. :)
The object foosvc.fooize is called a "bound method" in Python, and it contains both, a reference to foosvc and to the function FooSvc.fooize.  If you call the bound method, the reference to self will be passed implicitly as the first paramater.
On a side note, __getattr__() shouldn't silently return None for invalid attribute names.  Better use this:
def __getattr__(self, name):
    try:
        return self._service_calls[name]
    except KeyError:
        raise AttributeError


text:
Q: Firebase Method to check whether an email is already associated with an account Desired behavior:
I would like to have a method that verify the email address with firebase to throw some error if the email is used/invalid.
createUserWithEmailAndPassword(email, password) does not seem to do the job as I would only want to create the account if the user passes a phone verification on the second page, but I would like to throw some error before the user navigates to the second page.

A: if you have a backend that can use the Admin SDK, you can implement your own API to do this by following https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data
admin
  .auth()
  .getUserByEmail(email)
  .then((userRecord) => {
    // return error
  })
  .catch((error) => {
    // allow going to second page
  });


text:
Q: convert pdf (with special characters) to text Hi I'm trying to convert multiple pdfs to text, my code is working, however most of mine file are in spanish, with characters such as (ñ,í,ó,ú,é) and these (ñ,í,ó,ú,é) are getting corrupted. Also I need the text file to be in lower case for text analysis later:
library(XML)
  library(httr)
  library(dplyr)
  library(tidyr)
  library(stringr)
  library(tm)

  # Get a list of all of the document names of the downloaded PDFs
    pdf_files <- list.files(path = paste(getwd(), '/pdf', sep = ''),
                            pattern = 'pdf',
                            full.names = TRUE)

    # Check there are pdf files in directory
    if( length(pdf_files) > 0 ){

      # Loop through each PDF and create a txt version in the same folder

      for(i in pdf_files){

        system(
          paste(
            paste('"', getwd(), '/dependencies/xpdf/bin64/pdftotext.exe"', sep = ''),
            paste0('"', i, '"')),
          wait = FALSE)

      }
    }

  cat( '\nConversion to text complete.\n\n' )


text:
Q: Inequivalent quantizations of a classical system Suppose to have a Hamiltonian $H(q,p)$ defined on a phase space with (q,p) and suppose that exist a canonical transformation $$(Q,P)=X(q,p)$$ such that the  classical dynamics is equivalent using $H'(Q,P)$ and (Q,P).
Now, what happens if I quantize the system using (q,p) or (Q,P)? I would say that I get two Hilbert spaces E and E' that are not isomorphic in general because a canonical transformations could be non linear.
Is it true? If so, why we are used to quantize a system in a specific (q,p) phase space?
I observed this ambiguity in the quantization of the hydrogen atom: the system is quantized in the phase space $(x,y,z,p_{x},p_{y},p_{z})$ and only in the quantum world we shift to polar coordinates: what would happen if this change is made at a classical level and then we quantize the phase space (r,$\theta$,$\phi$,p$_{r}$,p$_{\theta}$,p$_{\phi}$)?

A: Within your question lies an assumption that is important to state explicitly: you have a semiclassical picture in mind where you have a physically meaningful classical Hamilton function $H(q,p)$ on phase space (or some other classical observable) and you would like to promote it to a physically meaningful quantum Hamiltonian $\hat{H} = H(x,-\mathrm{i} \nabla - A)$. The fact that both need to be physically meaningful places restrictions on your quantization procedure.
A quantization of observables (as opposed to states, which is also an option) is a systematic association of suitable functions on phase space with operators on a Hilbert space. In general, quantizations are not unique, for example you can choose your favorite operator ordering in a variation Weyl calculus or choose a gauge in magnetic Weyl calculus.
However, choosing a non-symmetric operator ordering leads to mathematically well-defined operators that are usually not physically meaningful. On the other hand, the gauge freedom in choosing a vector potential is different in that respect: if $A' = A + \nabla \chi$ are two equivalent gauges, then $f \bigl ( x , - \mathrm{i} \hbar \nabla - A' \bigr )$ and $f \bigl ( x , -\mathrm{i} \hbar \nabla - A , x \bigr )$ defined via magnetic Weyl calculus are unitarily equivalent operators related by $\mathrm{e}^{+ \mathrm{i} \chi}$.


text:
Q: TypeError: tuple indices must be integers or slices, not list, PCA function def pca(self,message):
        X=self.getData(False)
        pca = PCA(n_components=2)
        df=pca.fit(X[message])
        component_names = [f"PC{i+1}" for i in range(df.shape[1])]
        df = pd.DataFrame(df, columns=component_names)
        self.outDB.connectDB()
        self.outDB.createTable(self.outputName,df)
        self.outDB.disconnectDB()
        self.logDEBUG("PCA is done")

This is the PCA function that I'm using. I've converted the principal components into a data frame to fit a model. But it throws me the error that tuple indices must not be list. What should I do?


text:
Q: Importing beyond top-level package fails in python3 I need some help. I have been stuck with this for a while. I cannot figure out how and what to do.
I have a directory "folder" with the below structure.
.
├── folder1
│   ├── folder3
│   │   ├── a.py
│   │   └── __init__.py
│   └── __init__.py
├── folder2
│   ├── b.py
│   └── __init__.py
└── __init__.py

What I want to basically do is import a function in the "folder2/b.py" python file into "folder1/folder3/a.py". And I want to run the 'a.py' file from "folder1/folder3/" directory.
Let me illustrate this with an example. Suppose I have a function 'hello' in 'b.py'.
def hello():
    print("Hello world!")

And I have another file 'a.py' like this.
from b import hello

def hello1():
   print("Hello World!!")

I want to navigate to the 'folder3' directory.

cd folder1/folder3

And run the python file 'a.py' as follows.

python a.py

Doing so is giving me the below error.

ValueError: attempted relative import beyond the top-level package

I googled for a while and tried solving this with these resources (Import a module from a relative path, relative path not working even with init.py, How to fix "Attempted relative import in non-package" even with init.py).
The only method that worked so far is by using "sys.append" in 'a.py' like below. However, I have read that this usage is very unprofessional and highly unrecommended.
import sys
sys.path.append("D:/folder")

from folder2 import b

If you have dealt with such a setup/issue before, please help me out. Thanks!

A: Try adding your root folder to your python path.


text:
Q: Unity create a project for the first time I have just installed Unity and I am trying to create a project for the first time. Now all tutorials and books I ve read say to put the data for the new project and apply create and then work from there.
But after I did that first step I only get a progress bar that says "Unity Package Manager" "Starting Server..."
This is not mentioned in any tutorial and it is taking forever. It seems stucked.
What is this server that Unity has to start to simply create a project?


text:
Q: Launch PowerShell scriptblock asynchronously without dependency on parent process Below is a small PowerShell script that runs some PowerShell code asynchronously to show a dialog box (for the purpose of demonstrating my issue).
If I close the parent PowerShell process, the child process will also close and the dialog box disappears. Is there any way to launch a PowerShell scriptblock, complete with functions and arguments, asynchronously and without a dependence on the parent PowerShell process?
    $testjob = [PowerShell]::Create().AddScript({ $a = new-object -comobject wscript.shell
    $b = $a.popup('This is a test',5,'Test Message Box',1) })
    $result = $testJob.BeginInvoke()

Update #2
I am trying to execute a script block, rather than an external script. The script block should use functions and variables from the parent script. The problem is, I can't pass those functions or variables in to the new process unless they are contained directly within the script block. Any idea if this is doable?
    Function Show-Prompt {
        Param ($title,$message)
            $a = new-object -comobject wscript.shell
            $b = $a.popup($message,5,$title,1)
    }

    $scriptContent = {Show-Prompt -Message 'This is a test' -Title 'Test Message Box'}
    $scriptBlock = [scriptblock]::Create($scriptContent)
    Start-process powershell -argumentlist "-noexit -command &{$scriptBlock}"

A: You can use an intermediate PowerShell process.  There has to be a direct parent to process the return value from the async script.  For instance, put your script in a file called popup.ps1 and try execute like so:
Start-Process PowerShell -Arg c:\popup.ps1

You might want to bump the timeout up a bit from say 5 to 10 seconds.  You can close the original PowerShell and the popup will stay.  When you close the popup (or it times out) the secondary PowerShell window will disappear.

A: You can do this with WMI.  If you use Win32_Process to create the process, it will persist after you close PowerShell.
For instance:
invoke-wmimethod -path win32_process -name create -argumentlist calc

A: function GeneratePortableFunction {
    param ([string] $name, [scriptblock] $sb)
    $block = [ScriptBlock]::Create("return `${function:$name};");
    $script = $block.Invoke();
    $block = [ScriptBlock]::Create($script);
    return ("function {0} {{ {1} }}" -f $name, $block.ToString());
}
function RemoteScript {
    param ([string] $header, [string[]] $functions, [string] $footer)
    $sb = New-Object System.Text.StringBuilder;
    [void]$sb.Append("$header`n");
    $functions | % {
        [void]$sb.Append($_);
        [void]$sb.Append("`n");
    }
    [void]$sb.Append($footer);
    return [ScriptBlock]::Create($sb.ToString());
}

$fnc = @();
$fnc += GeneratePortableFunction -name "NameOfYourFunction1";
$fnc += GeneratePortableFunction -name "NameOfYourFunction2(CallsNameOfYourFunction1)";
$script = RemoteScript -header "param([int] `$param1)" -functions @($fnc) -footer "NameOfYourFunction2 -YourParameter `$param1;";
$p1 = 0;
$job = Start-Job -ScriptBlock $script -ArgumentList @($p1);
while($job.State -eq "Running")
{
    write-host "Running...";
    Start-Sleep 5;
}
$result = $job | Receive-Job;
Remove-Job -Id $job.Id;


text:
Q: Object reference not set to an instance of an object test if a button in other Form is cliked I have 2 Forms,FormA and FormB,for FormA have a button,in FormB I have to test if this button in formB is cliked,I tried this code:
FormA://in which I have the button
public bool button6WasClicked = false;

private void button6_Click(object sender, EventArgs e)
{
  ............
  button6WasClicked = true;
}

FormB://in which I have to test if the button in FormA is cliked
FormA nv;

private void button3_Click(object sender, EventArgs e)
{
    if (nv.button6WasClicked) //the error is at this line
    {
        ..........
        button6WasClicked = false;
    }
}

I have this problem :

the Translation is:Object reference not set to an instance of an object
thanks for Help :)

A: I guess below code should work :-
in constrctor you have to pass your FormA  object as shown below :-
public FormA nv;

    Public FormB(FormA formA)
    {
        nv = formA;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        if (nv.button6WasClicked)
        {
            ..........
            nv.button6WasClicked = false;
        }
    }


text:
Q: Laravel 9: How to rebuild Javascript files in a project I have created a Laravel 9 project recently on mac. I am trying to use Vue components in my project. The Laravel installation comes with a Vue component (js/Components/ExampleComponenets.vue). I included the example-component in a view file, and the page displays the component correctly.
I made a copy of this component as js/Components/NoteComponent.vue and updated app.js to register the new component as 'note-component'
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('note-component', require('./components/NoteComponent.vue').default);

However, when I used the  note-component in my view file, it displays error:
[Vue warn]: Unknown custom element: <note-component> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

(found in <Root>)

I removed the note-component from my view file and made a change to the console.log used in the ExampleComponent.vue, but surprisingly, the page continues to display the old message. I am getting an impression that somehow the application continues to use the old js files, and I need to do something to rebuild/regresh the js files. (php artisan clear:cache) did not help.
Can someone please advise how to fix this issue?
Thanks.

A: You need use npm run dev to start your vue server and remember, js is loaded when page was stored in browser memory, so do a full reload

*

*Command + Shift + R in mac

*CTRL + Shift + F5 in windows

A: We updated to Laravel to v9 recently and had to modify the js files in this way:
import Vue from "vue";

Vue.component("example", () => import("./components/ExampleComponent"));

Source: Vue template or render function not defined yet I am using neither?


text:
Q: Select an element inside an HTML template I have a template as below:
<script type="text/template" id="editorItemPlacholder">
    <div>
    ...
    </div>
</script>

And create an instance of the template like this:
var editorItemTemplate = $("#editorItemPlacholder").html();

Then I want to change the id of an element inside the template, each time I make an instance of it. So I think I must use this:
editorItemTemplate.find("div").prop("id",item);

but this doesn't work. And the sign is that the code doesn't go after this line. What is wrong with this type of selection? How can I make change in that template.

A: You are using a jQuery function in a html element. You can not use find into $editorItemTemplate, which contains the html of the template.
You have to find the element using this way:
$('div', $editorItemTemplate).prop('id', item);

Regards.


text:
Q: postgresql - key/value lookup to json object Running Postgres 9.6.
So I have this key/value lookup table which establishes the deepest child value of a huge JSON object.  Given a table of this structure:
CREATE TABLE myschema.file_items
(
    id integer NOT NULL DEFAULT nextval('file_items_id_seq'::regclass),
    file_id integer NOT NULL,
    key character varying[] COLLATE pg_catalog."default" NOT NULL,
    value character varying COLLATE pg_catalog."default",
    status character varying COLLATE pg_catalog."default",
    CONSTRAINT file_items_pkey PRIMARY KEY (id)
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE verification.file_items
    OWNER to postgres;

insert into file_items (file_id, key, value, status)
values (1, '{"cogs","cog1","description"}', 'val1', 'approved');
insert into file_items (file_id, key, value, status)
values (1, '{"cogs","cog1","cost"}', '100', null);
insert into file_items (file_id, key, value, status)
values (1, '{"cogs","cog1","window"}', '[-200,500]', 'not verified');
insert into file_items (file_id, key, value, status)
values (1, '{"cogs","cog2","description"}', 'val2', 'approved');
insert into file_items (file_id, key, value, status)
values (1, '{"cogs","cog2","cost"}', '200', null);
insert into file_items (file_id, key, value, status)
values (1, '{"cogs","cog2","window"}', '[-300,500]', null);

insert into file_items (file_id, key, value, status)
values (1, '{"widgets","widget1","description"}', 'wid1', 'approved');
insert into file_items (file_id, key, value, status)
values (1, '{"widgets","widget1","cost"}', '100', 'approved');
insert into file_items (file_id, key, value, status)
values (1, '{"widgets","widget1","window"}', '[-200,500]', 'not verified');
insert into file_items (file_id, key, value, status)
values (1, '{"widgets","widget2","description"}', 'wid2', null);
insert into file_items (file_id, key, value, status)
values (1, '{"widgets","widget2","cost"}', '300', 'approved');
insert into file_items (file_id, key, value, status)
values (1, '{"widgets","widget2","window"}', '[-1000,700]', null);

I can query all my cogs like so:
select *
from file_items
where 'cogs' = any(key)

How would I reverse-engineer this object?  Rather, I'd like to somehow generate a json object with the following format:
"cogs": {
    "cog1": {
        "description": "val1",
        "cost":100,
        "window":[-200,500]
    },
    "cog2": {
        "description": "val2",
        "cost":200,
        "window":[-300,500]
    }
}

Note that I'm deliberately not wanting to do an array of cogs objects.  They are actual properties to the cogs object.  Done this way as we can have incoming json objects to which we don't know all the properties of, thus we utilize a key/value mapping table to be able to dynamically identify what these property values are (ie, we don't know before hand that we're going to have a "cog67" object, or what kind of properties will be affixed to that object....).
Since this query would ultimately be fired from a Node.js package ('pg' module...), if I can't re-create the json object via query, I may need to do it in the javascript itself.  Just wondering if it's possible to to correctly build the json object at the database level and return that though, rather than querying a bunch of rows and re-constructing the object in the server-side code.
Any help would be greatly appreciated!  Thank you!

A: Use jsonb_object_agg() twice, for both levels of aggregation (jsonb_pretty() not necessary, used for a nice output):
select jsonb_pretty(jsonb_build_object(key, jsonb_object_agg(subkey, value)))
from (
    select key[1], key[2] as subkey, jsonb_object_agg(key[3], value) as value
    from file_items
    where 'cogs' = any(key)
    group by key[1], key[2]
    ) s
group by key;

            jsonb_pretty
-------------------------------------
 {                                  +
     "cogs": {                      +
         "cog1": {                  +
             "cost": "100",         +
             "window": "[-200,500]",+
             "description": "val1"  +
         },                         +
         "cog2": {                  +
             "cost": "200",         +
             "window": "[-300,500]",+
             "description": "val2"  +
         }                          +
     }                              +
 }
(1 row)


text:
Q: How to compute a least common ancestor algorithm's time complexity? I came into an article which talking about the LCA algorithms, the code is simple
http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html
// Return #nodes that matches P or Q in the subtree.
int countMatchesPQ(Node *root, Node *p, Node *q) {
  if (!root) return 0;
  int matches = countMatchesPQ(root->left, p, q) + countMatchesPQ(root->right, p, q);
  if (root == p || root == q)
    return 1 + matches;
  else
    return matches;
}

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root || !p || !q) return NULL;
  if (root == p || root == q) return root;
  int totalMatches = countMatchesPQ(root->left, p, q);
  if (totalMatches == 1)
    return root;
  else if (totalMatches == 2)
    return LCA(root->left, p, q);
  else /* totalMatches == 0 */
    return LCA(root->right, p, q);
}

but I was wondering how compute the time complexity of the algorithm,can anyone help me?

A: The complexity of LCA is O(h) where h is the height of the tree. The upper bound of the tree height is O(n), where n denotes the number of vertices/nodes in the tree.
If your tree is balanced, (see AVL, red black tree) the height is order of log(n), consequently the total complexity of the algorithm is O(log(n)).

A: The worst case for this algorithm would be if the nodes are sibling leave nodes.
Node *LCA(Node *root, Node *p, Node *q)
{
  for root call countMatchesPQ;
  for(root->left_or_right_child) call countMatchesPQ; /* Recursive call */
  for(root->left_or_right_child->left_or_right_child) call countMatchesPQ;
  ...
  for(parent of leave nodes of p and q) call countMatchesPQ;
}

countMatchesPQ is called for height of tree times - 1. Lets call height of tree as h.
Now check the complexity of helper function
int countMatchesPQ(Node *root, Node *p, Node *q) {
  Search p and q in left sub tree recursively
  Search p and q in right sub tree recursively
}

So this is an extensive search and the final complexity is N where N is the number of nodes in the tree.
Adding both observations, total complexity of the algorithm is
O(h * N)

If tree is balanced, h = log N (RB tree, treap etc)
If tree is unbalanced, in worse case h may be up to N
So complexity in terms of N can be given as

For balanced binary tree: O(N logN)
To be more precise, it is actual h(N + N/2 + N/4...)
for balanced tree and hence should come 2hN
For unbalanced binary tree: O(N2)
To be more precise, it is actual h(N + N-1 + N-2...)
for balanced tree and hence should come h x N x (N+1) / 2

So the worse case complexity is N2
Your algorithm doesn't use any memory. By using some memory to save path, you can improve your algorithm drastically.


text:
Q: Launching a URL from an Eclipse plugin I'd like to have my Eclipse plugin cause a URL to be opened by the users' default browser. This seems like pretty standard behavior, but I haven't been able to find any docs on how to do this.
Can anyone help?

A: You are looking for:
final IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser( ... );
browser.openURL(url);

A: Use Program.launch(String) from the SWT API.
(Alternatively, Java 6 introduced the Desktop class.)

A: If you want it in an external browser, you don't need to create one. This is the way:
PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL("http://www.example.com/"));

A: Do you mean launch an external windows (IE, FireFox, ...) outside eclipse, or opening an internal "Browser" composite ?
Because on the internal side, the org.eclipse.help.ui.internal.browser.embedded.EmbeddedBrowser seems to be able to define any kind of major browser.
To open the default user's browser (as an internal or external window) is a preference defined in General/Web browser.


text:
Q: selenium click() not working on closing pop-up I've been working on a fake "bet bot" in order to learn selenium, but I'm having trouble closing a pop up that shows up sometimes on the web site that I want to get the odds from.
My approach is to use the function submit_bets(); a filtered games list in the form:
"League|team 1|team 2|Date|Probability in %|and prediction(1,X or 2)"

I get the data from here. Then for each of the filtered games I open the league bet page on the betting website, and go through all the games there to find the filtered game and get the real odds. For each filtered game in filtered_games I need to open the page of the bet website and if the pop up shows up, I can't get the data.
def submit_bets(filtered_games):
driver = webdriver.Chrome(PATH)
f=codecs.open("bets.txt","r", encoding='utf-8')
for line in filtered_games:
    l=line.split("|")
    print(l)
    driver.get(leagues_to_links.get(l[0]))
    scroll_down(driver)
    time.sleep(2)
    try:
        button = driver.find_element(By.XPATH, "/html/body/div[1]/div/section[2]/div[7]/div/div/div[1]/button" )
        driver.execute_script("arguments[0].scrollIntoView(true)", button)
        button.click()
    except:
        print("no button")
    games=driver.find_elements_by_class_name("events-list__grid__event")
    for i in games:
        game=str(i.text).split("\n")
        try:
            if forebet_teams_to_betano.get(l[1]) in game[2] and forebet_teams_to_betano.get(l[2]) in game[3]:
                print(game)
                if str(l[5]) == "1":
                    print("1")
                    print(str(game[7]))
                elif str(l[5]) == "X":
                    print("X")
                    print(str(game[9]))
                else:
                    print("2")
                    print(str(game[11]))
        except:
            print("")

In this link you can find the html of the page when the pop up shows up:
Github page with the html
In this link you can find the page files, you might have to refresh it sometimes to get the pop up
Thank you for your time, and feel free to leave any tips to improve my code.

A: My solution:
#Closing popup for Portugese betting site

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

URL = "https://www.betano.pt/sport/futebol/ligas/17083r/"

# Browser options
options = Options()
options.headless = True
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)

browser = webdriver.Firefox(firefox_profile=firefox_profile)
browser.get(URL)

##### Copy this part into your own code #####
try:
    browser.find_element_by_xpath('//button[@class="sb-modal__close__btn uk-modal-close-default uk-icon uk-close"]').click() # Click pop-up close button
    print("Pop-up closed.")
except:
    print("Pop-up button not found.")
#########

Closes this popup:

Keep in mind this relies on finding the button by it's very specific class name. You'll need to adapt the try-except at the end into your own code.


text:
Q: Why -frameForAlignmentRect: and -alignmentRectForFrame: not calling on IOS I want to use -frameForAlignmentRect: and -alignmentRectForFrame: to specify alignment rects in my iOS apps. But this methods not calling.
I have almost identical code for iOS and Mac. It is works perfectly on OS X but not on iOS.
Mac version
@implementation CustomView

#define SHADOW_SIZE 10

- (void)drawRect:(NSRect)dirtyRect {
    NSBezierPath *path;

    [[NSColor redColor] set];
    path = [NSBezierPath bezierPathWithRect:dirtyRect];
    [path fill];

    // Draw a shadow
    NSRect rect = NSMakeRect(SHADOW_SIZE, 0, dirtyRect.size.width - SHADOW_SIZE, dirtyRect.size.height - SHADOW_SIZE);
    path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:32 yRadius:32];
    [[[NSColor blackColor] colorWithAlphaComponent:0.3f] set];
    [path fill];

    // Draw shape
    rect.origin = CGPointMake(0, SHADOW_SIZE);
    path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:32 yRadius:32];

    [[NSColor orangeColor] set];
    [path fill];
}

#define USE_ALIGNMENT_RECTS 1

#if USE_ALIGNMENT_RECTS
- (NSRect)frameForAlignmentRect:(NSRect)alignmentRect {
    NSRect rect = alignmentRect;
    rect.origin.y -= SHADOW_SIZE;
    rect.size.width += SHADOW_SIZE;
    rect.size.height += SHADOW_SIZE;
    return rect;
}

- (NSRect)alignmentRectForFrame:(NSRect)frame {
   NSRect rect;
    rect.origin = CGPointMake(frame.origin.x, frame.origin.y + SHADOW_SIZE);
    rect.size.width = frame.size.width - SHADOW_SIZE;
    rect.size.height = frame.size.height - SHADOW_SIZE;
    return rect;
}
#endif
@end

@implementation AppDelegate

- (void)awakeFromNib {

    _view = _window.contentView;

    CustomView *view = [[CustomView alloc] init];
    [self.view addSubview:view];

    view.translatesAutoresizingMaskIntoConstraints = NO;

    // Set vertical and horizontal alignments and view size
    // A little trick from here https://github.com/evgenyneu/center-vfl

    NSDictionary *views = NSDictionaryOfVariableBindings(_view, view);
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[_view]-(<=1)-[view(200)]"
                                                               options:NSLayoutFormatAlignAllCenterY
                                                               metrics:nil
                                                                 views:views]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_view]-(<=1)-[view(200)]"
                                                                  options:NSLayoutFormatAlignAllCenterX
                                                                  metrics:nil
                                                                    views:views]];
}

@end

iOS version
@implementation MyView

#define SHADOW_SIZE 10

- (void)drawRect:(CGRect)dirtyRect {
    UIBezierPath *path;

    [[UIColor redColor] set];
    path = [UIBezierPath bezierPathWithRect:dirtyRect];
    [path fill];

    // Draw a shadow
    CGRect rect = CGRectMake(SHADOW_SIZE, SHADOW_SIZE, dirtyRect.size.width - SHADOW_SIZE, dirtyRect.size.height - SHADOW_SIZE);
    path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:32];
    [[[UIColor blackColor] colorWithAlphaComponent:0.3f] set];
    [path fill];

    // Draw shape
    rect.origin = CGPointMake(0, 0);
    path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:32];
    [[UIColor orangeColor] set];
    [path fill];
}

#define USE_ALIGNMENT_RECTS 1
#define USE_ALIGNMENT_INSETS 1

#if USE_ALIGNMENT_RECTS
- (CGRect)frameForAlignmentRect:(CGRect)alignmentRect {
    CGRect rect = alignmentRect;
    rect.size.width += SHADOW_SIZE;
    rect.size.height += SHADOW_SIZE;
    return rect;
}

- (CGRect)alignmentRectForFrame:(CGRect)frame {
    CGRect rect = frame;
    rect.size.width = frame.size.width - SHADOW_SIZE;
    rect.size.height = frame.size.height - SHADOW_SIZE;
    return rect;
}
#endif

#if USE_ALIGNMENT_INSETS
- (UIEdgeInsets)alignmentRectInsets {
    return UIEdgeInsetsMake(0, 0, SHADOW_SIZE, SHADOW_SIZE);
}
#endif

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    MyView *view = [[MyView alloc] init];
    [self.view addSubview:view];

    view.translatesAutoresizingMaskIntoConstraints = NO;

    UIView *superview = self.view;
    NSDictionary *views = NSDictionaryOfVariableBindings(superview, view);
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[superview]-(<=1)-[view(200)]"
                                                                  options:NSLayoutFormatAlignAllCenterY
                                                                  metrics:nil
                                                                    views:views]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[superview]-(<=1)-[view(200)]"
                                                                  options:NSLayoutFormatAlignAllCenterX
                                                                  metrics:nil
                                                                    views:views]];
}

@end

As you can see iOS version has also -alignmentRectInsets: which works well, but i want to figure out whats wrong with -frameForAlignmentRect: and -alignmentRectForFrame: methods.


text:
Q: Win32:trojan-gen virus exe installed I ran fake exe as i thought it was another program. After deep scanning with AVG, it located a win32:trojan-gen exe, moved it to quarantine and deleted. After scaning again, shows no malware. I am still worried if it's completely removed, should I do additional steps?

A: "win32:trojan-gen exe" is a fairly generic warning about an executable program (exe) that could be malware, but has not yet actually been run, nor done any harm, yet. I.E., it appears AVG intercepted it before harm was done.
That said, if you believe that there could be malware on your machine, it does no harm to run a free, third-party malware scanner, such as Malwarebytes or an alternative.
Before running or installing any third-party application, whether an anti-malware suite or some other application, check it in VirusTotal, which submits it to 60 or more reputable malware scanners. [If only one or two flags are raised, I might consider them perhaps false positives.]


text:
Q: Fallback location for psr-0/4 autoloading I'm building a PHP package and in it I have a folder (let's say /vendor/myvendor/packagename/src/Classes) which I want to autoload using PSR-4.
But I would also like to provide an option to copy that folder from its current location to the project root (let's say /packagename/Classes, something along the lines of Laravel's publish command).
So how could I go about autoloading it?
I would like Composer to first see if the folder exists under the app's root, and if it does then autoload that. Else fall back to the default location inside /vendor. Is that possible?
FWIW, this is Laravel specific package, which means that I could use Laravel's publish command to copy the entire folder where ever, but then

*

*I would have to manually add the new location to autoload;

*Even if I do, there would be namespace conflict between the old and new location.

A:
I would like Composer to first see if the folder exists under the app's root, and if it does then autoload that. Else fall back to the default location inside /vendor. Is that possible?

Yes, it is possible.
You need to mention everything on your ServiceProvider for your package.
There are every informations about how to publish your views, assets in the docs and it fits your needs.
Have a look at the docs:

https://laravel.com/docs/5.3/packages#public-assets

I am copying some example for you over here:
If you want to publish your translations, you need to perform this task:
/**
 * Perform post-registration booting of services.
 *
 * @return void
 */
public function boot()
{
    $this->loadTranslationsFrom(__DIR__.'/path/to/translations', 'courier');

    $this->publishes([
        __DIR__.'/path/to/translations' => resource_path('lang/vendor/courier'),
    ]);
}

If you don't have translation in app's lang/vendor/courier then it falls back to your package translation.
You don't need to copy your class codes, which could remain in your package directory. The only things you copy will be your views, assets, translation files etc.
This should help you.