text:
Q: difference between two comma separated strings I have the following dataframe yy
    fundId  Year    Qtr   StockCurrentQtr    StockNextQtr
    1       2015    1     1,2,3,4,5         2,3,4,51
    1       2015    2     2,3,4,51          7,8,9,4,2
    1       2015    3     7,8,9,4,2         NA
    2       2015    1     10,11,14          14,16,19
    2       2015    2     14,16,19          20,21,45
    2       2015    3     20,21,45          NA

I want to know the difference between StockNextQtr and StocCurrentQtr for each row group_by fundId or the difference between successive rows for the column 'StockCurrentQtr' group_by fundId
yy <- yy %>%
       group_by(fundId) %>%
       mutate(StockDiff = apply(yy,2,function(x){
                    paste(setdiff(unlist(strsplit(x[5], split = ",")), unlist(strsplit(x[4],
                                                            split = ","))),collapse = ",")}))

I am getting following error:

Column StockDiff must be length 3 (the group size) or one, not 5

A: You don't have to use apply here. Just rowwise, i.e.
library(dplyr)

df %>%
 mutate_at(vars(4:5), funs(strsplit(., ','))) %>%
 rowwise() %>%
 mutate(new = toString(setdiff(StocCurrentQtr, StockNextQtr)))

which gives,

Source: local data frame [6 x 6]
Groups: <by row>

# A tibble: 6 x 6
  fundId  Year   Qtr StocCurrentQtr StockNextQtr new
   <int> <int> <int> <list>         <list>       <chr>
1      1  2015     1 <chr [5]>      <chr [4]>    1, 5
2      1  2015     2 <chr [4]>      <chr [5]>    3, 51
3      1  2015     3 <chr [5]>      <chr [1]>    7, 8, 9, 4, 2
4      2  2015     1 <chr [3]>      <chr [3]>    10, 11
5      2  2015     2 <chr [3]>      <chr [3]>    14, 16, 19
6      2  2015     3 <chr [3]>      <chr [1]>    20, 21, 45

The equivalent in base R,
mapply(function(x, y)toString(setdiff(x, y)), strsplit(df$StocCurrentQtr, ','),
                                              strsplit(df$StockNextQtr, ','))

#[1] "1, 5"          "3, 51"         "7, 8, 9, 4, 2" "10, 11"        "14, 16, 19"    "20, 21, 45"

If StockNextQtr is missing, we can create it first and continue in the same manner as before, i.e.
df %>%
 group_by(fundId) %>%
 mutate(StockNextQtr = lead(StocCurrentQtr)) %>%
 mutate_at(vars(4:5), funs(strsplit(., ','))) %>%
 rowwise() %>%
 mutate(new = toString(setdiff(StocCurrentQtr, StockNextQtr)))

A: I found another way
yy <- yy %>% group_by(fundId, Year, Qtr) %>% mutate(new = paste(setdiff((unlist(strsplit(StockCurrentQtr,split = ","))), unlist(strsplit(StockNextQtr,split = ","))),collapse = ","))


text:
Q: Display attributes of an has_many through connection I have an invoice which has_many line_items which belongs_to products too. On invoice#show I want to display all line_items of that invoice with the name of the associated product. Coming from Rails I have a hard time to connect the dots. line_item.product.name in the template doesn't work. How can I display the product`s name in that table?
The application
mix phoenix.new my_app
cd my_app
mix ecto.create
mix phoenix.gen.html Invoice invoices number
mix phoenix.gen.html Product products name price:integer
mix phoenix.gen.html LineItem line_items invoice_id:references:invoices
                                         product_id:references:products
                                         quantity:integer
mix ecto.migrate

web/models/invoice.ex
defmodule MyApp.Invoice do
  use MyApp.Web, :model

  schema "invoices" do
    field :number, :string
    has_many :line_items, MyApp.LineItem
[...]

web/controllers/invoice_controller.ex
[...]
def show(conn, %{"id" => id}) do
  invoice =
    Repo.get!(Invoice, id)
    |> Repo.preload([:line_items])

  render(conn, "show.html", invoice: invoice)
end
[...]

web/templates/invoice/show.html.eex

Invoice <%= @invoice.number %>

      Product
      Quantity

<%= for line_item <- @invoice.line_items do %>

      <%= line_item.product.name %>
      <%= line_item.quantity %>

<% end %>

A: One way to handle this case to add a Ecto.Schema.has_many/3 :through option like so:
web/models/invoice.ex
defmodule MyApp.Invoice do
  # ...
  schema "invoices" do
    field :number, :string
    has_many :line_items, HasMany.LineItem
    has_many :products, through: [:line_items, :product]

    timestamps
  end
  # ...
end

Because the association runs through :line_items, you preload both associated :line_items and :products with a query like this:
web/controllers/invoice_controller.ex
def show(conn, %{"id" => id}) do
  invoice =
    Repo.get!(Invoice, id)
    |> Repo.preload([:products])

  render(conn, "show.html", invoice: invoice)
end

The docs provide some great examples regarding "has_many/has_one :through" associations: https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3

redpajama_set_name: RedPajamaStackExchange


text:
Q: CakePHP 3: Database syntax error or access violation issue I have the following code which runs fine in a vagrant environment, but fails in the server. Can't figure out why.
$settingsQuery = $this->Configurations->find()
                ->select([
                    'id',
                    'name',
                    'value',
                    'description',
                    'editable',
                    'keyPrefix' => "SUBSTR(name FROM 1 FOR POSITION('.' IN name) - 1)"
                ])->order('name');

if I comment out this part //'keyPrefix' => "SUBSTR(name FROM 1 FOR POSITION('.' IN name) - 1)" the code executes without issues. Something is wrong with this, but just on the server, not at the local dev.
I am getting the following error:

I am running CakePHP 3.4 on PHP 5.6 and MySQL 5.6 on an Ubuntu box.
The SQL query generated by my vagrant setup (dev) runs well when tried thru phpMyAdmin
SELECT Configurations.id AS `Configurations__id`, Configurations.name AS `Configurations__name`, Configurations.value AS `Configurations__value`, Configurations.description AS `Configurations__description`, Configurations.editable AS `Configurations__editable`, SUBSTR(name FROM 1 FOR POSITION('.' IN name) - 1) AS `keyPrefix` FROM settings_configurations Configurations ORDER BY name

A: Then you can print sql by dump($this->getLastSql()) and copy the Sql  deal in Sql environment.Then you can get the Error.


text:
Q: Laravel 5.2: Different view-layout depending on route I'd like to have two routes for every page on my website.
One route should extend the view from layouts/foo.blade.php and the other route should extend from layouts/bar.blade.php.
For example if enter example.com/foo/about I get my about-page with foo-layout. If I enter example.com/bar/about I get my about-page with bar-layout.
How would I solve this?

A: Well, you can use Request::segment() (or something like this), in order to dynamically set your base layout:
@extends( Request::segment(1) == 'foo' ? 'foo.blade.php' : 'bar.blade.php')

Where 1 (segment argument) is the first URL segment.


text:
Q: Thread-safety of bool flag crossing an async boundary Can the following case be assumed de facto thread-safe? The bool flag always starts at false and only goes one way to true or stays as is.
I know it's actually not thread-safe, but is it possible to really break somehow?
In this case the async execution is even strictly ordered and never parallel.
bool cancelled = false;

await MyAsyncJob.Process(() =>
{
    if (timeout)
    {
        cancelled = true;
    }
});

if (cancelled)
{
    DoSomething();
}

A:
Can the following case be assumed de facto thread-safe? The bool flag...

It's not clear which flag you're referring to.
In your code, the cancelled flag will work as you expect, because it is checked after the method that sets it is awaited. The code running after the await will see all side-effects caused by the awaited method.
However, timeout does not look thread-safe at all. The awaited code checks timeout but is (probably) not awaiting whatever code sets timeout.
You could go through the trouble of using locks and whatnot, or you can use the CancellationTokenSource, CancellationToken, and OperationCanceledException provided by the .NET framework for exactly this scenario:
try
{
  await MyAsyncJob.Process(() =>
  {
    cancellationToken.ThrowIfCancellationRequested();
  });
}
catch (OperationCanceledException)
{
  DoSomething();
}

By following the standard pattern, other developers will be able to understand your code more quickly. And you won't have to worry about thread safety at all; the provided framework types take care of it.


text:
Q: UI automation to take actions on directing to a third party website I want to know whether there is a way to take an action ( ex: clicking a button ) when directing to a third party website (ex: facebook.com ) from our website.
Ex: When someone clicks the Facebook icon on my website, it directs to a Linkedin page while opening the chat with a draft message.

A: No. At least not in the general case.
If it was possible to build a UI automation tool into a webpage which could take actions on completely different sites then you could set things up so that clicking a button on your site would cause my browser to visit my bank's website and transfer you money.
Browser vendors take some basic security precautions to prevent that sort of thing.


text:
Q: "cordova run ios " in Windows not works I install "ionic cordova run ios" on my PC (Windows 10) but I got an error message
"[ERROR] An error occurred while running subprocess cordova."
Does anyone know how to fix this?

A: To build an app for iOS you need to have the xcode command line tools  installed. Cordova looks for these tools before building. If you don't have that, you can't build your app for iOS.
If you want to build your app for iOS you'll need a Mac with xcode and Cordova installed. Or you could use a virtual machine to do it. For more information on the virtual machine option have look here


text:
Q: Hardcoded value or external property takes precedence for DB pool size? I have the below configuration in my springboot code :
xaDataSource.setMaxPoolSize(50);

Also I have this in the application.properties
data-source.reference.maximumPoolSize=15

Which one takes precendence?


text:
Q: Eclipse Oxygen - projects disappear Why do projects disappear from the project explorer in Oxygen?  I can see them briefly after starting Eclipse but then they disappear.
They can't be re-added or imported because it says they already exist.
I re-cloned the project from git into a different directory, deleted .classpath, .settings and .project and tried to import as a file system but can't advance.  The next button is greyed out.
Import projects from folder or archive allowed me to import my clone but then it dissappears again. I know it's there because if I select build, I see my newly added project and other projects that have disappeared.

A: Probably, the projects are only hidden by the active Working Set or by Focus on Active Task.


text:
Q: Optimizing calculation for Weighted Geometric Mean of a big set of data using GPU I need help with an optimization and performance problem related to the calculation of the Weighted Geometric Mean of some data.
I introduce the problem with a little sample.
I wrote the code to calculate the WGM for the simple example below.
% A matrix Example 3x3 matrix
% w column vector 3x1
% wgm row vector 1x3

A = rand(3);
w = [1,2,6]';
wgm = (prod(A.^w)).^(1/sum(w));

Now for the general problem:
Suppose I have a new A matrix sized nxm
and a W matrix composed of weight columns where weights values can go from 0 to k and I need all the columns permutations.
That is the W matrix is sized as n x k^n, since the nature of the weights and the weighted geometric computation this final matrix should be reduced excluding columns that represent a multiplication by a scalar value going from 0 to k of a permutation.
So if I have a column like [1, 1, 0] already that should exclude all t*[1,1,0] with t going from 0 to k.
Another example: [1 2 3] should exclude [2 4 6] or [3 6 9] and so on.
Basic idea: each generated column for the W matrix could be normalized dividing each weight by k, so if the new normalized column is redundant should not be added then converted back to an uint8 column to reduce memory consumption to 12.5%.
So considering a real data example suppose:

*

*I have a static A matrix 32x30.

*Weights values that go from 0 to 99.

*I need a way to create the W Matrix sized 32x100^32 and to optimize it.

*To calculate an optimized originally WGM 100^32x30 matrix where each row is the computation result from A matrix and corresponding W column.

So the problems to solve are:

*

*Creation of the optimized matrix of Weights both in size and performance.

*Calculation of the WGM Matrix.

*A way to allocate and partition those matrixes to avoid memory problems.

*Converting the Matlab code to GPU code for computation on a Cuda Device (1080 GTX with 8 GB video memory).

*Storing the final matrices in an efficient way.

Added information:
The Weighted Geometric Means matrix data will be validated through a set of stricter rules, and so not compliant rows will be discarded, same for the final W matrix where the elimination will occur for corresponding columns.
This could be evaluated earlier while creating the 2 matrices to find a solution that optimizes memory consumption while being maybe less efficient performance wise.


text:
Q: gcloud composer dags command error: gcloud crashed (TypeError): () takes 4 positional arguments but 6 were given I have a strange error when i try to execute the gcloud composer dags command like below.
$ gcloud composer environments run airflow-stg --location us-west1 dags list

and I got this error message:

kubeconfig entry generated for us-west1-airflow-stg-9c36547e-gke.
ERROR: gcloud crashed (TypeError): () takes 4 positional arguments but 6 were given
If you would like to report this issue, please run the following command:
gcloud feedback
To check gcloud for common problems, please run the following command:
gcloud info --run-diagnostics

I tried to reinstall my GCloud SDK but it still did not work.
Here is my computer environment:
apple macbook air M1

python version: 3.9.6 (use pyenv for global)

gcloud version:
   Google Cloud SDK 390.0.0
   bq 2.0.75
   core 2022.06.10
   gsutil 5.10


text:
Q: estimator for the derivative of the local linear model (SAS) I estimate a local linear model for the data with one continuous dependent variable and multiple explanatory variables (continuous and dichotomous).
Is it possible to estimate the derivatives of this function for each bundle of explanatory variables and save them for the further usage? How can one do it in SAS?
In principle, I would like to get some kind of analogue to the parameter estimates in a simple parametric regression. But now I would have not a one-point estimator but rather a distribution for each of the variable.
Thanks for any suggestions, comments, clarifications.
UPDATE:
For example, if I use the SAS datasample "ExperimentA" and run the local linear model, how can I get after the estimation the derivative for each indep.variable at each row of the data?
data ExperimentA;
    format Temperature f4.0 Catalyst f6.3 Yield f8.3;
    input Temperature Catalyst Yield @@;
datalines;
80  0.005 6.039  80 0.010 4.719  80 0.015 6.301
80  0.020 4.558  80 0.025 5.917  80 0.030 4.365
80  0.035 6.540  80 0.040 5.063  80 0.045 4.668
80  0.050 7.641  80 0.055 6.736  80 0.060 7.255
80  0.065 5.515  80 0.070 5.260  80 0.075 4.813
80  0.080 4.465  90 0.005 4.540  90 0.010 3.553
90  0.015 5.611  90 0.020 4.586  90 0.025 6.503
90  0.030 4.671  90 0.035 4.919  90 0.040 6.536
90  0.045 4.799  90 0.050 6.002  90 0.055 6.988
90  0.060 6.206  90 0.065 5.193  90 0.070 5.783
90  0.075 6.482  90 0.080 5.222 100 0.005 5.042
100 0.010 5.551 100 0.015 4.804 100 0.020 5.313
100 0.025 4.957 100 0.030 6.177 100 0.035 5.433
100 0.040 6.139 100 0.045 6.217 100 0.050 6.498
100 0.055 7.037 100 0.060 5.589 100 0.065 5.593
100 0.070 7.438 100 0.075 4.794 100 0.080 3.692
110 0.005 6.005 110 0.010 5.493 110 0.015 5.107
110 0.020 5.511 110 0.025 5.692 110 0.030 5.969
110 0.035 6.244 110 0.040 7.364 110 0.045 6.412
110 0.050 6.928 110 0.055 6.814 110 0.060 8.071
110 0.065 6.038 110 0.070 6.295 110 0.075 4.308
110 0.080 7.020 120 0.005 5.409 120 0.010 7.009
120 0.015 6.160 120 0.020 7.408 120 0.025 7.123
120 0.030 7.009 120 0.035 7.708 120 0.040 5.278
120 0.045 8.111 120 0.050 8.547 120 0.055 8.279
120 0.060 8.736 120 0.065 6.988 120 0.070 6.283
120 0.075 7.367 120 0.080 6.579 130 0.005 7.629
130 0.010 7.171 130 0.015 5.997 130 0.020 6.587
130 0.025 7.335 130 0.030 7.209 130 0.035 8.259
130 0.040 6.530 130 0.045 8.400 130 0.050 7.218
130 0.055 9.167 130 0.060 9.082 130 0.065 7.680
130 0.070 7.139 130 0.075 7.275 130 0.080 7.544
140 0.005 4.860 140 0.010 5.932 140 0.015 3.685
140 0.020 5.581 140 0.025 4.935 140 0.030 5.197
140 0.035 5.559 140 0.040 4.836 140 0.045 5.795
140 0.050 5.524 140 0.055 7.736 140 0.060 5.628
140 0.065 6.644 140 0.070 3.785 140 0.075 4.853
140 0.080 6.006
;
run;

ods graphics on;
ods output ScoreResults=PredLOESS;
proc loess data=ExperimentA;
    model Yield = Temperature Catalyst
                  / scale=sd select=gcv degree=2;
    score;
run;


text:
Q: Get UINavController from subview of UIView? I added a custom subview to a UIViewController's content view. From that subview, how can I get a reference to the superview's controller?
Thanks

A: The correct answer is "You're Doing It Wrong™" ;-)
You shouldn't need to reference to a view controller from a view, and you certainly should never retain a view controller in one of your views -- or you'll end up with a retain loop and leak memory.
Cocoa provides multiple patterns to solve this problem:

*

*Use a delegate: Define a protocol called DemoViewDelegate and add a delegate property to DemoView. Then have your view controller implement this protocol. Important: delegates should never be retained! Any delegate property you create should be set to assign. See Apple's Delegation docs or just google "delegation pattern".

*Use the responder chain: Call UIApplication's sendAction:to:from:forEvent: and leave to: set to nil to have your action message automatically routed up the responder chain to your view controller. See Apple's Responder docs and the more detailed Action Messages docs.

*Use a notification: Less common in this particular scenario, but you could also have your view controller listen for a notification, which the view sends.


text:
Q: Redirecting to homepage htaccess issue I have a strange issue where pages are redirecting to the homepage. Let me explain - my website is thedj.com.au
Now when I type in www.thedj.com.au/payments it redirects to thedj.com.au (even though it should be going to the page https://thedj.com.au/payments).
Any idea why this is and how to fix?
My htaccess file is below:
# BEGIN HTTPS Redirection Plugin
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^home.htm$ https://thedj.com.au/ [R=301,L]
RewriteRule ^photos.htm$ http://photos.thedj.com.au/ [R=301,L]
RewriteRule ^contacts.htm$ https://thedj.com.au/contact-us/ [R=301,L]
RewriteRule ^booking.htm$ https://thedj.com.au/book-dj/ [R=301,L]
RewriteRule ^downloads.htm$ https://thedj.com.au/downloads/ [R=301,L]
RewriteRule ^payonline.htm$ https://thedj.com.au/payments/ [R=301,L]
RewriteRule ^price.htm$ https://thedj.com.au/pricing/ [R=301,L]
RewriteRule ^questions.htm$ https://thedj.com.au/faq/ [R=301,L]
RewriteRule ^links.htm$ https://thedj.com.au/links/ [R=301,L]
RewriteRule ^thankyous/index.htm$ https://thedj.com.au/testimonials/ [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://thedj.com.au/ [L,R=301]
</IfModule>
# END HTTPS Redirection Plugin

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

RewriteCond %{HTTP_HOST} ^mrdj\.net\.au$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mrdj\.net\.au$
RewriteRule ^/?$ "https\:\/\/thedj\.com\.au\/" [R=301,L]

RewriteCond %{HTTP_HOST} ^mrdj\.com\.au$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mrdj\.com\.au$
RewriteRule ^/?$ "https\:\/\/thedj\.com\.au\/" [R=301,L]

RewriteCond %{HTTP_HOST} ^thedjs\.com\.au$ [OR]
RewriteCond %{HTTP_HOST} ^www\.thedjs\.com\.au$
RewriteRule ^/?$ "https\:\/\/thedj\.com\.au\/" [R=301,L]

RewriteCond %{HTTP_HOST} ^theperthweddingdjs\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.theperthweddingdjs\.com$
RewriteRule ^/?$ "https\:\/\/thedj\.com\.au\/" [R=301,L]

RewriteCond %{HTTP_HOST} ^thedjs\.net\.au$ [OR]
RewriteCond %{HTTP_HOST} ^www\.thedjs\.net\.au$
RewriteRule ^/?$ "https\:\/\/thedj\.com\.au" [R=301,L]

Note:
I've tried commenting out the lines
#RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://thedj.com.au/ [L,R=301]

However this has not fixed the issue. I'm thinking this may perhaps be because the website is entirely https:// - but any more ideas would be much appreciated.
Best,
Kosta

A: The .htaccess shouldn't do any redirect here.
For testing, this website could be useful.
Is this configuration from your live site? Because https://thedj.com.au/payments works for me.
Browsers tend to cache permanent redirects quite aggressively. You need to clear the complete cache or use the private browsing mode to test a redirect again. (But you need to close ALL private browsing windows and then open a new one)


text:
Q: How to chunk and stream a file I need to simulate a stream using a file...
This is what I was able to produce so far... the code works, but the streaming does not occur.
I have no experience with streams, so expect to find lot of bugs.
            Stream chunkedStream = new MemoryStream();
            var task = session.AnalyzeAsync(chunkedStream);

            FillStream(chunkedStream);

            while (!task.Wait(500))
            {

                Console.Write("\r" + ((float)chunkedStream.Position / 16000) + " Seconds");

                if (!chunkedStream.CanWrite)
                {
                    break;
                }
            }

        private static async Task FillStream(Stream chunkedStream)
        {
            var stream = Properties.Resources.ResourceManager.GetStream("Sample");
            byte[] chunk = new byte[16000];

            while (true)
            {
                Thread.Sleep(1000);

                int index = 0;
                // There are various different ways of structuring this bit of code.
                // Fundamentally we're trying to keep reading in to our chunk until
                // either we reach the end of the stream, or we've read everything we need.
                while (index < chunk.Length)
                {
                    int bytesRead = stream.Read(chunk, index, chunk.Length - index);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    index += bytesRead;
                }
                if (index != 0) // Our previous chunk may have been the last one
                {
                    // SendChunk(chunk, index); // index is the number of bytes in the chunk
                    chunkedStream.Write(chunk, 0, chunk.Length);
                }
                if (index != chunk.Length) // We didn't read a full chunk: we're done
                {
                    chunkedStream.Close();
                    return;
                }
            }
        }

       public async Task AnalyzeAsync(Stream voiceStream)
        {
            IntervalHandler();
            _StreamTask = UpStreamVoiceData(voiceStream);

            await _StreamTask;
        }

   private async Task<Result<AnalysisResult>> UpStreamVoiceData(Stream voiceStream)
        {
            HttpWebRequest webRequest = WebRequestExtensions.CreateJsonPostRequest(_actions.upStream);

            webRequest.ReadWriteTimeout = 1000000;
            webRequest.Timeout = 10000000;
            webRequest.SendChunked = true;

            webRequest.AllowWriteStreamBuffering = false;
            webRequest.AllowReadStreamBuffering = false;

            using (var requeststream = webRequest.GetRequestStream())
            {

                await voiceStream.CopyStreamWithAutoFlush(requeststream);
                requeststream.Close();
            }

            return webRequest.ReadJsonResponseAs<Result<AnalysisResult>>();
        }


text:
Q: How to refresh treeview on underlying data change I have written a very simple TreeView Extension for Visual Studio Code that displays a basic list of VSCode Tasks and executes the task on selection.
I would like the treeview to auto update when new tasks are added (via the tasks.json file, or autodetected tasks from things like the package.json files scripts) but can't figure out how to do so.
In my activate method I register my TreeDataProvider and execution command:
    vscode.window.registerTreeDataProvider('vscodeTasks', treeProvider);
    let disposable = vscode.commands.registerCommand('task.runTask', task => {
      vscode.tasks.executeTask(task);
    });
    vscode.context.subscriptions.push(disposable);

And in my implementation of the TreeDataProvider in the getChildren function I fetch the tasks using:
vscode.tasks.fetchTasks()

And turn each into a TreeItem
Any help with the auto refresh would be appreciated.

A: I was able to make my treeview reload by adding the following to the implementation
private _onDidChangeTreeData: EventEmitter<
    myItem | undefined
  > = new EventEmitter<myItem | undefined>();

  readonly onDidChangeTreeData: Event<myItem | undefined> = this
    ._onDidChangeTreeData.event;

  refresh(): void {
    this._onDidChangeTreeData.fire(undefined);
  }

And then registering this as a command
commands.registerCommand("******.refresh", () =>
          treeDataProvider.refresh()
        );

By doing this, you can reload your treeview on using the command refresh
I followed the following documents - https://code.visualstudio.com/api/extension-guides/tree-view
Now all you have to do is trigger this command when there is a change in your data, which can be done in different ways
Hope it helps! Happy Coding.


text:
Q: Minimize function / Find α resulting in lowest value for formula I think it's called minimizing a function, but I'm not sure. What I want is to find the value of $\alpha$ so that the result of the formula (the formula on the right side of the equal symbol) will be the lowest value possible.
\begin{align}
V(\alpha) = {} & \alpha^2 x_1 + (1-\alpha)^2 x_2 + 2\alpha(1-\alpha)x_3
\end{align}

I do already know the values of $x_1, x_2$ and $x_3$. These values are fixed. By using statistics software, I was able to calculate both the value of $\alpha$ and the result of the formula when said $\alpha$ is inserted into the formula. However, it would be nice to know how to solve this by hand/formulas.
I have been trying to search around for a while now, and even though there's many examples to find, I'm stuck.
Could anyone point me in the right direction or show me how it's done step by step?
Thank you.

A: Notice that $V(\alpha)$ is quadratic in $\alpha$ - you have an $\alpha^{2}$ term, a $(1-\alpha)^{2}=\alpha^{2}-2\alpha+1$ term, and a $\alpha(1-\alpha)=\alpha-\alpha^{2}$ term. So you can complete the square, then set the squared term to zero. However, this will only give you a minimum if the squared term's coefficient is positive.
You can also solve it via calculus, like DMcMor did. In general calculus is the way to go, but for quadratics completing the square is a nice alternative.
Answer in spoilers:

 $V(\alpha) = (x_{1}+x_{2}-2x_{3})\alpha^{2} - (2x_{2}-2x_{3})\alpha + x_{2} = a(\alpha - b)^{2} + c$ where $a = x_{1}+x_{2}-2x_{3}$, $b = (x_{2}-x_{3})/a$ and $c = x_{2} - ab^{2} = (x_{1}x_{2} - x_{3}^{2})/a$. Only if $a>0$ will you actually get a minimum, in which case you have $\alpha = b$ and $V(\alpha_{min})=c$.

EDIT:
Since OP has stated $\alpha$ is restricted to the interval $[0,1]$ (correct me if the interval is not closed), it might be the case that the minimum obtained by either this method or calculus will lie outside that interval. In this case, one would pick the value that is as close as possible to that minimum - say you got $1.5$, you would choose $\alpha=1$. If you got $-0.5$, you'd pick $\alpha=0$. You can do this because a quadratic is monotonic either side of its turning point. In fact, if you don't find any turning points in the allowed interval, the function must be monotonic if it is continuous, so the minimum in that interval must be one of the two endpoints (and it's usually simple to determine which).

A: Take the derivative:
\begin{align*}
V'(\alpha) &= 2\alpha x_{1} - 2(1-\alpha)x_{2} + 2(1-\alpha)x_{3} -2\alpha x_{3}\\
&=2\alpha x_{1} - 2x_{2} + 2\alpha x_{2} + 2x_{3} - 2\alpha x_{3} - 2\alpha x_{3}\\
&=2\alpha(x_{1}+x_{2}-2x_{3}) -2(x_{2}-x_{3}).
\end{align*}
Set $V' = 0$ and solve for $\alpha$:
$$0 = 2\alpha(x_{1}+x_{2}-2x_{3}) -2(x_{2}-x_{3}).$$
This yields
$$\alpha = \frac{x_{2}-x_{3}}{x_{1}+x_{2}-2x_{3}}.$$
At this point you need to verify that this particular $\alpha$ is in fact a local minimum, and as was pointed out in the comments you need to also check the boundary of whatever set $\alpha$ belongs to.

A: This should be possible as an application of Fermat's theorem, which states that the derivative of a differentiable function is zero at (local) extreme values.  Since $x_1$, $x_2$, and $x_3$ are constant, $V$ is a polynomial in $\alpha$, and so we can differentiate in order to obtain
\begin{align}
V(\alpha)
  &= \alpha^2 x_1 + (1-\alpha)^2x_2 + 2\alpha(1-\alpha)x_3 \\
  &= (x_1 + x_2 -2x_3) \alpha^2 + (-2x_2+2x_3) \alpha + x_2. \\
\implies V'(\alpha) &= 2(x_1+x_2-2x_3) \alpha + 2(x_3 - x_2).
\end{align}
Setting this equal to zero and solving, we get
$$ \alpha = \frac{2(x_2 - x_3)}{2(x_1+x_2-2x_3)} = \frac{x_2 - x_3}{x_1+x_2-2x_3}. $$
Since $V$ is quadratic in $\alpha$, this will be a global minimum if the leading coefficient $x_1+x_2-2x_3 > 0$, and a global maximum if $x_1+x_2-2x_3 < 0$.
In a comment, you specified that you are looking for the minimum on the interval $[0,1]$.  If the leading coefficient is positive, and if $\alpha$ ends up in that interval (i.e. if $0 \le \alpha \le 1$), then you are done---the minimum value of $V$ is achieved at $\alpha$.  However, if the leading coefficient is negative, or if $\alpha$ is not between 0 and 1, then the minimum value of $V$ will be achieved at one of the endpoints.  So, evaluate $V(0)$ and $V(1)$, and take the smallest.
In general, if $f : [a,b] \to \mathbb{R}$ is a differentiable function, the the minimum value of $f$ is found as follows:
(1)  Apply Fermat's Theorem:  First, solve $f'(x) = 0$.  You may get multiple solutions.  Each solution gives you a "critical point."
(2) Evaluate $f$ at each of the critical points, and at the endpoints of the interval (i.e. at $a$ and at $b$).
(3)  The minimum of $f$ will be the smallest value that you found in step (2).


text:
Q: Reducing build time on Webpack by identifying asset modules When I build/serve with Webpack it takes nearly a minute, it's a little too much time, so I enabled the profile flag to see a verbose log. But the result doesn't provide much information that the files are from where, for example.
In the following output, it says data:image/svg+xml,%3csvg xmlns=%27.. or data:image/png;base64,iVBORw0KGgoAAAAN.., so first of all I want to identify the location of the file/code, but I have no idea how/where. (Or rather, actually I doubt I have such image files on my code...)
So is there any way to find the file/code location that Webpack taking time with? Thanks.
$ NODE_ENV=production npx webpack build --config webpack.config.js --profile --progress
asset bundle.js 3.26 MiB [emitted] [minimized] [big] (name: main) 1 related asset
asset fb6f3c230cb846e25247.gif 4.08 KiB [emitted] [immutable] [from: ../node_modules/slick-carousel/slick/ajax-loader.gif] (auxiliary name: main)
asset 2630a3e3eab21c607e21.svg 2.1 KiB [emitted] [immutable] [from: ../node_modules/slick-carousel/slick/fonts/slick.svg] (auxiliary name: main)
asset a4e97f5a2a64f0ab1323.eot 2 KiB [emitted] [immutable] [from: ../node_modules/slick-carousel/slick/fonts/slick.eot] (auxiliary name: main)
asset c94f7671dcc99dce43e2.ttf 1.85 KiB [emitted] [immutable] [from: ../node_modules/slick-carousel/slick/fonts/slick.ttf] (auxiliary name: main)
asset 295183786cd8a1389865.woff 1.35 KiB [emitted] [immutable] [from: ../node_modules/slick-carousel/slick/fonts/slick.woff] (auxiliary name: main)
orphan modules 3.7 MiB [orphan] 282 modules
runtime modules 2.51 KiB 8 modules
cacheable modules 7.69 MiB (javascript) 11.4 KiB (asset)
  modules by path ../node_modules/ 3.89 MiB (javascript) 11.4 KiB (asset)
    javascript modules 3.89 MiB 117 modules
    asset modules 210 bytes (javascript) 11.4 KiB (asset) 5 modules
  modules by mime type image/svg+xml 6.1 KiB
    data:image/svg+xml,%3csvg xmlns=%27.. 324 bytes [built] [code generated]
      668 ms -> 592 ms -> 0 ms -> 1369 ms ->
      4 ms (resolving: 3 ms, restoring: 0 ms, integration: 0 ms, building: 1 ms, storing: 0 ms)
    data:image/svg+xml,%3csvg xmlns=%27.. 216 bytes [built] [code generated]
      668 ms -> 592 ms -> 0 ms -> 1369 ms ->
      0 ms (resolving: 0 ms, restoring: 0 ms, integration: 0 ms, building: 0 ms, storing: 0 ms)
    + 12 modules
  modules by path ./ 3.69 MiB 9 modules
  modules by mime type image/png 102 KiB
    data:image/png;base64,iVBORw0KGgoAAAAN.. 31.3 KiB [built] [code generated]
      668 ms -> 592 ms -> 0 ms -> 1420 ms ->
      2 ms (resolving: 1 ms, restoring: 0 ms, integration: 0 ms, building: 1 ms, storing: 0 ms)
    data:image/png;base64,iVBORw0KGgoAAAAN.. 70.5 KiB [built] [code generated]
      668 ms -> 592 ms -> 0 ms -> 1420 ms ->
      2 ms (resolving: 1 ms, restoring: 0 ms, integration: 0 ms, building: 1 ms, storing: 0 ms)

LOG from webpack.Compilation.ModuleProfile
<i> 2389 ms resolve to new modules
<w>  |  | 619 ms build modules > ./index.js
<w>  | 946 ms build modules > 17 x javascript/auto with ../node_modules/babel-loader/lib/index.js??ruleSet[1].rules[0].use[0]
<w> 2412 ms build modules
+ 105 hidden lines

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  bundle.js (3.26 MiB)

WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  main (3.26 MiB)
      bundle.js

WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

webpack 5.70.0 compiled with 3 warnings in 43210 ms


text:
Q: How to update PostgreSQL full text search field when relational data changes I have the following strategy for the full text search in my web app which uses PostgreSQL for relational data storage. For example I will take Invoices table.

*

*In the tables I have one additional field ALTER TABLE invoices ADD COLUMN tsv tsvector on which the full text search query is done like this ... WHERE tsv @@ to_tsquery('query:*') ...

*On every full text search table I have set an update trigger that updates tsv field on every change of the record. Update sets and concatenates the data from different fields to tsv field, sets the right weights, etc...

*The data that gets set into tsv field can also be relational data from other tables. From example in table invoices I have client_id field but since I want to search invoices by the client name as well I also include clients.client_name data in the invoices.tsv field
My question is what is the best strategy to keep the relational data in tsv selectors in sync. In above scenario -> if client name changes I would need to update this in tsv field for every invoice...
Should I set cron job setup up that would do this every night? It could be also done with triggers, but since my database schema is very large I am scared it might get out of control if I have triggers all over the place.

A: If you add the clients name into the tsv field you will end up with more complexity. You might want to look into Materialized views as mentioned in this article. The trade-off might be speed in showing results and the need to refresh the view periodically. As of Postgres 9.4 you can now refresh a view concurrently.
Another thing you could do is create an update trigger in the Client table and when there's an update it will update the data in the Invoices table as well.


text:
Q: ReactNative android app working very slower, can any one help me to solve? I am working on reactnative android app , and recently my app started to work very slower , i dont know whats happening in background! ,
please help me whether it is related with navigator or someother issues.

A: Check React Native Performance and if you use push on transitions and you think its not really needed just do .replace() instead it helped me alot with the smoothness


text:
Q: Can I use alternatives to manage multiple installs of Java on Ubuntu 20.04? TLDR
On some Linux systems (RedHat/CentOS based), I have found the UNIX alternatives program being used to manage different versions of java.  One of my systems is Ubuntu 20.04, and the alternatives program doesn't exist.
My question is can I use the alternatives program with Ubuntu 20.04?
If so, how do I install it?  I tried installing as shown below and it couldn't be found.
sudo apt install alternatives
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package alternatives

NOTE: a similar name sudo apt install galternatives (a GUI version of alternatives?) did install so I'm looking at that.  It might work well enough.
A related question is
(Q) Can I run the alternatives program on any version of Linux or does it only work with a particular Linux package manager?  Previously, I used it with CentOSs yum install command.
How does Alternatives work?
See this article https://www.redhat.com/sysadmin/alternatives-command.  I'll include examples described in it so this question stands alone (if that link stops working):
After alternatives is installed I should be able to:
(1) Install multiple versions of applications.  As long as each version is installed into a different directories then I can use alternatives.
(2) Configure the alternatives program to know how where different versions of your app are installed.
In this case one is in /opt/em-legacy/em2 and the other is in /usr/local/bin/nem.  I'll give it the name uemacs, and tell alternatives to make it available in /usr/bin/em so I don't need to change my path to run it.

$ sudo alternatives --install /usr/bin/em uemacs /opt/em-legacy/em2 1
$ sudo alternatives --install /usr/bin/em uemacs /usr/local/bin/nem 99

(3) Tell alternatives which version of the app you want to use.  This is done using the alternatives --config command as shown below.
$ sudo alternatives --config uemacs
[sudo] password for seth:

There are 2 programs which provide 'uemacs'.

  Selection    Command
-----------------------------------------------
*+ 1           /usr/local/bin/nem
   2           /opt/em-legacy/em2

There is more to it that is explained in the referenced article.
Background Information for my question
For years, I've managed my Java installs manually and would unzip/untar the Java package and when it needed to be updated repeat the unzip/untar into a new directory and manage symlinks to point to the version I was most predominately using.
Enter cloud... I'm so freakin tired of installing Java manually, I've got to find another (easier) way.   Alternatives seems to be a good solution.

A: On Debian based distro you can use two command lines tools to manage java version:

*

*update-alternatives
Here is my answer on U&L for the usage of update-alternatives.

*update-java-alternatives
The galternatives is the graphical  setup tool for the update-alternatives cli.


text:
Q: why do i get an error when i try to do $make? I'm using devkit pro, trying to create a 3DS Homebrew app. I keep getting an error while doing "$make"
I have this code,
#include <3ds.h>

int main(){
gfxInitDefault();
gfxExit();
return 0;
}

It just says,
\*\*\* missing seperator. stop.

I am trying to make the app go to the home menu when started.
So, basically what happened was, I did $make, and I expected the files to pop out, and I just got the error instead


text:
Q: Cable guides for CAT 5e in the rafters? I've got to pull six or so lines through the rafters of this building.  There's a mess of wire up there, and I'd like to keep these lines separated a bit.
Are there any cable guides that could be quickly nailed or fastened to roof trusses for this sort of thing?  Preferably something that cable can slide through during installation.

A: One easy thing to do would be to just get some 1" or 1.5" flexible plastic conduit and fasten it to the rafters with pipe hangers. This way, you only need to go into the attic once (to install the conduit). All subsequent cable runs can just be fished through the conduit. This type of conduit is readily available at the big box home improvement stores.

A: I don't have enough points to comment yet, but I'd like to add the tip of pulling some fishing lines through the conduits to help pull cables at a later date - in my experience, cables have a tendancy to get caught on the ridges in flexible conduit.
Being able to tie a new cable to some fishing line, then go to the other end of the conduit and pull the cable through is a big time saver.  When you pull a new cable, tie some fishing line to that, so it leaves a new line for the next cable, and so on.

A: You could use cable ties. Tie the wires together every so often. This would be easier than conduit. You can use a second cable tie to tie the first to something such as a nail in the rafters.


text:
Q: Enable GLX extension in Xvfb in Xquartz The version of Xvfb included in Xquartz on MacOS doesn't support GLX:
$ Xvfb +extension GLX
[mi] Extension "GLX" is not recognized
[mi] Only the following extensions can be run-time enabled:
[mi]    Generic Events
[mi]    Composite
 ...

Is it feasible to enable it?  What is involved?
Edited to add:  I tried running Xvfb with the GLX extension on a Linux VM.  It runs fine, but it doesn't actually render the OpenGL graphics.  Perhaps I used the wrong config for the display.  I used
Xvfb :1 -screen 0 1024x768x24 +extension GLX +render -noreset -fbdir temp >xsession.log 2>&1 &

or perhaps Xvfb just doesn't render OpenGL.


text:
Q: To get Id of a particular row in datagrid In the below code I have a datagrid, in which I have 2 columns userid and documentid and a button. I want to get that userid of particular row, how can I do this?
    <asp:DataGrid Width="100%" ID="DocumentUsergrid"
                       PagerStyle-Mode="NumericPages" PageSize="10" PagerStyle-Visible="true"
                            AllowPaging="true" AllowSorting="true"
                        AlternatingRowStyle-CssClass="alt">
                        <AlternatingItemStyle BackColor="White" />
     <asp:TemplateColumn HeaderText="DocumentID" ItemStyle-Width="150px" Visible="false" >
                                 <ItemTemplate>
                                  <asp:Label ID="lblOutputProductID_i"  runat="server"  Text='<%#Eval("DocumentID") %>' > </asp:Label>
                                 </ItemTemplate>
                              </asp:TemplateColumn>

     <asp:TemplateColumn HeaderText="UserID" ItemStyle-Width="150px" Visible="false" >
                                 <ItemTemplate>
                                   <asp:Label ID="lblSupportProductID_i"  runat="server"  Text='<%#Eval("UserID") %>' > </asp:Label>
                                 </ItemTemplate>
                              </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="Insert" ItemStyle-Width="150px">
                                  <ItemTemplate>
                               <asp:Button ID="btnSubmit" runat ="server" OnClick="btnSubmit_Click" />
                               </ItemTemplate>
 </Columns>

                  <HeaderStyle Font-Bold="True" ForeColor="White" />
                   <ItemStyle BackColor="#EFF3FB"/>

                </asp:DataGrid>

protected void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        Dictionary<string, string> OutputProductVal = new Dictionary<string, string>();
        OutputProductVal.Add("UserID", );//To get userid of particular row
        OutputProductVal.Add("DocumentID", ddlDocumentName.SelectedValue.ToString());
        DocumentServiceClient oProduct = new DocumentServiceClient();
        oProduct.InsertUserDocumentMap(OutputProductVal);
    }
}

A: You can find the user id label for the row in the grid view.
foreach(DataGridItem item in DocumentUsergrid.Items)
{
    Label l = item.FindControl("lblSupportProductID_i") as Label;
    string userId = l.Text;
}

A: Use a commandField column like that:
In the ASPX
<asp:CommandField ShowSelectButton="True" />

In the code-behind
Handles the DocumentUsergrid.SelectedIndexChanged event to do what you want.
 protected void DocumentUsergrid_SelectedIndexChanged(object sender, EventArgs e)
 {
 }

In the event code, you can retrieve the data like that:
row = YOUR_GRID.Rows(e.RowIndex);

For more informations about the selectIndexChanged event, see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedindexchanged(v=vs.110).aspx


text:
Q: Multiply methods to property in Swift Greeting, Everyone!
I'm wondering how implement ability to multiply methods associated to certain class
For example I've got custom class of UITextField
and I want to configurate it any way I need.
How can I handle it to get result kinda myTextField.configure().addSomeExtraFeatures().andOneMoreMethod()
like in RxSwift viewModel.fetch().rx.asObservable.bind(to: ...
Can anyone show me some direction to resolving? :) Any clue, please
Even how properly call this process will be useful

A: Return self in every function and use @discardableResult attribute so no need to care about the return.
For more about @discardableResult: https://www.avanderlee.com/swift/discardableresult/
Your UITextField custom class should be like this.
class CustomTextField: UITextField {

    @discardableResult
    func configure() -> Self {
        // Do your code here
        return self
    }

    @discardableResult
    func addSomeExtraFeatures() -> Self {
        // Do your code here
        return self
    }

    @discardableResult
    func andOneMoreMethod() -> Self {
        // Do your code here
        return self
    }
}

Usage:
Create an instance of CustomTextField and call function.
let customTextField: CustomTextField = CustomTextField()

customTextField.configure().addSomeExtraFeatures()


text:
Q: how can I add sub menu to the leaves top menu in odoo10? I want to add menu item to the Leave management top menu and I got error in my XML file that it want external ID.. how can I inherit this top menu to my module?

A: You put your id and menu name here. If you inherit any module name than put their menu id in parent.
<menuitem id="main_menu_id" name="Main Menu Name"/> <!-- Top menu define -->
<menuitem id="sub_menu_id" name="Sub Menu Name" action="your_action" parent="main_menu_id"/> <!-- Child menu define -->


text:
Q: Made successive wix lightbox modal I try to made a terms and condition modal next to my register form on my wix website.
enter image description here
I have two custom dialogs #lightbox1 & #lightbox2. After user clicks REGISTER NOW (#button2) on #lightbox1 another custom popup dialog (#lightbox2) with some text and OK button should be shown. After user clicks ACCEPTER on this popup, the register should be confirmed.
That is the code i added :
$w.onReady(() => {
  $w('#button2').on('click', function () {
   $w("#lightbox2").show();
   });
});

The problem is not recognize #lightbox2 and it throws me error :
"An element with the ID '#lightbox2' does not exist on this page. Select another element and view or edit its ID in the Properties & Events panel."
enter image description here
enter image description here
Then, if a charitable soul wants to help me, I'll welcome him with open arms .

A: Wix only allows one lightbox at a time to function, as an alternative approach you can add Wix Multi-State component inside the lightbox popup and switch the views with the help of code
Wix Velo Tutorial for Multi-State Boxes


text:
Q: Custom Template Controls: .ascx or vbhtml Does anyone have any recommendations about using a .ascx file (user control) versus a .vbhtml/.cshtml (razor) for custom templates?  It would appear from my limited interaction that they are completely interchangeable.
Is it purely a matter of comfort/experience or are there pros and cons to each method?
Thanks

A: Yes, they are interchangeable. But if your main application uses Razor I would recommend you using Razor for those templates. Unless you have some legacy code from some older ASP.NET MVC 2 application that you want to reuse. For all new views I recommend Razor.


text:
Q: Button wont go dark when clicked in chrome extension I have a chrome extension where the button wont get dark when clicked:
var alreadyClicked = false;
var timer;

chrome.browserAction.onClicked.addListener(function (tab) {

        //code for when dobleclicked

        timer = setTimeout(function () {
        chrome.tabs.update({
            url: "http://url.html"
        });

        clearTimeout(timer);

        alreadyClicked = false;
    }, 250);
});

Example of buttons for the translate extension:
normal:   clicked:


text:
Q: Does DM-Crypt partition look like random noise? If I format partition with dm-crypt does its entry in partition table suggest somehow that this partition is encrypted or for someone from outside it looks like regular partition with random noise stored on it? My goal is to encrypt partition and to make in undistinquishable from regular partition that was just formatted or erased by cat /dev/urandom > /dev/sda1.

A: Plain DM-Crypt looks like random, provided you are using a proper cipher. However you will have to remember all encryption settings by yourself.
DM-Crypt/LUKS has a distinct header which remembers the encryption settings for you and manages several pass phrases; however you can also put this header in an external file instead. As long as it's available at boot time and you don't ever lose it...
As a first step you should always scrub the device (shred -n 1 /dev/eraseme or similar) to get rid of old, non-random data.

A: Yes. Look at cryptsetup FAQ section 2.3 paragraph titled What is the difference between "plain" and LUKS format?


text:
Q: Backbone.js destroy not passing model information to server? My model definition:
var Note = Backbone.Model.extend({
    url: '/backbone/notes',

    defaults: function() {
      return {
        id: '',
        text: '',
        date: ''
      };
    },

    initialize: function() {
    },

});

I'm calling destroy on a model thusly:
    delete_note: function(e) {
        this.model.destroy({success: function(model) {
            console.log('success');
        }});
    },

But if I look at the request in firebug it contains no information about the model so I don't know what to delete on the server side. My gets and puts work fine.
This is the model contents:
Object {text: "fdsasdfasdf", date: "Jun 14, 2013", id: 4685293923860480}
Any ideas?

A: The id of your model will be appended to the url when making requests to the server. So the Gets and Puts that are working should be going to:
/backbone/notes/4685293923860480

Delete should be going to the same URL, but should not include no information beyond that. You should have enough information on what to delete by the URL that was hit and the method that was used.


text:
Q: Trouble setting the value of a struct in reflection Let's say I have a base struct that's a composite of two others:
type Config struct {
    common.Config
    common.ServerConfig
    APIPath      string `type:"string" name:"apipath" default:"localhost:8443" desc:"Path to the gRPC API server"`
    ServePath    string `type:"string" name:"servepath" default:"/" desc:"Path to serve the API from"`
    Organization string `type:"string" name:"organization" default:"" desc:"Default organization name"`
}

I'd like to iterate through every field in the struct and pull values into the struct:
func NewConfig(c Configer) {
    setConfigFlags(reflect.TypeOf(c).Elem(), c.GetViper())
}

So I'd call it so:
conf := Config{}
common.NewConfig(&conf)

My setConfigFlags is doing some recursion:
func setConfigFlags(t reflect.Type, viper *viper.Viper) {
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        switch field.Type.Kind() {
        case reflect.Struct:
            setConfigFlags(field.Type, viper)
            continue
        case reflect.String:
            fieldValue := reflect.ValueOf(&field).Elem()
            if !fieldValue.IsValid() || !fieldValue.CanSet() {
                return
            }
            fieldValue.SetString(
                viper.GetString(field.Tag.Get("name")),
            )
        }
    }
}

Now once I hit the SetString line towards the bottom I'm getting this error:
panic: reflect: call of reflect.Value.SetString on struct Value

When I look at the type of fieldValue at that point it's a structfield. I'm having trouble trying to address the value and change the value of the field. I believe I'm not grabbing the address of the actual struct field properly. The examples and documentation surely isn't helping.
In this particular example I'm pulling viper values. Basically looking for a way to define my viper definitions via struct tags, that's the ultimately goal.

A: As comments by mkopriva have noted, the code is attempting to set a value on a type.  Use a value.
func setConfigFlags(v reflect.Value, viper *viper.Viper) {
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        switch field.Type.Kind() {
        case reflect.Struct:
            setConfigFlags(v.Field(i), viper)
            continue
        case reflect.String:
            v.Field(i).SetString(viper.GetString(field.Tag.Get("name")))
        }
    }
}

Call it like this:
func NewConfig(c Configer) {
    setConfigFlags(reflect.Value(c).Elem(), c.GetViper())
}


text:
Q: Swift custom UITableView not showing up in build I'm having a problem in which my custom UITableView will not show up when I build my application.
Currently, I've built what the custom table should look like in my storyboard and also have created a cocoa class that is linked to the UITableViewCell.
This is the ViewController code that deals with retrieving the input form an array and then pasting it onto the table
import UIKit

struct eventStruct
{
    let eventHost : String
    let eventStatus : String
    let eventPrice : String
}

class eventsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var eventArrayData = [eventStruct]()

    override func viewDidLoad() {
        super.viewDidLoad()

        eventArrayData = [eventStruct(eventHost: "Event1", eventStatus: "OPEN", eventPrice: "$5"),
                              eventStruct(eventHost: "Event2", eventStatus: "CLOSED", eventPrice: "$0")]
    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return (eventArrayData.count)
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let eventCell = tableView.dequeueReusableCell(withIdentifier: "eventTemplate", for: indexPath) as! eventsTableViewCell

        eventCell.eventHost.text = eventArrayData[indexPath.row].eventHost
        eventCell.eventPrice.text = eventArrayData[indexPath.row].eventPrice
        eventCell.eventStatus.text = eventArrayData[indexPath.row].eventStatus

        return (eventCell)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Any extra information that is needed and/or help would be really appreciated!

A: You have not connected delegate to your view controller
you can connect your delegate in two ways
1) Using viewDidLoad() function
override func viewDidLoad() {
      super.viewDidLoad()

      yourTableVeiw.delegate = self
      yourTableView.dataSource = self
}

2) Using storyboard
just drag and drop on your view controller
follow below image


text:
Q: ConfirmPrompt won't change yes or no by the localization given I'm trying to change the localization of my bot to change the yes and no response when I use the ConfirmPrompt. I tried to change the localization inside the activity but nothing change and it's just prompt the yes and no as normal.
So here's my code:
private async Task<DialogTurnResult> ConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) {
    var bookingDetails = (BookingDetails)stepContext.Options;
    bookingDetails.TravelDate = (string)stepContext.Result;
    var messageText = $"Please confirm, I have you traveling to: {bookingDetails.Destination} from: {bookingDetails.Origin} on: {bookingDetails.TravelDate}. Is this correct?";
    var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput);
    stepContext.Context.Activity.Locale = "fr-BE";

    return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken);
}

I'm a newbie in Bot and I Don't know how it can be change to work for other language.

A: "fr-BE" isn't fully supported, currently. You can see the supported languages here.
Now, the real reason that locale isn't working in your example is that you're setting it manually with:
stepContext.Context.Activity.Locale = "fr-BE";

...and this doesn't get applied to ConfirmPrompt. Instead, you need the client to set the locale. It's different for every client, but for WebChat, you'd use something like:
window.WebChat.renderWebChat(
    {
        directLine: window.WebChat.createDirectLine({
            token: 'YOUR_DIRECT_LINE_TOKEN'
        }),
        locale: 'fr-FR', // CHANGE ME
    },
    document.getElementById('webchat')
    );

For Emulator, you set the locale in Settings:

Also note that ConfirmPrompt has a DefaultLocale setting that makes it so that if locale is not supplied at all on an activity, it defaults to whatever you set. WebChat and Emulator both will set en-US by default, therefore ConfirmPrompt.DefaultLocale will not work with WebChat/Emulator.


text:
Q: Linux kernel error when trying to install dconf-editor When running the command
sudo apt install dconf-editor

I get the output with an error at the end (something about the kernel?) and dconf-editor never installs:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  linux-image-4.18.0-15-generic
The following NEW packages will be installed:
  dconf-editor
0 upgraded, 1 newly installed, 1 to remove and 20 not upgraded.
2 not fully installed or removed.
Need to get 390 kB of archives.
After this operation, 6,465 kB disk space will be freed.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu bionic/universe amd64 dconf-editor amd64 3.28.0-1 [390 kB]
Fetched 390 kB in 0s (1,104 kB/s)
(Reading database ... 187516 files and directories currently installed.)
Removing linux-image-4.18.0-15-generic (4.18.0-15.16~18.04.1) ...
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.18.0-15-generic
/etc/kernel/postrm.d/zz-update-grub:
Sourcing file `/etc/default/grub'
/usr/sbin/grub-mkconfig: 35: /etc/default/grub: bluetooth.disable_ertm=1: not found
run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 127
dpkg: error processing package linux-image-4.18.0-15-generic (--remove):
 installed linux-image-4.18.0-15-generic package post-removal script subprocess returned error exit status 1
Errors were encountered while processing:
 linux-image-4.18.0-15-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

edit: I see /usr/sbin/grub-mkconfig: 35: /etc/default/grub: bluetooth.disable_ertm=1: not found and remember adding the line to /etc/sysfs.conf when trying to get my Xbox controller connected, but as I'm still learning about Linux, am not sure what this does (all tutorials only say to add the line, without explaining it), or how/if that is affecting dpkg.


text:
Q: Storing value from an html text input in a PHP variable using AJAX I'm trying to obtain the value in an html text input in real time (without submitting a form) and store it in a PHP variable. I'm doing all of this within the same php file (home.php). The script doesn't return any errors. However, when I try to access the value through the global POST array, I get an error that says the index 'query' is undefined.
Any help would be greatly appreciated.

<input name='searchBar' type='text' onChange='getQuery();' size='100' id='query'></input>

<?php
    $x = $_POST['query'];
    echo $x;
?>

A: UPDATED
home.php

<input id="query" name="query" type="text" size="100"></input>

search.php
<?php
$x = $_POST['query'];
echo 'You made it to your search page.  x = ' . $x;
?>


text:
Q: Using MySQL how can I better select all people and their jobs excluding anyone who has a particular job? Here is a link to a fiddle that currently works, it just seems like there is a better way to do this that I am not seeing: http://sqlfiddle.com/#!2/396f2/6
--- Sample schema
CREATE TABLE `jobs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `salary` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `people` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `people_jobs` (
  `pid` int(11) NOT NULL DEFAULT '0',
  `jid` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`pid`,`jid`),
  KEY `jid` (`jid`),
  CONSTRAINT `people_jobs_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `people` (`id`),
  CONSTRAINT `people_jobs_ibfk_2` FOREIGN KEY (`jid`) REFERENCES `jobs` (`id`)
);

And here is the query
SELECT p.name, j.title FROM people p LEFT JOIN
 people_jobs pj ON pj.pid = p.id LEFT JOIN
 jobs j ON j.id = pj.jid WHERE p.id NOT IN
(SELECT p.id FROM people p INNER JOIN
 people_jobs pj ON pj.pid = p.id INNER JOIN
 jobs j ON j.id = pj.jid WHERE j.title = 'Artist');

Is there a way to do this with a LEFT JOIN? That is how I would typically look for things that don't exist in a table. But in this case I am looking for things that don't exist or don't match a particular job. I poked around a lot but could not find any examples of excluding based on not being in a table or matching a particular condition.
I want to get back pairs of people and their associated jobs (or null if they have no jobs) who are not Artists. So if someone has 5 jobs, but one of them is 'Artist' I want to exclude that person entirely from the list.

A: Build the result set you want (people to people_jobs to jobs), then left join to people_jobs a second time, where the person is the same but the job is always "artist".  Filter out the resulting non-null rows, because those are people who have an artist job.
e.g.
SELECT p.name, j.title
FROM people p
LEFT JOIN (
    people_jobs pj
    JOIN jobs j ON j.id = pj.jid
) ON pj.pid = p.id
LEFT JOIN people_jobs artists ON artists.pid = p.id AND artists.jid = 5
WHERE artists.pid IS NULL

This assumes you know (or can get) the job id for an artist ahead of time, and that it's 5.  If not, you can do another nested join or subquery to look up the job by name.

A: I am unsure on how you would be using your query without a nested sub query to exclude artists, but a small optimisation would be to remove the unnecessary join to people in your sub query, I.e.
SELECT p.name, j.title
  FROM people p
  LEFT JOIN people_jobs pj ON pj.pid = p.id
  LEFT JOIN jobs j ON j.id = pj.jid
 WHERE p.id NOT IN
   (SELECT pj.pid
      FROM people_jobs pj
     INNER JOIN jobs j ON j.id = pj.jid
     WHERE j.title = 'Artist')

A: I think you can try this:
select
  p.name, j.title
from
  people as p
  left join people_jobs as pj on p.id = pj.pid
  left join jobs as j on j.id = pj.jid
  left join (
    select
      p.Id
    from
      people as p
      inner join people_jobs pj on p.id = pj.pid
      inner join jobs as j on pj.jid = j.id
    where
      j.title = 'Artist'
  ) as a on p.id = a.id
where
  a.id is null;

You can put the condition in a left joininstead of a wherecondition.
Try the (new) updated SQL Fiddle.
If your tables are large, maybe you can consider creating a temp table and using it instead of the subquery:
drop table if exists temp_condition;
create temporary table temp_condition
    select distinct
      p.Id
    from
      people as p
      inner join people_jobs pj on p.id = pj.pid
      inner join jobs as j on pj.jid = j.id
    where
      j.title = 'Artist';
alter table temp_condition
    add unique index idx_id(Id);
select
  p.name, j.title
from
  people as p
  left join people_jobs as pj on p.id = pj.pid
  left join jobs as j on j.id = pj.jid
  left join temp_condition as a on p.id = a.id
where
  a.id is null;

Hope this helps now


text:
Q: Stop child overflowing parent I have a page with a sidebar. The sidebar content overflows the page, so I've added overflow-y: hidden and max-height: 100vh to main and overflow-y: auto to the list group to make it scroll but that does not work. The overflowing content is cut off but the scroll bar is not there.

main {
  height: 100vh;
  max-height: 100vh;
  overflow-y: hidden;
}

.scrollarea {
  overflow-y: auto;
}

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

          Sign out

Placeholder

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                  Title
                  10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

          main content

How can I make the sidebar scrollable, preferably using Bootstrap classes?

A: Here a sample using flexbox trick with some position property to achieve that, and please do take note that the sample here is not covering the topic of responsive layout in small screen view.

*

*Use flex css to prepare the layout structure (header, sidebar, main content)

*Then use position on the scrollable area: an absolute box within a relative container

Hope it helps and Happy coding!

main {
  height: 100vh;
}

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

          Sign out

Placeholder

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

                      Title
                      10

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsa velit necessitatibus eveniet blanditiis eum maxime odio autem labore omnis repudiandae cumque explicabo nisi suscipit iste rem, a sapiente voluptas incidunt?

          main content


text:
Q: Is there a Twitter client for Mac that doesn't need a user+password login (uses OAuth)? Are there any Twitter client for Mac that don't need a user+password login (but uses OAuth instead)?

A: Adium 1.4, just updated over the weekend, is an open-source multi-protocol native OS X chat client that now supports Twitter using OAuth. I've never been a fan of AIR apps, and use Adium already, so this was a natural. Your timeline can be updated at an interval you select .


text:
Q: git removes server generated files in tracked directory Let's assume this basic project:
├── css
│   ├── custom.css
│   └── main.css
└── index.html

In the root of this directory the following commands are run:
git init
git add -A :/
git commit -m "initial commit"
git push ssh://username@servername:path/to/www master

This deploys the first commit to the server so it has the same directory structure. The file custom.css is intended for someone with access to the server (via ftp) to be able to edit as they need to. So I need it set up so whenever a push is made that the custom.css file isn't overwritten by the version on my local. So I run the following commands:
echo css/custom.css >> .gitignore
git rm --cached css/custom.css
git commit -am "removed custom.css from being tracked"
git push ssh://username@servername:path/to/www master

However this just removes the custom.css file from it's location rather than leaving it untouched. How can I set it up so when pushing git doesn't overwrite or remove custom.css without having to configure anything serverside? I'm hoping for a solution that involves configuring the local git repo. Thanks!

A: .gitignore is a global method of ignoring a file, which means it won't be tracked at all.  If you need to ignore files locally, but you do not want the repository to ignore the file, you should commit the custom.css file then create a local explicit repository exclude by using a .git/info/exclude as described in the git documentation.
That said, I think the best practice would be to set up a watcher on the server (for example a grunt worker or a cron job running at regular intervals) to watch for changes to the files on the server and commit them as they are made, since this will provide you with proper version control over the custom.css file and allow rollbacks if necessary. (Depending on your particular situation, this may be overkill, in which case, just go with the explicit exclude.)
If you decide to go that route, you should probably maintain the git repository in a separate directory from the production site.  Configure a grunt worker to watch the production site, so when the FTP user makes changes it will trigger a commit to the repository. One way you could accomplish this would be by using grunt-git-commit in combination with grunt-git-deploy being triggered by a grunt-contrib-watch task.


text:
Q: How to send email from a non-gmail account in R I am developing an application in R and it needs to send the email to specific people in the organization.
sender <- "xxxx.yyyy@gmail.com"
recipients <- c("yyyy.xxxx@zzz.com")
send.mail(from = sender,
          to = recipients,
          subject = "Test mail from Rstudio",
          body = "Test email body",
          smtp = list(host.name = "smtp.gmail.com", port = 465,
                      user.name = "xxxx.yyyy@gmail.com",
                      passwd = "******", ssl = TRUE),
          authenticate = TRUE,
          send = TRUE)

This code works well when the sender sends a mail from gmail account. What can be done to send a email from a non gmail account (Organization email account)? Is it possible?
Thanks in advance...

A: if your app runs in a linux box, and the mail subsystem is properly configured:
system("echo 'test body' | mail -s 'test subject' -r sender_addr@foo.com dest_addr@bar.com")


text:
Q: REST API design: the endpoint which returns a report I need to create an endpoint which return some form of a report. Something like:
api-v1/report?format=XML. And it report with custom XML-report.
What should I do in case xsl?
api-v1/report?format=XSL is it normal to answer on such request with XSL(Excel) file?

A: the resource (data) should be independent from the formatting/encoding
whether it is xml, json, xls, csv, etc should be determined through "content negotiation" usually accomplished by using the "accept" header.

A: One solution is to respond with the URL of where the file can be downloaded from, instead of sending the contents of the file.


text:
Q: How do you set the initial state of a checkbox in WPF (either in XAML or code)? I have two simple related controls on a form, a delete button and a confirm delete checkbox.
The idea is to protect against accidental deletions (don't worry, undo will be added later) but still allow the user to delete without annoying confirmations if they so wish.
However, I want the initial state of the checkbox to be set. The XAML code is currently:
<CheckBox Margin="0 5 0 0"
          x:Name="chkConfirmDel"
          Checked="chkConfirmDel_Change">
    Confirm delete?
</CheckBox>

but I can't see any obvious property for forcing the initial state, either in XAML or in the Window_Loaded() code.

A: XAML:
<!-- Initialized checked -->
<CheckBox x:Name="cbxSwitch" IsChecked="True" Content="Simple switch" />

<!-- Initialized in third state -->
<CheckBox x:Name="cbxSwitch3" Content="3 state switch"
    IsThreeState="True" IsChecked="{x:Null}" />

CS:
// Two-state CheckBox doesn't require checking null
if (cbxSwitch.IsChecked == true)
{
    // Do something if selected
}

// In three-state CheckBox, IsChecked may be true, false or null
if (cbxSwitch3.IsChecked ?? false)
{
    // Do something only if IsChecked==true (selected)
}

A: IsChecked="True"


text:
Q: Ruby method refactor multi line assignment to pass RuboCop I have been trying to tune this method that sets up complex assignment and I am looking for other options to make this function pass the cops.
Would anyone have thoughts to point me in the right direction?
Right now, I am tinkering with breaking out the two inner .map calls.
Failing Cops
Assignment Branch Condition size for parse_items is too high. [24.08/15]
  def parse_items
Avoid multi-line chains of blocks.
    end.compact.map do |opt|

The problem code
  def parse_items
    options = parse_relationships
    options = options.select { |opt| opt['type'] == 'product_options' }
    options.map do |opt|
      parse_included.detect { |x| x['id'] == opt['id'] }
    end.compact.map do |opt|
      {
        group_id: @payload['id'],
        originator_id: opt['id'],
        price: opt['attributes']['price'],
        description: opt['attributes']['name'],
        exp_quantity: opt['attributes']['quantity'].to_i,
        title: parse_attributes['name'],
        image_originator_url: 'image_for_product',
        updated_at: timestamp
      }
    end
  end

Helper Methods
  private

  def parse_data
    @payload['data']
  rescue
    []
  end

  def parse_included
    @payload['included']
  rescue
    []
  end

  def parse_attributes
    @payload['data']['attributes']
  rescue
    []
  end

  def parse_relationships
    @payload['data']['relationships']['options']['data']
  rescue
    []
  end

  def timestamp
    Time.parse(parse_attributes['updated_at'])
  end

Updated Errors
In the spec: wrong number of arguments (given 2, expected 1) for Failure/Error: SELECT = ->(opt) { opt['type'] == 'product_options' }
Assignment Branch Condition size for parse_items is too high. [17/15]
Updated Code
  SELECT = ->(opt) { opt['type'] == 'product_options' }
  MAP = ->(opt) { parse_included.detect { |x| x['id'] == opt['id'] } }
  def parse_items
    parse_relationships.select(&SELECT).map(&MAP).compact.map do |opt|
      {
        group_id: @payload['id'],
        originator_id: opt['id'],
        price: opt['attributes']['price'],
        description: opt['attributes']['name'],
        exp_quantity: opt['attributes']['quantity'].to_i,
        title: parse_attributes['name'],
        image_originator_url: 'image_for_product',
        updated_at: timestamp
      }
    end
  end

A: I was able to refactor this making it far cleaner and pass all the cops! Hooray!
  def parse_items
    assign_item_attributes(select_included_option(select_item_options(parse_relationships['options']['data'])))
  end

  def select_included_option(options)
    options.map do |opt|
      parse_included.detect { |x| x['id'] == opt['id'] }
    end
  end

  def assign_item_attributes(options)
    options.compact.map do |opt|
      {
        group_id: @payload['id'],
        originator_id: opt['id'],
        price: opt['attributes']['price'],
        description: opt['attributes']['name'],
        exp_quantity: opt['attributes']['quantity'].to_i,
        title: parse_attributes['name'],
        image_originator_url: parse_image,
        updated_at: parse_timestamp
      }
    end
  end

  def select_item_options(options)
    options.select { |opt| opt['type'] == 'product_options' }
  end


text:
Q: Local alarm for a foreground service? I have a foreground service and while it's active I want to run some events based on specific exact time that you a user previously set, it can be one time or it can repetitive every day for example.
I don't want to use AlarmManager because it triggers system events and you need some permissions for it, I have a running service anyway so why would I  use something like this... So it should lifescoped to the service
I don't want to use Handler and its func postDelayed or launch and delay of Coroutines because it's like inventing a wheel, especially when you need to implement logic for repeatable events for a specific time.
So I'm looking something as local broadcast messages but with time configuration like in alarm and I could use set date/time instead of millis delay logic

A: I might need some more clarifying details to give better advice, but the following should give you an idea of the possible options and their pros and cons.
As much as AlarmManager might seem like a pain, it is probably your best bet for something like this, especially if the events are spread out over a longer period as the question hints (e.g. once a day). The alternative would be to use something like Handler, Coroutines, or a TimerTask inside the service. In addition to introducing the complexities of managing repeating events (as you mentioned), all of these require that the service is constantly running and presumably doing nothing other than waiting to fire an event, which is wasteful and likely not precise over a long period of time. Further, the service could be killed by the system and then you'd have to recreate all the timing logic, whereas AlarmManager scheduling is more persistent.
If your foreground service really is active doing other things for the entire duration in which you want these events to fire, or if the requirement is that the events fire if and only if the service is already active, then these options could be back on the table, but I'm not sure without more information.
If exactness is not an issue, you could potentially use OneTimeWorkRequest or PeriodicWorkRequest; see this documentation.
If your main concern with AlarmManager is using date/time scheduling instead of milliseconds, that shouldn't be an issue as most temporal classes provide easy ways to convert to milliseconds.
Overall, because of the inherit difficulty of precise scheduling, a system-based implementation like AlarmManager is best if exactness is the goal, and other options will incur an unnecessary waste of resources.


text:
Q: How to exclude a hidden MacOS folder like Library/Spotify from Time Machine? After figuring out that Time Machine always commits a lot of stuff whenever I use Spotify (using sudo tmutil compare "path1" "path2" ), I wanted to remove Spotify from being backed up. In the time machine options, it is easy to add folders to be ignored. So I added Spotify from the application folder. However, I wanted to ignore also
/Users/***/Library/Application Support/Spotify/PersistentCache

for every user, but was not able to do so. The problem is that Library does not show up in the final dialog, being sort of a hidden folder.
Any hints to solve this?

A: Use this shortcut when the dialog opens.
CMD + Shift + .


text:
Q: parent table with multiple child insertion using hibernate i've created an application which uses hibernate inheritance and mapping.
There is a parent class named Payment and Child class called Credit.
Right i'm trying to insert multiple child values for one single parent id.
Like as shown below
|``````````````|
|    Payment   |
|--------------|
| id  |  nane  |
|-----|--------|
|  1  |  mod 1 |
|-----|--------|
|  2  |  mod 2 |
|-----|--------|

|````````````````````````````````|
|              Credit            |
|--------------------------------|
| id  |  payid | type  |  mode   |
|-----|--------|-------|---------|
|  1  |   1    |   1   |   m1    |
|-----|--------|-------|---------|
|  2  |   1    |   4   |   m6    |
|-----|--------|-------|---------|
|  3  |   1    |   5   |   m5    |
|-----|--------|-------|---------|
|  4  |   1    |   1   |   m7    |
|-----|--------|-------|---------|

My code is as given below (For mapping and other details you can check THIS)
Payment tabletcstatus=new Payment();
    tabletcstatus.setName("name 123");
    session.save(tabletcstatus);

    Credit c=new Credit();
    c.setMode("mode 1");
    c.setPayid(tabletcstatus);
    session.save(c);

    Credit c1=new Credit();
    c1.setMode("mode 2");
    c1.setPayid(tabletcstatus);
    session.save(c1);

But when i execute i'm getting the following executed
Hibernate: insert into hhh.payment (name) values (?)
Hibernate: insert into hhh.payment (name) values (?)
Hibernate: insert into credit (type, mode, payid) values (?, ?, ?)
Hibernate: insert into hhh.payment (name) values (?)
Hibernate: insert into credit (type, mode, payid) values (?, ?, ?)

here payment is inserted thrice and the two credit has different payid
can anyone please tell me some solution for this.

A: Well your mapping is somewhat 'exotic' in that you have Credit extends Payment and Payment also has a collection of credits. Not something I have come across but I guess, if this is really what you want, then it should work.
Regarding the first issue, how many entries would you expect in payments? You create three 'payments' 1 x Payment and 2 x Credits and are using a Joined Table strategy so 3 insertions is exactly right.


text:
Q: Debugging Test Environment w/ IdentityServer4 We are in the process of setting up IdentityServer4. Our dev environment is working but it is not clear how this will work in other environments (Test/UAT/Production/etc).
The dev instance is able to work because we are fine with putting localhost resources (clients/apis) in the database. This allows us to have an Angular app with an implicit flow that redirects to http://ourdevserver.com (as an example) and get a token that we can then use with either dev apis or local apis/clients that are being debugged on localhost.
Once we start moving to other non-dev environments, we do not want to have localhost resources in the database (for obvious reasons). Does this mean that we will not be able to debug any environment outside of our dev server? It seems like it would be valuable to debug a client against a production resource under certain conditions but I am not sure how to achieve this in a way that doesn't compromise security.


text:
Q: Nodemon execute different scripts based on the changed file name I am trying to make Nodemon run two different commands depending on which file changed. I tried using nodemon.json and invoking it using nodemon nodemon.json (because it didn't seem to be getting picked up just by nodemon):
{
  "watch": "nodemon.json,main.js,index.js",
  "execMap": {
    "main.js": "electron .",
    "index.js": "echo todo",
    "nodemon.json": "echo Nodemon config reloaded"
  }
}

Nodemon doesn't pick up any changes with this setup. I think I might have a problem in the watch glob. When I remove it (so it watches everything I think by default), then file changes are getting picked up, but Nodemon only ever executes node index.js. I never speficied that anywhere so I assume that's the default and the execMap is not being honored? Is it only for extensions?
I am not sure how to craft a config which takes these two different paths. Is it even possible with Nodemon?

A: The execMap property seems to be intended to support non-default file extensions.
According to the docs

...you can define your own default executables using the execMap
property. This is particularly useful if you're working with a
language that isn't supported by default by nodemon

One thing you can do is run multiple nodemon processes, one for each file/directory, from a script, like:
nodemon -w "path1/" -x "<command 1>" &
nodemon -w "path2/" -x "<command 2>"


text:
Q: p:commandButton action not invoked after and ajax update I have a JSF page which has a p:commandButton which has ajax=true and renders a p:panel which is wrapped in p:outputPanel when clicked. When this button is clicked the action method will set showCreateUser value in ManagedBean to true and this is used to render the Panel. This works fine - on button click the panel is rendered properly. Inside the p:panel there is another p:commandButton. This commanButton is not working as nothing happens when I click on it. The action method is never invoked. When I debug I realised that even though the ajax action sets showCreateUser to true but when I click on second button the showCreateUser value is false. So, the panel panel rendered=false and so the action is never invoked. Following are the xhtml and managedbean class. How can I resolve this? Thanks for your help!
registration.xhtml
<h:form id="userForm" style="background-color:white;border:0px; width:90%;">
   <p:messages id="messagesForDebugging"
               showDetail="true"
               autoUpdate="true" />
   <ui:debug hotkey="x"/>
   <div style="margin-bottom: 10px;">
       <p:commandButton id="btnConfirmYes" value="Yes" ajax="true" update="userRegOutPanel"
               action="#{regBean.confirmYes}" styleClass="button" style="height:35px;">
        <!-- <f:ajax render="userRegOutPanel" execute="userRegOutPanel"/> -->
       </p:commandButton>

       <p:commandButton id="btnConfirmNo" value="No" ajax="false"
             action="#{regBean.confirmNo}" styleClass="button" style="height:35px;"/>
   </div>

   <p:outputPanel id="userRegOutPanel">
        <p:panel id="userRegPanel" rendered="#{regBean.showCreateUser}">
            <p:panelGrid id="userRegPanelGrid">
                <p:row>
                   <p:column style="width:40%;background-color:#00a5b6;-moz-border-radius: 10px;-webkit-border-radius: 10px;-khtml-border-radius: 10px;border-radius: 10px;text-align:left;">

                      <h:inputHidden id="ssn" value="#{regBean.ssn}"/>

                      <p:panelGrid>
                          <p:row>
                              <p:column>
                                  <p:commandButton value="Submit" ajax="true" action="#{regBean.submitRegistration}"
                                           styleClass="button" style="width:140px;height:35px;" type="submit"/>
                              </p:column>
                          </p:row>
                      </p:panelGrid>
                   </p:column>
                </p:row>
            </p:panelGrid>
        </p:panel>
   </p:outputPanel>
</h:form>

Managed Bean
    @ManagedBean
        @ViewScoped
        public class RegBean implements Serializable{

    private static final long serialVersionUID = 1L;
    static Logger log = LoggerFactory.getLogger(RegBean.class);

    private String ssn;

    private boolean showCreateUser = false;

    public void confirmYes(){
        setShowCreateUser(true);
    }

    public String confirmNo(){
        log.info("In retrieveRegistration");
        FacesContext fc = FacesContext.getCurrentInstance();
        fc.addMessage("registrationError", new FacesMessage(
                FacesMessage.SEVERITY_ERROR,
                "Error. Contact customer service",
                "Error. Contact customer service"));
        return "/registration/registrationError";
    }

    public String submitRegistration() {
        log.info("In submitRegistration");
        FacesContext fc = FacesContext.getCurrentInstance();

        return "/secured/home";
    }

    public String getSsn() {
        return ssn;
    }
    public void setSsn(String ssn) {
        this.ssn = ssn;
    }

    public boolean isShowCreateUser() {
        return showCreateUser;
    }

    public void setShowCreateUser(boolean showCreateUser) {
        this.showCreateUser = showCreateUser;
    }
}

A: <p:commandButton id="btnConfirmNo" value="No" ajax="false"
action="#{regBean.ConfirmNo}"
styleClass="button" style="height:35px;"/>

In above code ,you've set action to be "ConfirmNo". I don't see any method as such.
Change above code as :
<p:commandButton id="btnConfirmNo" value="No" ajax="false"
action="#{regBean.agentConfirmNo}"
styleClass="button" style="height:35px;"/>

Now, it will invoke the method agentConfirmNo from your registration bean.
I hope that helps.


text:
Q: How Can I Access the WiFiManager Framework iOS? I am trying to access the WiFiManager Framework (previously apple80211) and can't find the right information. I understand Apple doesn't allow the use of private frameworks for apps on the app store but I am writing this app for personal use so this is of no concern to me. What I need to know is can I still access the WiFiManager Framework for an app I upload directly to my phone and is there any information out there on how to? Thanks in advance for ANY help.

A: See my answer here.
//IN YOUR APP
notify_post("com.yourcompany.yourapp.yournotification");

//IN YOUR DYLIB

#import <SpringBoard/SBWiFiManager.h>

HOOK(SpringBoard, applicationDidFinishLaunching$, void, id app) {
    //Listen for events via DARWIN NOTIFICATION CENTER
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL,
     &NotificationReceivedCallback, CFSTR("com.yourcompany.yourapp.yournotification"), NULL,
      CFNotificationSuspensionBehaviorCoalesce);
}

//THIS IS WHERE THE MAGIC HAPPENS
static void NotificationReceivedCallback(CFNotificationCenterRef center,
                                            void *observer, CFStringRef name,
                                            const void *object, CFDictionaryRef
                                            userInfo)
{
    [[objc_getClass("SBWiFiManager") sharedInstance] setWiFiEnabled:NO];
}


text:
Q: Cron Job - Command to delete all .flv files everyday I have this command that I run everyday via cron:
find /home/get/public_html/videos -daystart -maxdepth 0
-mtime +1 -type f -name "*.flv" |xargs rm -f

The problem is that it doesn't delete the .flv files in a directory that are  1 or more days old.
How can I correct the above command?
EDIT: Paul - the command "ls -l /home/get/public_html/videos" results in 2000+ files but here is 2 of them that should be deleted:
-rw-r--r--  1 get get   3501188 Jan  4 15:24 f486cf0a2b6bb40e4c50c991785084131231104229.flv
-rw-r--r--  1 get get  10657314 Jan  4 17:51 f5f1490ddaa11a663686f9d06fb37d981231112941.flv

A: It's better to use -print0 on find and -0 in xargs in case one file has an uncommon name.
Also, you want to use -maxdepth 1 to actually find something in the specified directory.
-maxdepth 0 means it'll only find in the directories listed in the command line, it won't check the contents of those directories.

A: Do you mean, if you have a directory /home/get/public_html/videos/foo it doesn't delete the files in them? That would be because you have the -maxdepth 0 argument set, which prevents find from descending into subdirectories.

A: -maxdepth 1


text:
Q: How to read file that has been downloaded on selenium grid for protractor e2e tests? Here is my capabilities settings :
capabilities: {

    browserName: 'chrome',

    chromeOptions: {
        args: ['--no-sandbox'],
        prefs: {
            'download': {
                prompt_for_download: false,
                directory_upgrade: true,
                default_directory: process.cwd()
            }
        }
    }
}

and it fails when I am trying to read this file
also I tried adding '/temp to the default directory please advise


text:
Q: Конвертация изображения в код Здраствуйте ,пишу программу для конвертации 3d моделей в код для постройки mc (библиотека майнкрафта основанная на python).Для удобства разбиваю 3d модель в изображение

Всё что белое нужно переводить в код , черное пропускается .
Т.к. это 3d модель таких изображений может быть от 10 до 150 штук +- (количество уровней)
В чем заключается проблема: Мне нужно найти оптимальный способ строить через библиотеку mc .Там есть прекрасная функция setCuboid , функция принимает 6 параметров (7 , но в данном случае он не важен) x,y,z и x1,y1,z1 .  x,y,z начальные координаты , x1,y1,z1 конечные .
Строительство по слайсам ,занимает очень много времени . Как я это делал брал точку (1) и искал ей конец вдоль какой либо координаты (2), заполнял ,получалось что-то вроде этого setCuboid(0,0,0,10,0,0). Но это достаточно медленный процесс, особенно когда таких "слайсов" около 150 штук.

СУТЬ
Нужно построить за минимальное время . Для этого я сохранял всё изображения в массив[номер_изображения(он же "y")][x][z]. После пробовал найти быстрый способ через перебор, как это работает у меня. if allpoints[y][x][z] == "1": программа находит пиксель белого цвета,далее добавляет значение 1 к каждой координате и если они тоже белые добавляет ещё и т.д.
for plus in range(300):
`if allpoint[y+plus][x+plus][y+plus] == "1":`

eсли значение равно 0 программа сохраняет в файл такой вывод: setCuboid(x,y,z,x+plus,y+plus,z+plus)
но даже если строить таким способом одиночные пиксели увеличивают количество строк или вовсе пропускают блоки(пиксели)

A: Используйте библиотеки PIL и numpy:
from PIL import Image
import numpy as np

img = Image.open("WGadg.png") # имя вашего файла со слайсом
img.load()
slc = np.asarray(img.convert('1'), dtype="int32" )

теперь у вас в slc двумерный массив numpy со значением 0, если точка черная (пустая) и 1, если точка белая. соответственно, к каждой точке можно обратиться по индексу:
print(slc[0][0])
print(slc[10][10])

0
1