text:
Q: ServiceStack MQ: how to populate data in RequestContext I'm developing a JWT-based multi-tenancy system using ServiceStack. The JWT token contains shard information, and I use JwtAuthProvider to translate the JWT token to session object following instructions at http://docs.servicestack.net/jwt-authprovider.
Now, I want to use ServiceStack MQ for asynchronous processing. The MQ request needs to be aware of the shard information, so I populate the request context before executing it as follow
mqServer.RegisterHandler<EmployeeAssignedToProject>(m =>
            {
                var req = new BasicRequest { Verb = HttpMethods.Post };
                var sessionKey = SessionFeature.GetSessionKey(m.GetBody().SessionId);
                var session = HostContext.TryResolve<ICacheClient>().Get<Context>(sessionKey);
                req.Items[Keywords.Session] = session;
                var response = ExecuteMessage(m, req);
                return response;
            });

Here, Context is my custom session class. This technique is stemmed from the instruction at http://docs.servicestack.net/messaging#authenticated-requests-via-mq. Since I execute the message within the context of req, I reckon that I should then be able to resolve Context as follow
container.AddScoped<Context>(c =>
        {
            var webRequest = HostContext.TryGetCurrentRequest();
            if (webRequest != null)
            {
                return webRequest.SessionAs<Context>();
            } else
            {
                return HostContext.RequestContext.Items[Keywords.Session] as Context;
            }
        });

However, HostContext.RequestContext.Items is always empty. So the question is, how to populate HostContext.RequestContext.Items from within message handler registration code?
I've tried to dig a little bit into ServiceStack code and found that the ExecuteMessage(IMessage dto, IRequest req) in ServiceController doesn't seem to populate data in RequestContext. For my case, it is a bit too late to get session inside service instance, as a service instance depends on some DB connections whose shard info is kept in session.

A: The same Request Context instance can't be resolved from the IOC. The Request Context instance is created in the MQ's RegisterHandler<T>() where you can add custom data in the IRequest.Items property, e.g:
mqServer.RegisterHandler<EmployeeAssignedToProject>(m =>
{
    var req = new BasicRequest { Verb = HttpMethods.Post };
    req.Items[MyKey] = MyValue; //Inject custom per-request data
    //...
    var response = ExecuteMessage(m, req);
    return response;
});

This IRequest instance is available throughout the Request pipeline and from base.Request in your Services. It's not available from your IOC registrations so you will need to pass it in as an argument when calling your dependency, e.g:
public class MyServices : Service
{
    public IDependency MyDep { get; set; }

    public object Any(MyRequest request) => MyDep.Method(base.Request, request.Id);
}


text:
Q: order by from 2 column from different tables I am trying to pull all the items for sales on a POS system.
I have a few tables I need to join and order/group by. I hope I can get this explained.
Table `items`:
+---------+--------+
| item_id |  Name  |
+---------+--------+
|    33   | Thing1 |
|    34   | Thing2 |
|    54   | Thing3 |
|    67   | Thing4 |
+---------+--------+

Table `kits`:
+-------------+------+
| item_kit_id | Name |
+-------------+------+
|      1      | Kit1 |
|      2      | Kit2 |
+-------------+------+

Table `sales`:
+---------+-------------+---------+
| sale_id | sale_date   |  Total  |
+---------+-------------+---------+
|       1 |  2016-06-11 | 100.00  |
|       2 |  2016-06-12 | 145.00  |
+---------+-------------+---------+

Table `sale_items`:
+-----+---------+----------+---------+
| id  | sale_id | line_num | Item_id |
+-----+---------+----------+---------+
|  1  |     1   |    1     |    33   |
|  2  |     1   |    3     |    54   |
|  3  |     2   |    1     |    34   |
|  4  |     2   |    2     |    67   |
+-----+---------+----------+---------+

Table `sale_kit_items`:
+-----+---------+----------+-------------+
| id  | sale_id | line_num | item_kit_id |
+-----+---------+----------+-------------+
|  1  |     1   |    2     |       1     |
|  2  |     2   |    3     |       2     |
+-----+---------+----------+-------------+

I want to results to look like
Results:
+---------+----------+---------+-------------+
| sale_id | line_num | item_id | item_kit_id |
+---------+----------+---------+-------------+
|    1    |     1    |    33   |     null    |
|    1    |     2    |   null  |       1     |
|    1    |     3    |    54   |     null    |
|    2    |     1    |    54   |     null    |
|    2    |     2    |    67   |     null    |
|    2    |     3    |  null   |       2     |
+---------+----------+---------+-------------+

or even better if I could get:
Results:
+---------+----------+---------+-------------+--------+
| sale_id | line_num | item_id | item_kit_id |  name  |
+---------+----------+---------+-------------+--------+
|    1    |     1    |    33   |     null    | Thing1 |
|    1    |     2    |   null  |       1     |  Kit1  |
|    1    |     3    |    54   |     null    | Thing2 |
|    2    |     1    |    54   |     null    | Thing3 |
|    2    |     2    |    67   |     null    | Thing4 |
|    2    |     3    |  null   |       2     |  Kit2  |
+---------+----------+---------+-------------+--------+

A: Took me sometime to understand your scenario...
EDIT
Perhaps you should change the LEFT JOINs with items and sale_kit_items to INNER JOINs (I expect that the IDs will be found in the respective tables).
select s.sale_id, si.line_num, si.item_id, null as item_kit_id, i.name
from sales s
left join sale_items si on s.sale_id = si.sale_id
left join items i on si.item_id = i.item_id
union all
select s.sale_id, ski.line_num, null as item_id, ski.item_kit_id, k.name
from sales s
left join sale_kit_items ski on s.sale_id = ski.sale_id
left join kits k on ski.item_kit_id = k.item_kit_id
order by 1, 2
;

A live demo can be found here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: php mysql retrieving single value from database Hey guys this is a really noob question but for some reason I can't seem to get a single value from a database.
Here is the code that I'm using:
$stmt = $pdo->prepare("SELECT column FROM teacher WHERE id = :id")
$stmt->bindParam(':id', $id);
$stmt->execute();

$oldValue = $stmt->fetchColumn();

I do filter the variables before in the code because I got them in this file as post data, here's the code for that part:
$column = filter_input(INPUT_POST, "column", FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_STRING);
$value = filter_input(INPUT_POST, "value", FILTER_SANITIZE_STRING);

In this same file updating the database works so its probably not a problem with connecting to the database. Please help! Thanks
Full error from $stmt:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'column FROM teacher WHERE id = ?' at line 1' in /var/www/duties/testTableDataUpload.php:25Stack trace:#0 /var/www/duties/testTableDataUpload.php(25): PDO->prepare('SELECT column F...')#1 {main}  thrown in /var/www/duties/testTableDataUpload.php on line 25

A: I know this is not an answer, just trying to post code to OP.
jquery:
var data="id="+id;
        $.ajax({
            type:"POST",
            data: data,
            url:"somePHPdbPage.php",
            success: function(result){
            $('#blah').html(result);
            }
    });

Then somewhere on your main page do:

what this will do is add the result to the div blah. and you should plainly see it on your main page. then c/p all you want.  Have to head out for a bit.  will check back in.
and on your php page:
$stmt = $pdo->prepare("SELECT column FROM teacher WHERE id = :id")
$stmt->bindParam(':id', $id);
$stmt->execute();
print_r($stmt->errorInfo());

A: column is a reserved word in MySQL and must be escaped using '`'. You are also missing a semicolon at the end of the line. Try the following:
$stmt = $pdo->prepare("SELECT `column` FROM teacher WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();

$oldValue = $stmt->fetch();

A: maybe the problem be with your data but if there be duplicated data you can use one of the belows:
$stmt = $pdo->prepare("SELECT distinct column FROM teacher WHERE id = :id")

or
$stmt = $pdo->prepare("SELECT column FROM teacher WHERE id = :id limit 1")

A: If you have a column in the teach tabled named 'first_name' you should be able to do the following

$stmt = $pdo->prepare("SELECT first_name FROM teacher WHERE id = :id ORDER BY id DESC limit 1")
$stmt->bindParam(':id', $id);
$stmt->execute();

$row = $stmt->fetch(PDO:FETCH_ASSOC);
echo $row['first_name']; //Will print out the first name (if that is a column in your table of course)


text:
Q: Convert Long to String Python @staticmethod
def next_group_id():
    cursor = connections['ips4'].cursor()
    cursor.execute(Ips4Manager.SQL_GET_ALL_GROUP_IDS)
    row = cursor.fetchall()
    if row is not None:
        string_num = str(row)
        max_number = max(string_num)
        print max_number
    else:
        logger.debug("cannot determine next group id")
        return False
outputs : (8L,)

Whats the most efficient way to convert it to a string so i only get 8?
I'm new at python any help would be appreciated.

A: What you are seeing is that the information in row is actually a list of tuples. Each of those tuples has one member.
Try printing max(row)[0].
See this example;
In [7]: row = [(1,), (2,), (8,)]

In [8]: max(row)
Out[8]: (8,)

In [9]: print(max(row)[0])
8

(You're not seeing L here because I'm using Python 3)
Just to show that it works in Python 2:
Python 2.7.11 (default, Jan  9 2016, 15:47:04)
[GCC 4.2.1 Compatible FreeBSD Clang 3.4.1 (tags/RELEASE_34/dot1-final 208032)] on freebsd10
Type "help", "copyright", "credits" or "license" for more information.
>>> row = [(1L,), (2L,), (8L,)]
>>> max(row)
(8L,)
>>> print(max(row)[0])
8


text:
Q: Get object from another model for method I have the following method in a class and I need to pull an item from another model to use in this method. I cant seem to pull the item because I am using current_user to get the other item and the model does not recognize current_user. I am not sure how DRY this is anyway because I have read that the model should not call current_user. Here is the method...
class Upsell
  include Mongoid::Document
  belongs_to :user
  belongs_to :charges

...

  def total_fees
    items = []
    items << (current_user.reportapprovals.first.admin_request_report_type).to_i
      if self.multiple_admin == true
       items << self.multiple_admin_amount
      end
end

My error is that
undefined local variable or method `current_tenant' for #<Upsell:0xc82c9d39>

I am wondering if I should set user in the model but so far that has not worked.
@user = User.find(params[:id])

A: You need to pass current_user as function parameter
def total_fees_for user
    items = []
    items << (user.reportapprovals.first.admin_request_report_type).to_i
    if self.multiple_admin == true
       items << self.multiple_admin_amount
    end
end


text:
Q: How to identify the default sender IP address? In context of IP warming, I wonder how (within Marketing Cloud interface) to identify which IP address emails are being sent from.

A: If you purchased a dedicated IP, you can see it in the Deliver profile:

When you create a delivery profile, you specify the IP address to use.
  If you do not use a private domain, you select the account default.

Here's the help doc: https://help.salesforce.com/articleView?id=mc_es_delivery_profiles.htm&type=5&sfdcIFrameOrigin=null
If you haven't purchased your own IP, you're on a shared one, and there is currently no way to check the IP address from the interface:

By design, it is not currently possible to locate the default IP
  address used for email sends in your Marketing Cloud account.
For assistance obtaining your account's default IP email sending
  address, please create a Case with Marketing Cloud Support via
  Salesforce Help.

Help doc: Find the default email sending IP address for your Marketing Cloud account


text:
Q: How to send a .gif file over a serial port connection using C in Linux I would like to send a .gif file over a serial port connection using C in Linux.
I know how to send bytes over the connection and receive them on the other hand, but have no real idea how to do it with a .gif file.
How can I send the image byte per byte over the connection and reconstruct it on the other end?
Thanks.

A: Sending a gif is no different than sending any other sequence of bytes.  As long as you're not using a file mode that tries to translate carriage returns and/or line feeds like some non-binary connections do, you just read the file in and send the contents, and on the other end read them off the connection and write them to a file.

A: You should try the Zmodem protocol. As a bonus, there is a description and source code at this site:  http://pauillac.inria.fr/~doligez/zmodem/


text:
Q: Syntax error in entering mathematical expression I am trying to enter the following mathematical expression in code:
Subscript[Q, n, 2][
  n] = (1/2\[InvisibleComma]\[Mu][
       n]^2 Sqrt[\[Lambda]] (Cos[\[Mu][n] Sqrt[\[Lambda]]]^2 +
        Cosh[\[Mu][n] Sqrt[\[Lambda]]]^2) +
     3/2 \[Mu][
       n] Cos[\[Mu][n] Sqrt[\[Lambda]]] Cosh[\[Mu][
         n] Sqrt[\[Lambda]]] (Cos[\[Mu][
            n] Sqrt[\[Lambda]]] Sinh[\[Mu][n] Sqrt[\[Lambda]]] +
        Cosh[\[Mu][n] Sqrt[\[Lambda]]] Sin[\[Mu][
            n] Sqrt[\[Lambda]]])) Cosh[\[Mu][n]^2/Sqrt[\[Lambda]]]

However, I get a syntax error in Mathematica:

Can anybody spot a reason why this might be happening?


text:
Q: Using a Javascript function to Return a value in a table element I need to display this result as a background image of my table.  I have added a function to the bottom of the javascript, but am unable to get it to pass thru. I removed the function it since it did not work.
This works as it is now, but does not put the image in the background.
Thanks.

<base href="http://localhost:85/shop/" target="_blank">

A: I think I know what you mean, I may be wrong.
You want to select an image from an array containing strings of HTML which also happens to contain an image tag, you want to use the src attribute value for the background image of your table.
You would use a regular expression to do that in a for loop or join the array to a string first, could be used, but as Adam Botley mentioned, store each URL in the array, it will make your life a whole lot easier.
It looks like your code is from a tutorial, so if all you really want to do is randomly select a background image for the table that's even easier.
Here is what you can do. Create an array of URLs.

var urls = ['http://lorempixel.com/200/200', 'http://lorempixel.com/200/200'];

Then you need to calculate a random number to use for the key.

var index = Math.floor(Math.random() * urls.length);

A random number in Javascript is floating point number between 0 and 1, so you multiply this by the amount of URLs in the array. The Math.floor() returns the integer of the argument.
Then you'll need a reference to the table element.

var theTableElement = document.getElementById('theTableElement');

For that to actually work you must add an id to the table in the HTML.

    hello
    there

    you
    person :)

Now, to set the background image, you can just.

theTableElement.style.background = 'url(' + urls[index] + ')';

Now It should work, let me know!


text:
Q: using f string and .format together name = input("Please enter your name: ")
age= int(input("How old are you,{0}?" .format(name)))

print(age)

if age >= 22:
    print(f"Congratulations {name} , You're eligible to vote.")
else:
    print(f"Oops {name} ,We're are sorry but you can try again in {0} years." .format(22 - age))

The outcome is not minusing the .format command? can we not use both the functions into one line of code.

A: The f string is evaluated to a str which has the format method, so yes, it will work. The trick is that you have to escape the brackets intended for the format method so that they resolve properly later.
>>> foo = "bar"
>>> f"foo {foo} 0 {{0}}".format("baz")
'foo bar 0 baz'

Notice that {{0}} resolves to {0} in the f string and then to the first formatted parameter.

A: This makes no sense at all, you can do everything with f-strings:
name = input("Please enter your name: ")
age = int(input(f"How old are you {name}? "))
print(age)
if age >= 22:
    print(f"Congratulations {name}, You're eligible to vote.")
else:
    print(f"Oops {name}, We're are sorry but you can try again in {22 - age} years.")

f-strings are now the best option. For more info see:
https://peps.python.org/pep-0498/#abstract


text:
Q: Joomla 2.5. prevent module from showing on article page I have a problem with the module that I use to show the content of a category. The module is set to show on this category, but it also shows when I open an article which is also under this same category...
What I would like is to show only article without this module and module to be visible only on category of the article.
I know this can be achieved if I add every article to a new menu which is not shown anywhere on the site but this is too much work and is complicating things to my editors. I hope this can be achieved without adding every article to a menu...
thank you!

A: There is no such tool, app, plugin, or component called "Advance Menu manager"
However there is a plugin called "Advance MODULES manager"
And this too on Joomla 2.5 has the same issue.
I have it set to NOT show certain momdules on article, or category pages however the module still appears.
Its my impression this is because the article are inside categories which were created in a joomla version PRIOR to j 2.5
Since J2.5 no longer uses the same structure for categories, its still picking up the wrong menu ID somehow.
At this moment, i am still working this out

A: This is due to the articles inheriting the itemID from the category. Joomla places modules based on the itemID of the menu items. In order to prevent the module(s) from displaying on the child items of a menu item, you will need to use Advance Menu manager. It has the option to only display module on the parent menu item.

A: you should edit the code of the module (if it's yours) or override its view (if it's core) and start it with:
if (JRequest::getVar('view','')=='blog') {

As an alternative which I used on a fairly complex site, do this check at the template level and output two different module positions based on this, i.e. sidebar-blog and sidebar-article.
You will then have some modules duplicated (if you want them on both blog and article pages) but it's a very easy fix and requires little coding.


text:
Q: Dask distributed problem: shuffle_transfer failed during shuffle I don't know which part is not correct, at the first, I create a clusters on AWS with cloud-provider library, then I run tsfresh library to extract features. And I got this error.
from dask_cloudprovider.aws import FargateCluster
from distributed import Client

cluster = FargateCluster(
    n_workers=2,
    worker_mem=1024*8,
    image="dask-tslearn:latest",
    fargate_spot=True,
    task_role_policies=["arn:aws:iam::aws:policy/AmazonS3FullAccess"],
)
client = Client(cluster)
client

Then, I run below:
cluster.scale(50)

from tsfresh.feature_extraction import EfficientFCParameters

settings = EfficientFCParameters()
assert "matrix_profile" not in settings

import dask.dataframe as dd
from tsfresh import extract_features

df = dd.read_parquet("s3://**/")

X = extract_features(
    df,
    column_id="meter_id",
    column_sort="iso_datetime",
    chunksize=1,
    default_fc_parameters=settings,
)

result = X.compute()

then, the code failed because of error:
RuntimeError                              Traceback (most recent call last)
Cell In [11], line 7
      3 from tsfresh import extract_features
      5 df = dd.read_parquet("s3***")
----> 7 X = extract_features(
      8     df,
      9     column_id="id",
     10     column_sort="***",
     11     chunksize=1,
     12     default_fc_parameters=EfficientFCParameters(),
     13 )
     15 result = X.compute()

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/tsfresh/feature_extraction/extraction.py:164, in extract_features(timeseries_container, default_fc_parameters, kind_to_fc_parameters, column_id, column_sort, column_kind, column_value, chunksize, n_jobs, show_warnings, disable_progressbar, impute_function, profile, profiling_filename, profiling_sorting, distributor, pivot)
    161 else:
    162     warnings.simplefilter("default")
--> 164 result = _do_extraction(
    165     df=timeseries_container,
    166     column_id=column_id,
    167     column_value=column_value,
    168     column_kind=column_kind,
    169     column_sort=column_sort,
    170     n_jobs=n_jobs,
    171     chunk_size=chunksize,
    172     disable_progressbar=disable_progressbar,
    173     show_warnings=show_warnings,
    174     default_fc_parameters=default_fc_parameters,
    175     kind_to_fc_parameters=kind_to_fc_parameters,
    176     distributor=distributor,
    177     pivot=pivot,
    178 )
    180 # Impute the result if requested
    181 if impute_function is not None:

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/tsfresh/feature_extraction/extraction.py:304, in _do_extraction(df, column_id, column_value, column_kind, column_sort, default_fc_parameters, kind_to_fc_parameters, n_jobs, chunk_size, disable_progressbar, show_warnings, distributor, pivot)
    301 if not pivot:
    302     return result
--> 304 return_df = data.pivot(result)
    305 return return_df

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/tsfresh/feature_extraction/data.py:413, in DaskTsAdapter.pivot(self, results)
    404 """
    405 The extract features function for dask returns a
    406 dataframe of [id, variable, value].
   (...)
    410 Attention: this is highly non-optimized!
    411 """
    412 results = results.reset_index(drop=True).persist()
--> 413 results = results.categorize(columns=["variable"])
    414 feature_table = results.pivot_table(
    415     index=self.column_id, columns="variable", values="value", aggfunc="sum"
    416 )
    418 return feature_table

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/dask/dataframe/core.py:5255, in DataFrame.categorize(self, columns, index, split_every, **kwargs)
   5253 @wraps(categorize)
   5254 def categorize(self, columns=None, index=None, split_every=None, **kwargs):
-> 5255     return categorize(
   5256         self, columns=columns, index=index, split_every=split_every, **kwargs
   5257     )

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/dask/dataframe/categorical.py:152, in categorize(df, columns, index, split_every, **kwargs)
    149 dsk.update(df.dask)
    151 # Compute the categories
--> 152 categories, index = compute_as_if_collection(
    153     df.__class__, dsk, (prefix, 0), **kwargs
    154 )
    156 # some operations like get_dummies() rely on the order of categories
    157 categories = {k: v.sort_values() for k, v in categories.items()}

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/dask/base.py:341, in compute_as_if_collection(cls, dsk, keys, scheduler, get, **kwargs)
    339 schedule = get_scheduler(scheduler=scheduler, cls=cls, get=get)
    340 dsk2 = optimization_function(cls)(dsk, keys, **kwargs)
--> 341 return schedule(dsk2, keys, **kwargs)

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/distributed/client.py:3136, in Client.get(self, dsk, keys, workers, allow_other_workers, resources, sync, asynchronous, direct, retries, priority, fifo_timeout, actors, **kwargs)
   3134         should_rejoin = False
   3135 try:
-> 3136     results = self.gather(packed, asynchronous=asynchronous, direct=direct)
   3137 finally:
   3138     for f in futures.values():

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/distributed/client.py:2305, in Client.gather(self, futures, errors, direct, asynchronous)
   2303 else:
   2304     local_worker = None
-> 2305 return self.sync(
   2306     self._gather,
   2307     futures,
   2308     errors=errors,
   2309     direct=direct,
   2310     local_worker=local_worker,
   2311     asynchronous=asynchronous,
   2312 )

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/distributed/utils.py:338, in SyncMethodMixin.sync(self, func, asynchronous, callback_timeout, *args, **kwargs)
    336     return future
    337 else:
--> 338     return sync(
    339         self.loop, func, *args, callback_timeout=callback_timeout, **kwargs
    340     )

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/distributed/utils.py:405, in sync(loop, func, callback_timeout, *args, **kwargs)
    403 if error:
    404     typ, exc, tb = error
--> 405     raise exc.with_traceback(tb)
    406 else:
    407     return result

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/distributed/utils.py:378, in sync.<locals>.f()
    376         future = asyncio.wait_for(future, callback_timeout)
    377     future = asyncio.ensure_future(future)
--> 378     result = yield future
    379 except Exception:
    380     error = sys.exc_info()

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/tornado/gen.py:769, in Runner.run(self)
    766 exc_info = None
    768 try:
--> 769     value = future.result()
    770 except Exception:
    771     exc_info = sys.exc_info()

File /opt/homebrew/Caskroom/miniforge/base/envs/lake/lib/python3.10/site-packages/distributed/client.py:2168, in Client._gather(self, futures, errors, direct, local_worker)
   2166         exc = CancelledError(key)
   2167     else:
-> 2168         raise exception.with_traceback(traceback)
   2169     raise exc
   2170 if errors == "skip":

File /opt/conda/lib/python3.10/site-packages/distributed/shuffle/_shuffle.py:71, in shuffle_transfer()

RuntimeError: shuffle_transfer failed during shuffle c1992000bcde9deee65a2332ab4614a2

below is my package version.
Package                       Version
----------------------------- -----------
aiobotocore                   2.4.2
aiohttp                       3.8.4
aioitertools                  0.11.0
aiosignal                     1.3.1
anyio                         3.6.2
appnope                       0.1.3
argon2-cffi                   21.3.0
argon2-cffi-bindings          21.2.0
asttokens                     2.2.1
async-timeout                 4.0.2
attrs                         22.2.0
backcall                      0.2.0
backports.functools-lru-cache 1.6.4
beautifulsoup4                4.11.2
bleach                        6.0.0
bokeh                         2.4.3
botocore                      1.27.59
brotlipy                      0.7.0
certifi                       2022.12.7
cffi                          1.15.1
charset-normalizer            2.1.1
click                         8.1.3
cloudpickle                   2.2.1
colorama                      0.4.6
comm                          0.1.2
cryptography                  39.0.1
cytoolz                       0.12.0
dask                          2023.3.0
dask-cloudprovider            2022.10.0
debugpy                       1.6.6
decorator                     5.1.1
defusedxml                    0.7.1
distributed                   2023.3.0
entrypoints                   0.4
executing                     1.2.0
fastjsonschema                2.16.3
flit_core                     3.8.0
frozenlist                    1.3.3
fsspec                        2023.1.0
HeapDict                      1.0.1
idna                          3.4
importlib-metadata            6.0.0
importlib-resources           5.12.0
ipykernel                     6.21.2
ipython                       8.11.0
ipython-genutils              0.2.0
jedi                          0.18.2
Jinja2                        3.1.2
jmespath                      1.0.1
joblib                        1.2.0
jsonschema                    4.17.3
jupyter_client                8.0.3
jupyter_core                  5.2.0
jupyter-events                0.6.3
jupyter_server                2.3.0
jupyter_server_terminals      0.4.4
jupyterlab-pygments           0.2.2
llvmlite                      0.39.1
locket                        1.0.0
lz4                           4.3.2
MarkupSafe                    2.1.2
matplotlib-inline             0.1.6
mistune                       2.0.5
msgpack                       1.0.4
multidict                     6.0.4
nbclassic                     0.5.2
nbclient                      0.7.2
nbconvert                     7.2.9
nbformat                      5.7.3
nest-asyncio                  1.5.6
notebook                      6.5.2
notebook_shim                 0.2.2
numba                         0.56.4
numpy                         1.23.5
packaging                     23.0
pandas                        1.5.3
pandocfilters                 1.5.0
parso                         0.8.3
partd                         1.3.0
patsy                         0.5.3
pexpect                       4.8.0
pickleshare                   0.7.5
Pillow                        9.4.0
pip                           23.0.1
pkgutil_resolve_name          1.3.10
platformdirs                  3.0.0
pooch                         1.7.0
prometheus-client             0.16.0
prompt-toolkit                3.0.38
psutil                        5.9.4
ptyprocess                    0.7.0
pure-eval                     0.2.2
pyarrow                       11.0.0
pycparser                     2.21
Pygments                      2.14.0
pyOpenSSL                     23.0.0
pyrsistent                    0.19.3
PySocks                       1.7.1
python-dateutil               2.8.2
python-json-logger            2.0.7
pytz                          2022.7.1
PyYAML                        6.0
pyzmq                         25.0.0
requests                      2.28.2
rfc3339-validator             0.1.4
rfc3986-validator             0.1.1
s3fs                          2023.1.0
scikit-learn                  1.2.1
scipy                         1.10.1
Send2Trash                    1.8.0
setuptools                    67.4.0
six                           1.16.0
sniffio                       1.3.0
sortedcontainers              2.4.0
soupsieve                     2.3.2.post1
stack-data                    0.6.2
statsmodels                   0.13.5
stumpy                        1.11.1
tblib                         1.7.0
terminado                     0.17.1
threadpoolctl                 3.1.0
tinycss2                      1.2.1
toolz                         0.12.0
tornado                       6.2
tqdm                          4.64.1
traitlets                     5.9.0
tsfresh                       0.20.0
typing_extensions             4.4.0
urllib3                       1.26.14
wcwidth                       0.2.6
webencodings                  0.5.1
websocket-client              1.5.1
wheel                         0.38.4
wrapt                         1.15.0
yarl                          1.8.2
zict                          2.2.0
zipp                          3.15.0

and the package used for cluster worker:
ARG BASE_CONTAINER=condaforge/mambaforge:latest
FROM --platform=linux/amd64 $BASE_CONTAINER

ARG python=3.10.8
ARG release=2023.3.0

SHELL ["/bin/bash", "-c"]

ENV PATH /opt/conda/bin:$PATH
ENV PYTHON_VERSION=${python}
ENV DASK_VERSION=${release}

RUN mamba install -y \
    "mamba>=0.27.0" \
    python=${PYTHON_VERSION} \
    tsfresh \
    pyarrow \
    s3fs \
    nomkl \
    cmake \
    dask=${DASK_VERSION} \
    cachey \
    streamz \
    && mamba clean -tipy \
    && find /opt/conda/ -type f,l -name '*.a' -delete \
    && find /opt/conda/ -type f,l -name '*.pyc' -delete \
    && find /opt/conda/ -type f,l -name '*.js.map' -delete \
    && find /opt/conda/lib/python*/site-packages/bokeh/server/static -type f,l -name '*.js' -not -name '*.min.js' -delete \
    && rm -rf /opt/conda/pkgs

COPY prepare.sh /usr/bin/prepare.sh

RUN mkdir /opt/app

ENTRYPOINT ["tini", "-g", "--", "/usr/bin/prepare.sh"]


text:
Q: Azure SQL Transpose a table with all rows I use Azure SQL database. I have a table - test_excel_poc_head with the below values which I want to transpose using link id values as the columns

The intended output is below where the column is the 'link_id' values. The link_id values are dynamic

I started using UNPIVOT and PIVOT option and below is my unpivot query and results:
SELECT link_id,head_values
FROM
(SELECT link_id,comp1,comp2,comp3,comp4
 FROM [dbo].[test_excel_poc_head]
) AS cp
UNPIVOT
(head_values FOR head_value in (comp1,comp2,comp3,comp4)
) AS up

RESULTS:

Now when I add the PIVOT code, it expects an aggregate function which I do not have as it is a string and it errors out.
If I add MAX as the aggregate function, I do not get the intended result.
SELECT * FROM (
SELECT link_id,head_values
FROM
(SELECT link_id,comp1,comp2,comp3,comp4
 FROM [dbo].[test_excel_poc_head]
) AS cp
UNPIVOT
(head_values FOR head_value in (comp1,comp2,comp3,comp4)
) AS up
) temp_results
PIVOT(
MAX(head_values)
FOR link_id
IN (
[1],[2],[3],[4],[5],[6]
)
) AS PivotTable

RESULT:

But this is not my expected result. Is there any other option to achieve PIVOT without the use of agg functions?
Thanks for your time and help.

A: I tried my luck. Could you check below query if it works,
What I did different to your query is making the result of UNPIVOT distinct by adding row_number to it so that the later PIVOT will take max of each row and display separately. My bad if the explanation doesn't makes sense to you.
select [1],[2],[3],[4],[5],[6]
  from
  ( select link_id,head_values,
           row_number() over (partition by link_id order by link_id) rn
      from
         ( select link_id
                 ,cast(comp1 as varchar(255)) as comp1
                 ,cast(comp2 as varchar(255)) as comp2
                 ,cast(comp3 as varchar(255)) as comp3
                 ,cast(comp4 as varchar(255)) as comp4
             from [dbo].[test_excel_poc_head]
         ) as cp
    unpivot
    (
      head_values for head_value in (comp1,comp2,comp3,comp4)
    ) as up
   ) temp_results
pivot
(
  max(head_values)
  for link_id in ([1],[2],[3],[4],[5],[6])
) as pivottable;

db<>fiddle for your reference.


text:
Q: Angular UI Bootstrap Typeahead with 1 object that has comma separated Key:Values Not sure if anyone has run into this situation.  I have an endpoint I'm using for my typeahead that returns 1 object with a list of key:values.  A normal response will look like this:
{
 "BK-021":"BK-021",
 "BK-058":"BK-058",
 "BK-068":"BK-068",
 "BK-088":"BK-088",
 "bk-1":"bk-1",
 "BK-10":"BK-10"
}

If I search for "BK" in this case for the example above, the endpoint returns the same key name as the value.  This makes it seemingly impossible to plug into typeahead since its not returning a list of objects with a known KEY and doesn't separate the list into multiple objects either. I've been wracking my brain over this for a while now.

A: Figured it out with a bit of underscore to help.  My request now looks like this:
$scope.getCode = function(val) {
  return $http.get('http://urlhere'+val)
  .then(function(response){
    var sorted = response.data;
    var sortedObject = _.values(sorted);
    return sortedObject;
  });
};

By using _.values I'm able to just transform the object into a basic array and print all results.  Works perfectly!


text:
Q: D3.js upgrade from version 3 to version 4/5 - diagram not populating I am try to upgrade this working version of d3.js flow-chart in jsfiddle:- https://jsfiddle.net/zgv9ajn4/7/ from Version 3 to Version 4/5.
I went through the documentation and the console error messages and rectified the errors one after the other. Below are some other things I also had in mind during this version upgrade.

I am not able to see any diagram after making the changes, I don't even see any console errors too, Only an empty screen.
Here is the jsfiddle for the version4 :- http://jsfiddle.net/5d02grL7/1/

var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 960 - margin.right - margin.left,
  height = 800 - margin.top - margin.bottom;

function generateEmptyDecisionBox(condition) {
  return condition === 'False' ? [{
    "name": "newDecision",
    "id": "newId",
    "type": "decision",
    "value": "notSure",
    "condition": `${condition}`,
  }, {}] : [{}, {
    "name": "newDecision",
    "id": "newId",
    "type": "decision",
    "value": "notSure",
    "condition": `${condition}`,
  }];
}

function generateEmptyActionBox(condition) {
  return condition === 'False' ? [{
    "name": "newAction",
    "id": "newId",
    "type": "action",
    "value": "notSure",
    "condition": `${condition}`,
  }, {}] : [{}, {
    "name": "newAction",
    "id": "newId",
    "type": "action",
    "value": "notSure",
    "condition": `${condition}`,
  }];
}

var selectedNode;
var selectedLink;

var treeData = {
  "name": "Root",
  "type": "decision",
  "children": [{
      "name": "analytics",
      "condition": "False",
      "type": "decision",
      "value": "a+b",
      "children": [{
        "name": "distinction",
        "type": "action",
        "condition": "True",
        "value": "5",
      }, {
        "name": "nonDistinction",
        "type": "action",
        "condition": "false",
        "value": "4",
        "children": [],
      }],
    },
    {
      "condition": "True",
      "name": "division",
      "type": "decision",
      "value": "a-b",
      "children": {
        "name": "analytics",
        "condition": "False",
        "type": "decision",
        "value": "a+b",
        "children": [{
          "name": "distinction",
          "type": "action",
          "condition": "True",
          "value": "5",
        }, {
          "name": "nonDistinction",
          "type": "decision",
          "condition": "false",
          "value": "4",
          "children": {
            "name": "analytics",
            "condition": "False",
            "type": "decision",
            "value": "a+b",
            "children": [{
              "name": "distinction",
              "type": "action",
              "condition": "True",
              "value": "5",
            }, {
              "name": "nonDistinction",
              "type": "action",
              "condition": "false",
              "value": "4"
            }],
          },
        }],
      },
    }
  ]
};

var i = 0,
  duration = 1000,
  rectW = 120,
  rectH = 60;

var treeMap = d3.tree().size([150, 90]);

//LINK FUNCTION TO DRAW LINKS
var linkFunc = function(d) {
  console.log("linkFunc", d);
  var source = {
    x: d.parent.x + rectW / 2,
    y: d.parent.y + (rectH / 2)
  };
  var target = {
    x: d.x + (rectW / 2),
    y: d.y + 3,
  };

  // This is where the line bends
  var inflection = {
    x: target.x,
    y: source.y
  };
  var radius = 5;

  var result = "M" + source.x + ',' + source.y;

  if (source.x < target.x && d.data.type) {
    // Child is to the right of the parent
    result += ' H' + (inflection.x - radius);
  } else if (d.data.type) {
    result += ' H' + (inflection.x + radius);
  } else {
    return;
  }

  // Curve the line at the bend slightly
  result += ' Q' + inflection.x + ',' + inflection.y + ' ' + inflection.x + ',' + (inflection.y + radius);

  result += 'V' + target.y;
  return result;
}

// END OF LINK FUNC //

/* var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.x + rectW / 2, d.y + rectH / 2];
  }); */

// DRAW TREE //
var svg = d3.select(".tree-diagram").append("svg").attr("width", 1000).attr("height", 1000)
  .call(zm = d3.zoom().scaleExtent([1, 3]).on("zoom", redraw)).append("g")
  .attr("transform", "translate(" + 350 + "," + 20 + ")");

// ADD ARROW TO THE BOTTOM POINTING TO THE NEXT DECISION.

svg.append("svg:defs").selectAll("marker")
  .data(["end"]) // Different link/path types can be defined here
  .enter().append("svg:marker") // This section adds in the arrows
  .attr("id", String)
  .attr("viewBox", "0 -5 10 10")
  .attr("refX", 15)
  .attr("refY", 0.5)
  .attr("markerWidth", 4)
  .attr("markerHeight", 4)
  .attr("orient", "auto")
  .append("svg:path")
  .attr("d", "M0,-5L10,0L0,5");

//necessary so that zoom knows where to zoom and unzoom from
/* zm.translate([350, 20]); */

root = d3.hierarchy(treeData, function(d) {
  return d.children;
});
root.x0 = 0;
root.y0 = 0;

update(root);

d3.select(".tree-diagram").style("height", "1000px");

// END OF DRAW TREEE //

function update(source) {
  var treeData = treeMap(root);
  const treeRoot = d3.hierarchy(root);
  d3.tree(treeRoot);
  // var treeData = treeMap(root);

  // Compute the new tree layout.
  var nodes = treeData.descendants(),
    links = treeData.descendants().slice(1);

  console.log(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 90;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr('transform', 'translate(' + source.x0 + ', ' + source.y0 + ')')
    .attr("class", "node")
    .on("click", click)
  //  .on("blur", onNodeBlur);

  nodeEnter.append('path')
    .attr("d", function(d) {
      if (d.type === 'decision') {
        return 'M 60 0 120 30 60 60 0 30 Z';
      } else if (d.type === 'action') {
        return 'M 0 0 120 0 120 60 0 60 Z';
      } else {
        return 'M -100 -10 -10 -10 -10 -10 -10 -10Z'
      }
    }).attr("stroke-width", 1)
    .attr('class', 'myPaths')
    .style("fill", function(d) {
      return "lightsteelblue";
    });

  nodeEnter.append("text")
    .attr("x", rectW / 2)
    .attr("y", rectH / 2)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.name;
    });

  // UPDATE
  var nodeUpdate = nodeEnter.merge(node);

  // Transition to the proper position for the node
  nodeUpdate.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + (d.x) + "," + (d.y) + ")";
    });

  nodeUpdate.select('path.myPaths')
    .attr("d", function(d) {
      if (d.type === 'decision') {
        return 'M 60 0 120 30 60 60 0 30 Z';
      } else if (d.type === 'action') {
        return 'M 0 0 120 0 120 60 0 60 Z';
      } else {
        return 'M -100 -10 -10 -10 -10 -10 -10 -10Z'
      }
    }).attr("stroke-width", 1)
    .style("fill", function(d) {
      return "lightsteelblue";
    });

  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.x + "," + source.y + ")";
    })
    .remove();

  nodeExit.select("path")
    .attr("d", function(d) {
      if (d.type === 'decision') {
        return 'M 60 0 120 30 60 60 0 30 Z';
      } else if (d.type === 'action') {
        return 'M 0 0 120 0 120 60 0 60 Z';
      } else {
        return 'M -100 -10 -10 -10 -10 -10 -10 -10Z'
      }
    }).attr("stroke-width", 1)
    .attr('class', 'myPaths')
    .style("fill", function(d) {
      return "lightsteelblue";
    });

  nodeExit.select("text");

  // Update the links…
  var link = svg.selectAll(".link")
    .data(links, function(d) {
      console.log(d);
      return d.id;
    }).classed('link1', true);

  // Enter any new links at the parent's previous position.
  var linkEnter = link.enter()
    .insert("g", "g")
    .attr("class", "link");

  linkEnter.append('path')
    .on('click', function(d, i) {
      selectedLink = d;
      // Use the native SVG interface to get the bounding box to
      // calculate the center of the path

      var bbox = this.getBBox();
      var x;
      var y;

      if (d.parent.x < d.x) {
        // Child is to the right of the parent
        x = bbox.x + bbox.width;
        y = bbox.y;
        plusButton
          .attr('transform', 'translate(' + x + ', ' + y + ')')
          .classed('hide', false);

      } else {
        x = bbox.x;
        y = bbox.y;
        plusButton
          .attr('transform', 'translate(' + x + ', ' + y + ')')
          .classed('hide', false);
      }
    })
    .on('blur', function(d, i) {
      plusButton
        .classed('hide', true);
    }).attr("marker-end", "url(#end)");

  // Add Link Texts.
  linkEnter.append('text');

  link.select('path')
    .attr("d", linkFunc);

  link.select('text')
    .text(function(d, i) {
      if (d.parent.x < d.x) {
        return 'True';
      } else {
        return 'False';
      }
    })
    .attr('transform', function(d) {
      console.log(d);
      if (d.parent.x < d.x && d.data.type) {
        console.log("comes in here for source < target");
        return 'translate(' + (d.x + rectW / 2) + ',' + (d.parent.y + rectH) + ')';
      } else if (d.data.type) {
        return 'translate(' + (d.parent.x + rectW / 2) + ',' + (d.y + rectH) + ')';
      } else {
        return;
      }
    });

  //LinkUpdate
  var linkUpdate = linkEnter.merge(link);

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", linkFunc);

  // Transition links to their new position.

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", linkFunc)
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

// ON CLICK OF NODES
function click(d) {

  if (d.type === 'action') {
    return;
  }

  selectedNode = d;
  var m = d.x;
  var h = d.y;

  var m = d.x + 110;
  var h = d.y + 35;

  diamondImage
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);

  var m = d.x + 110;
  var h = d.y;

  rectangleShape
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);

  var m = d.x - 20;
  var h = d.y + 35;

  diamondImageFalse
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);

  var m = d.x - 20;
  var h = d.y;

  rectangleShapeFalse
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);
}

/* function onNodeBlur(){
  diamondImage
  .classed('hide', true);
  rectangleShape
    .classed('hide', true);
   diamondImageFalse
     .classed('hide',true);
   rectangleShapeFalse
    .classed('hide',true);
}
 */
//Redraw for zoom
function redraw() {
  //console.log("here", d3.event.translate, d3.event.scale);
  svg.attr("transform",
    "translate(" + d3.event.translate + ")" +
    " scale(" + d3.event.scale + ")");
}

// oN CALL

function addElement(d, truthy) {
  console.log(d);

  d.children = null;
  d.children = generateEmptyDecisionBox(truthy);
  update(root);
}

// draw elements //

function drawDiamond(centroid) {
  // Start at the top
  console.log(centroid);
  console.log("rectH", rectH, rectW)
  // Start at the top
  var result = 'M' + centroid.x + ',' + (centroid.y - rectH / 2);

  // Go right
  result += 'L' + (centroid.x + rectW / 2) + ',' + centroid.y;

  // Bottom
  result += 'L' + centroid.x + ',' + (centroid.y + rectH / 2);

  // Left
  result += 'L' + (centroid.x - rectW / 2) + ',' + centroid.y;

  // Close the shape
  result += 'Z';

  return result;
}

function drawRect(centroid) {
  // Start at the top left
  console.log(centroid);
  var result = 'M' + (centroid.x - rectW / 2) + ',' + (centroid.y - rectH / 2);

  // Go right
  result += 'h' + rectW;

  // Go down
  result += 'v' + rectH;

  // Left
  result += 'h-' + rectW;

  // Close the shape
  result += 'Z';

  console.log(result);
  return result;
}

var plusButton = svg
  .append('g')
  .classed('button', true)
  .classed('hide', true)
  .on('click', function() {
    console.log("hello");
    /*        addElement(selectedLink.source); */
    console.log("Clicked on Diamond");
    console.log("set hide to true");
    removeAllButtonElements();
  });

plusButton
  .append('rect')
  .attr('transform', 'translate(-8, -8)') // center the button inside the `g`
  .attr('width', 16)
  .attr('height', 16)
  .attr('rx', 2);

plusButton
  .append('path')
  .attr('d', 'M-6 0 H6 M0 -6 V6');

var rectangleShape = svg.append('g')
  .classed('conditionImage', true)
  .classed('hide', true)
  .on('click', function() {
    removeAllButtonElements();
  })

rectangleShape
  .append('rect')
  .attr('width', 30)
  .attr('height', 20)
  .style('fill', 'orange');

var diamondImage = svg.append('g')
  .classed('conditionSvg', true)
  .classed('hide', true)
  .classed('scale', true)
  .on('click', function() {
    console.log("Clicked on Diamond");
    console.log("set hide to true");
    addElement(selectedNode, 'True');
    removeAllButtonElements();
  });

diamondImage
  .append('path')
  .attr('d', 'M 15 0 30 15 15 30 0 15 Z')
  .style("fill", 'orange');

var rectangleShapeFalse = svg.append('g')
  .classed('conditionImage', true)
  .classed('hide', true)
  .on('click', function() {
    console.log("rectangle clicked");
    removeAllButtonElements();
  })

rectangleShapeFalse
  .append('rect')
  .attr('width', 30)
  .attr('height', 20)
  .style('fill', 'orange');

var diamondImageFalse = svg.append('g')
  .classed('conditionImage', true)
  .classed('hide', true)
  .classed('scale', true)
  .on('click', function() {
    console.log("Clicked on Diamond");
    console.log("set hide to true");
    addElement(selectedNode, 'False');
    removeAllButtonElements();
  });

diamondImageFalse
  .append('path')
  .attr('d', 'M 15 0 30 15 15 30 0 15 Z')
  .style("fill", 'orange');

function removeAllButtonElements() {
  plusButton.classed('hide', true);
  diamondImage.classed('hide', true);
  rectangleShape.classed('hide', true);
  diamondImageFalse.classed('hide', true);
  rectangleShapeFalse.classed('hide', true);
}
.node {
  cursor: pointer;
  outline: none !important;
}

.node text {
  font: 10px sans-serif;
}

.button>path {
  stroke: blue;
  stroke-width: 1.5;
  /*   outline: none;  */
}

.button>rect {
  fill: #ddd;
  stroke: grey;
  stroke-width: 1px;
}

.conditionalSvg {
  /*   outline: none; */
  display: none;
}

.hide {
  /*    display: none;  */
  opacity: 0 !important;
  /*  pointer-events: none;  */
}

.link:hover {
  outline: none !important;
  cursor: pointer;
  stroke-width: 3px;
}

.link path {
  /*   outline: none !important;  */
  fill: none;
  stroke: darkgray;
  stroke-width: 2px;
}

.link path:hover {
  cursor: pointer;
  stroke-width: 4px;
}

.link text {
  font: 10px sans-serif;
}

.colorBlue {
  background-color: blue;
}

A: When I write v4 code, the steps I take in my head are:

*

*Select the nodes;

*Apply the data;

*Get the .exit() selection and apply their specific changes;

*Get the .enter() selection and apply their specific changes. Use this to append nodes and set constant attributes (that do not rely on d);

*Get the existing selection, apply their specific changes;

*Then .merge() with the .enter() selection and apply common changes - those that do rely on d.

For your links, you forgot to do the last step; adding the merge() line made the links be drawn.
// Add Link Texts.
linkEnter.append('text');

// Merge the new and the existing links before setting `d` and `text` on all of them
link = linkEnter.merge(link);

link.select('path')
  .attr("d", linkFunc);

Now, for your nodes, the data structure actually changed. All your metadata (name, type, etc) were now no longer properties of d, but of d.data. So changing if (d.type === 'decision') { to if (d.data.type === 'decision') { made it work.

var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120,
  },
  width = 960 - margin.right - margin.left,
  height = 800 - margin.top - margin.bottom;

function generateEmptyDecisionBox(condition) {
  return condition === 'False' ? [{
    "name": "newDecision",
    "id": "newId",
    "type": "decision",
    "value": "notSure",
    "condition": `${condition}`,
  }, {}] : [{}, {
    "name": "newDecision",
    "id": "newId",
    "type": "decision",
    "value": "notSure",
    "condition": `${condition}`,
  }];
}

function generateEmptyActionBox(condition) {
  return condition === 'False' ? [{
    "name": "newAction",
    "id": "newId",
    "type": "action",
    "value": "notSure",
    "condition": `${condition}`,
  }, {}] : [{}, {
    "name": "newAction",
    "id": "newId",
    "type": "action",
    "value": "notSure",
    "condition": `${condition}`,
  }];
}

var selectedNode;
var selectedLink;

var treeData = {
  "name": "Root",
  "type": "decision",
  "children": [{
      "name": "analytics",
      "condition": "False",
      "type": "decision",
      "value": "a+b",
      "children": [{
        "name": "distinction",
        "type": "action",
        "condition": "True",
        "value": "5",
      }, {
        "name": "nonDistinction",
        "type": "action",
        "condition": "false",
        "value": "4",
        "children": [],
      }],
    },
    {
      "condition": "True",
      "name": "division",
      "type": "decision",
      "value": "a-b",
      "children": {
        "name": "analytics",
        "condition": "False",
        "type": "decision",
        "value": "a+b",
        "children": [{
          "name": "distinction",
          "type": "action",
          "condition": "True",
          "value": "5",
        }, {
          "name": "nonDistinction",
          "type": "decision",
          "condition": "false",
          "value": "4",
          "children": {
            "name": "analytics",
            "condition": "False",
            "type": "decision",
            "value": "a+b",
            "children": [{
              "name": "distinction",
              "type": "action",
              "condition": "True",
              "value": "5",
            }, {
              "name": "nonDistinction",
              "type": "action",
              "condition": "false",
              "value": "4",
            }],
          },
        }],
      },
    },
  ],
};

var i = 0,
  duration = 1000,
  rectW = 120,
  rectH = 60;

var treeMap = d3.tree()
  .size([150, 90]);

//LINK FUNCTION TO DRAW LINKS
var linkFunc = function(d) {
  console.log("linkFunc", d);
  var source = {
    x: d.parent.x + rectW / 2,
    y: d.parent.y + (rectH / 2),
  };
  var target = {
    x: d.x + (rectW / 2),
    y: d.y + 3,
  };

  // This is where the line bends
  var inflection = {
    x: target.x,
    y: source.y,
  };
  var radius = 5;

  var result = "M" + source.x + ',' + source.y;

  if (source.x < target.x && d.data.type) {
    // Child is to the right of the parent
    result += ' H' + (inflection.x - radius);
  } else if (d.data.type) {
    result += ' H' + (inflection.x + radius);
  } else {
    return;
  }

  // Curve the line at the bend slightly
  result += ' Q' + inflection.x + ',' + inflection.y + ' ' + inflection.x + ',' + (inflection.y + radius);

  result += 'V' + target.y;
  return result;
};

// END OF LINK FUNC //

/* var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.x + rectW / 2, d.y + rectH / 2];
  }); */

// DRAW TREE //
var svg = d3.select(".tree-diagram")
  .append("svg")
  .attr("width", 1000)
  .attr("height", 1000)
  .call(zm = d3.zoom()
    .scaleExtent([1, 3])
    .on("zoom", redraw))
  .append("g")
  .attr("transform", "translate(" + 350 + "," + 20 + ")");

// ADD ARROW TO THE BOTTOM POINTING TO THE NEXT DECISION.

svg.append("svg:defs")
  .selectAll("marker")
  .data(["end"]) // Different link/path types can be defined here
  .enter()
  .append("svg:marker") // This section adds in the arrows
  .attr("id", String)
  .attr("viewBox", "0 -5 10 10")
  .attr("refX", 15)
  .attr("refY", 0.5)
  .attr("markerWidth", 4)
  .attr("markerHeight", 4)
  .attr("orient", "auto")
  .append("svg:path")
  .attr("d", "M0,-5L10,0L0,5");

//necessary so that zoom knows where to zoom and unzoom from
/* zm.translate([350, 20]); */

root = d3.hierarchy(treeData, function(d) {
  return d.children;
});
root.x0 = 0;
root.y0 = 0;

update(root);

d3.select(".tree-diagram")
  .style("height", "1000px");

// END OF DRAW TREEE //

function update(source) {
  var treeData = treeMap(root);
  const treeRoot = d3.hierarchy(root);
  d3.tree(treeRoot);
  // var treeData = treeMap(root);

  // Compute the new tree layout.
  var nodes = treeData.descendants(),
    links = treeData.descendants()
    .slice(1);

  console.log(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 90;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter()
    .append("g")
    .attr('transform', 'translate(' + source.x0 + ', ' + source.y0 + ')')
    .attr("class", "node")
    .on("click", click);
  //  .on("blur", onNodeBlur);

  nodeEnter.append('path')
    .attr("stroke-width", 1)
    .attr('class', 'myPaths')
    .style("fill", function(d) {
      return "lightsteelblue";
    });

  nodeEnter.append("text")
    .attr("x", rectW / 2)
    .attr("y", rectH / 2)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.data.name;
    });

  // UPDATE
  var nodeUpdate = nodeEnter.merge(node);

  // Transition to the proper position for the node
  nodeUpdate.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + (d.x) + "," + (d.y) + ")";
    });

  nodeUpdate.select('path.myPaths')
    .attr("d", function(d) {
      if (d.data.type === 'decision') {
        return 'M 60 0 120 30 60 60 0 30 Z';
      } else if (d.data.type === 'action') {
        return 'M 0 0 120 0 120 60 0 60 Z';
      } else {
        return 'M -100 -10 -10 -10 -10 -10 -10 -10Z';
      }
    });

  var nodeExit = node.exit()
    .transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.x + "," + source.y + ")";
    })
    .remove();

  // Update the links…
  var link = svg.selectAll(".link")
    .data(links, function(d) {
      return d.id;
    })
    .classed('link1', true);

  // Enter any new links at the parent's previous position.
  var linkEnter = link.enter()
    .insert("g", "g")
    .attr("class", "link");

  linkEnter.append('path')
    .on('click', function(d, i) {
      selectedLink = d;
      // Use the native SVG interface to get the bounding box to
      // calculate the center of the path

      var bbox = this.getBBox();
      var x;
      var y;

      if (d.parent.x < d.x) {
        // Child is to the right of the parent
        x = bbox.x + bbox.width;
        y = bbox.y;
        plusButton
          .attr('transform', 'translate(' + x + ', ' + y + ')')
          .classed('hide', false);

      } else {
        x = bbox.x;
        y = bbox.y;
        plusButton
          .attr('transform', 'translate(' + x + ', ' + y + ')')
          .classed('hide', false);
      }
    })
    .on('blur', function(d, i) {
      plusButton
        .classed('hide', true);
    })
    .attr("marker-end", "url(#end)");

  // Add Link Texts.
  linkEnter.append('text');

  // Merge the new and the existing links before setting `d` and `text` on all of them
  link = linkEnter.merge(link);

  link.select('path')
    .attr("d", linkFunc);

  link.select('text')
    .text(function(d, i) {
      if (d.parent.x < d.x) {
        return 'True';
      } else {
        return 'False';
      }
    })
    .attr('transform', function(d) {
      console.log(d);
      if (d.parent.x < d.x && d.data.type) {
        console.log("comes in here for source < target");
        return 'translate(' + (d.x + rectW / 2) + ',' + (d.parent.y + rectH) + ')';
      } else if (d.data.type) {
        return 'translate(' + (d.parent.x + rectW / 2) + ',' + (d.y + rectH) + ')';
      } else {
        return;
      }
    });

  //LinkUpdate
  var linkUpdate = linkEnter.merge(link);

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", linkFunc);

  // Transition links to their new position.

  // Transition exiting nodes to the parent's new position.
  link.exit()
    .transition()
    .duration(duration)
    .attr("d", linkFunc)
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

// ON CLICK OF NODES
function click(d) {

  if (d.data.type === 'action') {
    return;
  }

  selectedNode = d;
  var m = d.x;
  var h = d.y;

  var m = d.x + 110;
  var h = d.y + 35;

  diamondImage
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);

  var m = d.x + 110;
  var h = d.y;

  rectangleShape
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);

  var m = d.x - 20;
  var h = d.y + 35;

  diamondImageFalse
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);

  var m = d.x - 20;
  var h = d.y;

  rectangleShapeFalse
    .attr('transform', 'translate(' + m + ', ' + h + ')')
    .classed('hide', false);
}

/* function onNodeBlur(){
  diamondImage
  .classed('hide', true);
  rectangleShape
    .classed('hide', true);
   diamondImageFalse
     .classed('hide',true);
   rectangleShapeFalse
    .classed('hide',true);
}
 */

//Redraw for zoom
function redraw() {
  //console.log("here", d3.event.translate, d3.event.scale);
  svg.attr("transform",
    "translate(" + d3.event.translate + ")" +
    " scale(" + d3.event.scale + ")");
}

// oN CALL

function addElement(d, truthy) {
  console.log(d);

  d.children = null;
  d.children = generateEmptyDecisionBox(truthy);
  update(root);
}

// draw elements //

function drawDiamond(centroid) {
  // Start at the top
  console.log(centroid);
  console.log("rectH", rectH, rectW);
  // Start at the top
  var result = 'M' + centroid.x + ',' + (centroid.y - rectH / 2);

  // Go right
  result += 'L' + (centroid.x + rectW / 2) + ',' + centroid.y;

  // Bottom
  result += 'L' + centroid.x + ',' + (centroid.y + rectH / 2);

  // Left
  result += 'L' + (centroid.x - rectW / 2) + ',' + centroid.y;

  // Close the shape
  result += 'Z';

  return result;
}

function drawRect(centroid) {
  // Start at the top left
  console.log(centroid);
  var result = 'M' + (centroid.x - rectW / 2) + ',' + (centroid.y - rectH / 2);

  // Go right
  result += 'h' + rectW;

  // Go down
  result += 'v' + rectH;

  // Left
  result += 'h-' + rectW;

  // Close the shape
  result += 'Z';

  console.log(result);
  return result;
}

var plusButton = svg
  .append('g')
  .classed('button', true)
  .classed('hide', true)
  .on('click', function() {
    console.log("hello");
    /*        addElement(selectedLink.source); */
    console.log("Clicked on Diamond");
    console.log("set hide to true");
    removeAllButtonElements();
  });

plusButton
  .append('rect')
  .attr('transform', 'translate(-8, -8)') // center the button inside the `g`
  .attr('width', 16)
  .attr('height', 16)
  .attr('rx', 2);

plusButton
  .append('path')
  .attr('d', 'M-6 0 H6 M0 -6 V6');

var rectangleShape = svg.append('g')
  .classed('conditionImage', true)
  .classed('hide', true)
  .on('click', function() {
    removeAllButtonElements();
  });

rectangleShape
  .append('rect')
  .attr('width', 30)
  .attr('height', 20)
  .style('fill', 'orange');

var diamondImage = svg.append('g')
  .classed('conditionSvg', true)
  .classed('hide', true)
  .classed('scale', true)
  .on('click', function() {
    console.log("Clicked on Diamond");
    console.log("set hide to true");
    addElement(selectedNode, 'True');
    removeAllButtonElements();
  });

diamondImage
  .append('path')
  .attr('d', 'M 15 0 30 15 15 30 0 15 Z')
  .style("fill", 'orange');

var rectangleShapeFalse = svg.append('g')
  .classed('conditionImage', true)
  .classed('hide', true)
  .on('click', function() {
    console.log("rectangle clicked");
    removeAllButtonElements();
  });

rectangleShapeFalse
  .append('rect')
  .attr('width', 30)
  .attr('height', 20)
  .style('fill', 'orange');

var diamondImageFalse = svg.append('g')
  .classed('conditionImage', true)
  .classed('hide', true)
  .classed('scale', true)
  .on('click', function() {
    console.log("Clicked on Diamond");
    console.log("set hide to true");
    addElement(selectedNode, 'False');
    removeAllButtonElements();
  });

diamondImageFalse
  .append('path')
  .attr('d', 'M 15 0 30 15 15 30 0 15 Z')
  .style("fill", 'orange');

function removeAllButtonElements() {
  plusButton.classed('hide', true);
  diamondImage.classed('hide', true);
  rectangleShape.classed('hide', true);
  diamondImageFalse.classed('hide', true);
  rectangleShapeFalse.classed('hide', true);
}

// draw elements end ..
.node {
  cursor: pointer;
  outline: none !important;
}

.node text {
  font: 10px sans-serif;
}

.button>path {
  stroke: blue;
  stroke-width: 1.5;
  /*   outline: none;  */
}

.button>rect {
  fill: #ddd;
  stroke: grey;
  stroke-width: 1px;
}

.conditionalSvg {
  /*   outline: none; */
  display: none;
}

.hide {
  /*    display: none;  */
  opacity: 0 !important;
  /*  pointer-events: none;  */
}

.link:hover {
  outline: none !important;
  cursor: pointer;
  stroke-width: 3px;
}

.link path {
  /*   outline: none !important;  */
  fill: none;
  stroke: darkgray;
  stroke-width: 2px;
}

.link path:hover {
  cursor: pointer;
  stroke-width: 4px;
}

.link text {
  font: 10px sans-serif;
}

.colorBlue {
  background-color: blue;
}


text:
Q: connect apache druid with prometheus and druid-exporter I have a Apache Druid database and I want to monitor Apache Druid database with Prometheus.
I research and found Druid Exporter support Prometheus collect metrics from Apache Druid
and I found document as below:
https://github.com/opstree/druid-exporter
I install everything in docker.

Follow guideline, I set in file common.runtime.properties of druid:
> druid_emitter_http_recipientBaseUrl=http://<druid_exporter_url>:<druid_exporter_port>/druid
> druid_emitter=http

Replace
http://<druid_exporter_url>:<druid_exporter_port>/druid

With
http://druid.opstreelabs.in:9091/druid

After that I run druid-exporter with command:
docker run -itd --name druid-exporter -p 9091:9091 -e DRUID_URL="http://druid.opstreelabs.in" -e PORT="9091" opstree/druid-exporter:v0.10

I finally, I edit prometheus.yml file with:
- job_name: 'druid'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:9091']

After run prometheus on port 9090, I received targets at bellow:

Please help me to resolve it. Thank you!

A: I think that all the steps you ran are fine but seems that the exporter is not running normally (this often happens when the 9091 port is being used elsewhere).
Anyway, you should check the logs via:
docker logs -f druid-exporter

and then see what happened.

If the exporter is executed normally, you can see the following logs.
time="2021-08-25T03:35:52Z" level=info msg="Druid exporter started listening on: 9091"
time="2021-08-25T03:35:52Z" level=info msg="Metrics endpoint - http://0.0.0.0:9091/metrics"
time="2021-08-25T03:35:52Z" level=info msg="Druid emitter endpoint - http://0.0.0.0:9091/druid"


text:
Q: What happens when we call pg_dump while users are still using the system? We have a web application with PostgreSQL as our database and use celery background tasks for somewhat complex task. At the very beginning of this complex task we take a backup of the database using pg_dump.
I was wondering about the state of this sql dump if the users are still using the system. Could it cause any inconsistencies ?
Also, I would like to know if pg_dump is the best choice for taking backups in this case. Of course as the database grows the backup takes a lot of time which slows the overall process.
Thanks.

A:
I was wondering about the state of this sql dump if the users are still using the system

pg_dump relies on PostgreSQL's MVCC support to ask PostgreSQL to take a snapshot of the database state at a given point in time.
Changes made by concurrent transactions after the point where pg_dump gets its snapshot do not affect pg_dump, whether they're committed or not.
There are a few things that aren't necessarily consistent, like sequences, which continue to increase while pg_dump is running. But applications have to be prepared for gaps in sequences anyway, so this isn't considered to be a problem.

Also, I would like to know if pg_dump is the best choice for taking backups in this case

No, you're way better off using WAL archiving and PITR for your purpose. Look into PgBarman and read the docs on continuous archiving.
You should still take logical dumps for disaster recovery, but it need not be an all-the-time thing.


text:
Q: TikZ intersection problem with PWM signal generation Consider the MWE of a PWM signal generation based on this question.
\documentclass[tikz, border=6mm]{standalone}

\usetikzlibrary{intersections}

\begin{document}
\newcommand{\step}{.25}
  \begin{tikzpicture}[>=latex]
    \draw [->] (0,-1.4) -- ++(8,0) node [right] {$t$};
    \draw [->] (0,-1.4) node [left] {$0$} -- ++(0,3) ;
    \draw [name path=sawtooth, line width=0.1pt,line join=miter]
      \foreach \x in {0,\step,...,6} {
        % (\x,1.0) -- ++(0,-2.0) -- ++(\step,2.0) % y domain = -1.0 -- 1.0
        (\x,1.4) -- ++(0,-2.8) -- ++(\step,2.8) % y domain = -1.4 -- 1.4
      };

      \draw [red,smooth, domain=0:2*pi, name path global=wave-1,line width=0.1pt] plot ({\x},{sin((\x+0) r)}) node [below right, font=\scriptsize] {$sig_1$};
      \draw [blue,name intersections={of={wave-1} and sawtooth, total=\n}]
        \foreach \i [remember=\i as \lasti (initially 1)] in {2,...,\n} {
         \ifodd\i {}
          \else
            (intersection-\lasti |- 0,-2*1) rectangle (intersection-\i |- 0,-3)
          \fi
        };
      \draw [->] (0,-3) -- ++(8,0) node [right] {$t$};
      \draw [->] (0,-3) node [left] {0} -- ++(0,1.2) ;

  \end{tikzpicture}
\end{document}

This MWE compiles correct and the generated PWM signal is also correct. Of course, I want the sawtooth signal to be in the y domain (-1.0,1.0) so that the PWM signal is maximal and minimal. But if I
compile the MWE with that y domain, Tikz fails to determine the intersections correctly. I made the sawtooth and sine wave with ultra thin lines but no success.
Can someone shed a light on the capabilities of the determination of the intersections in this particular case?

A: If the red signal is very close to the outer ends of the sawtooth signal at an intersection, TikZ finds only one instead of two intersections. Therefore, you may want to split the sawtooth path into two, a vertical and a diagonal one. (BTW, it is sometimes safer to work with "fake straight lines" when one wants to sort intersections, see this answer.)
\documentclass[tikz, border=6mm]{standalone}

\usetikzlibrary{intersections}

\begin{document}
\newcommand{\step}{.25}
  \begin{tikzpicture}[>=latex]
    \draw [->] (0,-1.4) -- ++(8,0) node [right] {$t$};
    \draw [->] (0,-1.4) node [left] {$0$} -- ++(0,3) ;
    \draw [name path=sawtooth vert, line width=0.1pt,line join=miter]
      \foreach \x in {0,\step,...,6} {
        (\x,1.0) to[bend left=0] ++(0,-2.0)  % y domain = -1.0 -- 1.0
        %(\x,1.4) -- ++(0,-2.8) -- ++(\step,2.8) % y domain = -1.4 -- 1.4
      };
     \draw [name path=sawtooth diag, line width=0.1pt,line join=miter]
      \foreach \x in {0,\step,...,6} {
       (\x,-1.0) to[bend left=0] ++(\step,2.0)};
      \draw [red,smooth, domain=0:2*pi, name path global=wave-1,line width=0.1pt] plot ({\x},{sin((\x+0) r)}) node [below right, font=\scriptsize] {$sig_1$};
      \path  [name intersections={of={wave-1} and {sawtooth diag}, name=x, total=\n}]
         \pgfextra{\typeout{\n\space intersections\space in\space vert}};
      \draw [blue,name intersections={of={wave-1} and {sawtooth vert}, total=\n}]
      \pgfextra{\typeout{\n\space intersections}}
        \foreach \i [remember=\i as \lasti (initially 1)] in {2,...,\n} {
%          \ifodd\i {}
%           \else
            (x-\lasti |- 0,-2*1) rectangle (intersection-\i |- 0,-3)
%          \fi
        };
      \draw [->] (0,-3) -- ++(8,0) node [right] {$t$};
      \draw [->] (0,-3) node [left] {0} -- ++(0,1.2) ;

  \end{tikzpicture}
\end{document}


text:
Q: SQL Use Result from one Query for another Query This is an excerpt from one table:
| id | type    | other_id | def_id | ref_def_id|
| 1  | int     | NULL     |  5     | NULL     |
| 2  | string  | NULL     |  5     | NULL     |
| 3  | int     | NULL     |  5     | NULL     |
| 20 | ref     | 3        |  NULL  | 5        |
| 21 | ref     | 4        |  NULL  | 5        |
| 22 | ref     | 5        |  NULL  | 5        |

What I want is to find entries with type ref. Then I would for example have this one entry in my result:
| 22 | ref     | 5        |  NULL  | 5        |

The problem I am facing is that I now want to combine this entry with other entries of the same table where def_id = 5.
So I would get all entries with def_id = 5 for this specific ref type as result. I somehow need the output from my first query, check what the ref_def_id is and then make another query for this id.
I really have problems to understand how to proceed. Any input is much appreciated.

A: use below query to get column from sub query.
select a.ref_def_id
from (select ref_def_id from YourTable where type='ref') as a;

A: If I understand correctly you need to find rows with a type of 'ref' and then use the values in their ref_def_id columns to get the rows with the same values in def_id. In that case you need to use a subquery for getting the rows with 'ref' type and combine it using either IN or EXISTS:
select *
from YourTable
where def_id in (select ref_def_id from YourTable where type='ref');

select *
from YourTable
where exists (select * from YourTable yt
  where yt.ref_def_id=YourTable.def_id and yt.type='ref')

Both queries are equivalent, IN is easier to understand at first sight but EXISTS allow more complex conditions (for example you can use more than one column for combining with the subquery).
Edit: since you comment that you need also the id from the 'ref' rows then you need to use a subquery:
select source_id, YourTable.*
from YourTable
join (select id as source_id, ref_def_id
      from YourTable
      where type='ref')
as refs on refs.ref_def_id=YourTable.def_id
order by source_id, id;

With this for each 'ref' row you would get all the rows with the associated ref_id.

A: What you are looking for is a subquery or even better a join operation.
Have a look here: http://www.mysqltutorial.org/mysql-left-join.aspx
Joins / the left join allows you to combine rows of tables within one query on a given condition. The condition could be id = 5 for your purpose.

A: You would seem to want aggregation:
select max(id) as id, type, max(other_id) as other_id,
       max(def_id) as def_id, ref_def_id
from t
where type = 'ref'
group by type, ref_def_id


text:
Q: MySQL Query with 3 AND I'm trying to get from database many fields to check user account.
On form, user fill in code, pass and email.
I need to check if user code exist, if password is correct, if email is correct and user have level 1 or 2 to go ahead.
I'm trying with query below, but i'm redirected to error page.
Where do I wrong?
$sql = "SELECT * FROM users WHERE (`user_code` = '". $user_code ."')
                              AND (`user_pass` = '". $user_pass ."')
                              AND (`user_email` = '". $user_email ."')
                              AND ((`user_level` = '1') OR (`user_level` = '2'))
                              LIMIT 1";

$query = mysql_query($sql);
    if (mysql_num_rows($query) != 1) {
        header("Location: index.php?message=error"); exit;


text:
Q: How do I collect all the οbjects created from abstract class in a arraylist How do I collect all the οbjects created from abstract class in a arraylist?
Here is what i've tried so far :
package exercice3;

import java.util.ArrayList;
import java.util.List;

public abstract class Personne {

    protected String nom ;
    protected String prenom ;
    protected String adresse ;
    protected static int nbPersonnes = 0 ;
    List<Personne> ListePersonnes = new ArrayList <>();

    public Personne(String nom , String prenom , String adresse) {

        this.nom= nom ;
        this.prenom = prenom ;
        this.adresse = adresse ;
        nbPersonnes++;
        ListePersonnes.add(nbPersonnes, );
    }
}

A: public abstract class Personne {

    protected String nom ;
    protected String prenom ;
    protected String adresse ;
    protected static int nbPersonnes = 0 ;
    static List<Personne> ListePersonnes = new ArrayList<>();

    public Personne(String nom , String prenom , String adresse) {

        this.nom= nom ;
        this.prenom = prenom ;
        this.adresse = adresse ;
        nbPersonnes++;
        ListePersonnes.add(this);  // <== use 'this' keyword

    }
 }


text:
Q: How can I add a test-environment route dynamically? i would like to add a route that is only available in test environment, so i would prefer not to pollute routes.rb file. i cannot seem to find a working way to add a route dynamically after original routes were drawn. i tried this https://gist.github.com/1351762 but that didn't quite work
How can I add a new route after routes.rb has already loaded and processed all the routes?

A: The with_routing test helper redefines routes within a block.
 with_routing do |map|
   map.draw do
    resources :test, only: [:show]
   end

   get :show
   assert assigns(:test)
 end

A: After some tries and errors, I found that:
Rails.application.routes.eval_block(Proc.new do
  get "/backdoor", :to => "backdoors#backdoor"
end)


text:
Q: Can we have image sliderview and icons in one activity? I am trying to  write code for an activity which looks like this image. On top of my screen I want an image sliderview along with some icons below the sliderview as shown in the picture. How do I do this?
.

A: This is what I've done as tutorial for one app: I've loaded the images on the center, and I change them not with pointers but with 'Go' and 'Back' buttons inside a RelativeLayout for moving the images, but you can chage it as you want. I have a centered button with 'Finish' and a label with one title in the bottom.
As you'll see this is a example with no previews or icons, but maybe this is a code from what you can start your own.
The tutorial.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Notificacion" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/button3"
    android:layout_below="@+id/RelativeLayout1"
    android:layout_marginTop="4dp"
    android:src="@drawable/guia1" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/img1"
    android:textColor="#000000"
    android:textSize="15sp" />

<RelativeLayout
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/transparent"
        android:paddingLeft="6dp"
        android:text="@string/back"
        android:textColor="#088A08"
        android:textSize="15sp" />

    <Button
        android:id="@+id/button_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/transparent"
        android:paddingRight="8dp"
        android:text="@string/next"
        android:textColor="#088A08"
        android:textSize="15sp" />

</RelativeLayout>

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:background="@android:color/transparent"
        android:onClick="back"
        android:text="@string/fin"
        android:textColor="#088A08"
        android:textSize="12sp" />
</RelativeLayout>

And my class is named Tutorial.java, that implements OnClickListener. Here I load the several images from the drawable folder and one text for each one.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class Tutorial extends Activity implements OnClickListener{

ImageView foto;
TextView tv;
int[] fotoId = {R.drawable.yourimage01, R.drawable.yourimage02, R.drawable.yourimage03, R.drawable.yourimage04, R.drawable.yourimage05, R.drawable.yourimage06, R.drawable.yourimage07};
String[] textos = {"Text for image 01", "Text for image 02", "Text for image 03", "Text for image 04", "Text for image 05", "Text for image 06", "Text for image 07",};
int i = 0;
int total;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tutorial);

    Button next= (Button) findViewById(R.id.button_next);
    Button back= (Button) findViewById(R.id.button_back);
    next.setOnClickListener(this);
    back.setOnClickListener(this);

    tv = (TextView) findViewById(R.id.textView1);
    foto = (ImageView) findViewById(R.id.imageView1);
    total = fotoId.length;
}

@Override
public void onClick(View view) {

    int id = view.getId();
    if(id == R.id.button_back) {
        i++;
        if(i == total){
            i = 0;
        }
    }

    if(id == R.id.button_next) {
        i--;
        if(i == -1){
            i = total -1;
        }
    }
    foto.setImageResource(fotoId[i]);
    tv.setText(textos[i]);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void back(View view) {
    Intent i = new Intent(this, Indice.class );
    startActivity(i);
  }
}

Hope it helps.

A: I suggest to use this library for your purpose. Just add its dependency and set it for top of tour activity then fill the rest with icons or everthing else you want.


text:
Q: Binding inside listbox itemtemplate problems I have two separate binding problems with listboxes with an itemtemplate which contains a texbox.
1) One listbox binds to a list of strings. How can I display each string inside the textboxes created and allow two way binding at the same time? Two way binding isn't allowed without specifying a Path or XPath.
<ListBox Height="231" HorizontalAlignment="Left" Margin="0,167,0,0" Name="listBoxKeys" VerticalAlignment="Top" Width="219" ItemsSource="{Binding Path=SelectedPlatform.Keys}" SelectedItem="{Binding Path=SelectedKey,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
         <ListBox.ItemTemplate>
              <DataTemplate>
                  <StackPanel Orientation="Horizontal" Margin="0,0,0,0">
                     <TextBox Text="{Binding Mode=OneWay}" Margin="0,0,0,0" Height="Auto" MinWidth="80" MaxWidth="80" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                   </StackPanel>
               </DataTemplate>
          </ListBox.ItemTemplate>
 </ListBox>

And 2) I use another listbox which binds to some generic list of a custom KeyValuePair class. The itemtemplate contains a textbox and combobox. The textbox text is bound to the key property of each KeyValuePair object and the combobox selecteditem to the value property. My problem is that I want the combo to get filled by a list of strings declared in my viewmodel which will be changing on runtime. The window's datacontext is the viewmodel where the list is declared. I don't know the exact syntax I need to use to bind the combobox itemssource there. Here's my code :
<ListBox Height="393" HorizontalAlignment="Left" Margin="0,72,0,0" Name="listBoxActions" VerticalAlignment="Top" Width="254" ItemsSource="{Binding Path=SelectedPlayer.ControlProfile.MappedActions}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal" Margin="0,0,0,0">
          <TextBox Text="{Binding Key, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Margin="10,0,0,0" Height="Auto" MinWidth="80" MaxWidth="80" HorizontalAlignment="Left" VerticalAlignment="Center"/>
          <ComboBox Margin="10,0,0,0" Height="Auto" MinWidth="80" MaxWidth="80" HorizontalAlignment="Left" VerticalAlignment="Center" ItemsSource="{Binding ?}" SelectedItem="{Binding Value, Mode=TwoWay}"/>
         </StackPanel>
        </DataTemplate>
       </ListBox.ItemTemplate>
</ListBox>

A: The problem is that the two-way binding on the source itself cannot work because it would mean that the whole object (string), for which the data template is created, must be replaced when user changes the text in the text box. Obviously, this will not work. Two-way binding will work only on a writable property of the bound object.
In your case I would suggest creating a view model for the items in the list box (basically a view model for your strings) and expose a Value property on it and bind to it in the data template:
<ListBox Height="231" HorizontalAlignment="Left" Margin="0,167,0,0"
         Name="listBoxKeys" VerticalAlignment="Top" Width="219"
         ItemsSource="{Binding Path=SelectedPlatform.KeyViewModels}"
         SelectedItem="{Binding Path=SelectedKey,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
        <ListBox.ItemTemplate>
             <DataTemplate>
                 <StackPanel Orientation="Horizontal" Margin="0,0,0,0">
                    <TextBox Text="{Binding Value, Mode=TwoWay}" Margin="0,0,0,0" Height="Auto" MinWidth="80" MaxWidth="80" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                  </StackPanel>
              </DataTemplate>
         </ListBox.ItemTemplate>
</ListBox>

A: 1) Pavlo Glazkov seems to have a good answer to me
2) This is down to the DataContext for the ComboBox now being the key value pair rather than the ViewModel. There may be other ways to do this but the one that I've used before is to set the bindings RelativeSource source back to it's parent ItemsControl.
RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}

Something like:
<ListBox Height="393" HorizontalAlignment="Left" Margin="0,72,0,0" Name="listBoxActions" VerticalAlignment="Top" Width="254" ItemsSource="{Binding Path=SelectedPlayer.ControlProfile.MappedActions}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal" Margin="0,0,0,0">
          <TextBox Text="{Binding Key, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Margin="10,0,0,0" Height="Auto" MinWidth="80" MaxWidth="80" HorizontalAlignment="Left" VerticalAlignment="Center"/>
          <ComboBox Margin="10,0,0,0" Height="Auto" MinWidth="80" MaxWidth="80" HorizontalAlignment="Left" VerticalAlignment="Center" ItemsSource="{Binding DataContext.Keys,  RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" SelectedItem="{Binding Value, Mode=TwoWay}"/>
         </StackPanel>
        </DataTemplate>
       </ListBox.ItemTemplate>
</ListBox>


text:
Q: How to set the enable property to a highcharts line in page load If you want to understand my requirement , first you have to see this demo highcharts demo
. Now click on Tokyo from that demo chart, that tokyo line will be dissappear. Now I want to able to set that property in page load, I mean whenever the page is loaded, the tokyo link should be clicked and only one line should display, when I click on Tokyo then the tokyo line should display. You can find the source code from that demo itself Thank you in advance.

A: When creating chart, just set series.visible = false for series which should be hidden by default.
See docs.

A: I think what you are after is a way to make only the clicked legend series show. If that is the case you can do it with the plotOptions.series.events.legendItemClick. To have only one series show up initially on the chart (but still show in the legend) you need to set that series' visible property to true and the others to false. If you want to have all series show on initial load that step can be ignored.
To get the toggle working you need to get the index of the legend item you clicked. You then loop through all the series in your chart to find the one that matches that clicked index. When it matches you set series\[i\].show() for the ones that don't you set series.hide().
Here is the basic toggling code:
series: {
    events: {
        legendItemClick: function (event) {
            var seriesIndex = this.index;
            var serie = this.chart.series;
            console.log(seriesIndex);
            for (i = 0; i < serie.length; i++) {
                if (serie[i].index == seriesIndex) {
                    serie[i].show();
                    console.log(serie[i].index);
                } else {
                    serie[i].hide();
                }
            }
            return false;
        }
    }
}

And here is a live fiddle.


text:
Q: How do I check to see if an apt lock file is locked? I am writing a script to do some apt commands, but I am running into potential issues of the apt/dpkg databases being locked so my script bails.  I want to check the lock files (i.e. /var/lib/dpkg/lock) before doing anything just like apt does when it runs its command, but I can't figure out how apt is performing the lock.
The lock file is always there, and apt-get is not doing a flock on the file.  How else would it be checking to see if it is in use?  From an strace I see that apt-get opens the file, but that is it.  In my script, I can open the file while apt-get has it open as well.

A: Well I thought there would be a simple answer here but I can't find anything.  First, are you 100% sure that lock file is always there?  Try running
lsof /var/lib/dpkg/lock

as root to see if any process has it open.
From what I've read, apt-get does an fcntl lock, but I haven't looked at the code to verify. I guess that wuld explain why the file is there all the time, apt just locks it as needed.
What about just doing a check of the process list when your script runs, and exiting if apt is running at the same time?  Would that be sufficient for your use?
Looks like this person went down the same path as you did, without much success.

A: I came here looking for a solution similar to what gondoi ended up using but written in Python instead of Ruby. The following seems to work well:
import fcntl

def is_dpkg_active():
    """
    Check whether ``apt-get`` or ``dpkg`` is currently active.

    This works by checking whether the lock file ``/var/lib/dpkg/lock`` is
    locked by an ``apt-get`` or ``dpkg`` process, which in turn is done by
    momentarily trying to acquire the lock. This means that the current process
    needs to have sufficient privileges.

    :returns: ``True`` when the lock is already taken (``apt-get`` or ``dpkg``
              is running), ``False`` otherwise.
    :raises: :py:exc:`exceptions.IOError` if the required privileges are not
             available.

    .. note:: ``apt-get`` doesn't acquire this lock until it needs it, for
              example an ``apt-get update`` run consists of two phases (first
              fetching updated package lists and then updating the local
              package index) and only the second phase claims the lock (because
              the second phase writes the local package index which is also
              read from and written to by ``dpkg``).
    """
    with open('/var/lib/dpkg/lock', 'w') as handle:
        try:
            fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return False
        except IOError:
            return True

A: From a shell script (see flock(1)):
flock --timeout 60 --exclusive --close /var/lib/dpkg/lock apt-get -y -o Dpkg::Options::="--force-confold" upgrade
if [ $? -ne 0 ]; then
  echo "Another process has f-locked /var/lib/dpkg/lock" 1>&2
  exit 1
fi

A: I found out that apt is using a fcntl.  Since I am using Ruby for the scripting language, I had to create my own function to look for lock.  The reason for this, is because Ruby does not implement the fcntl function entirely.  It only provides the function call and constants.  The ability to build flock structs and how to pass them is left out or not documented.
Here is the list I found talking about that.
Here is the function I ended up writing:
def flocked? &block
  flockstruct = [Fcntl::F_RDLCK, 0, 0, 0, 0].pack("ssqqi")
  fcntl Fcntl::F_GETLK, flockstruct
  status = flockstruct.unpack("ssqqi")[0]
  case status
    when Fcntl::F_UNLCK
      return false
    when Fcntl::F_WRLCK|Fcntl::F_RDLCK
      return true
    else
      raise SystemCallError, status
  end
end


text:
Q: Startup error Part::partw When I started mathematica, this message popped up.
Part::partw: Part 5 of PacletManager`Utils`Private`$taskData[2] does not exist.

Does anyone know what this is? My version is mma 11.2.

A: We believe this should be fixed in Mathematica 12.0. We were never able to reproduce this internally so we're not completely sure about this, though. Please let us know if this continues to happen in 12.0 for you.

A: If you encounter this message at the MMA's startup, please check init.m located in %AppData%\Mathematica\FrontEnd. I solved the same problem (I use MMA 11.3) just by deleting entire text/commands in the %AppData%\Mathematica\FrontEnd\init.m file. This init.m is automatically initialized at every system startup and automatically updated by the MMA. Backup the file before deleting any text/commands in this initialization file.


text:
Q: VMWare Workstation not opening anymore After some Windows 10 upgrades (I don't know exactly which ones), my VMWare Workstation 15.0.4 just doesn't open anymore.
I click on it and nothing happens, not even an error message ...
I researched some articles but found nothing conclusive.
Repaired VMware, uninstalled, upgraded version, but nothing changed.
Does anyone have any ideas?

A:
After some Windows 10 upgrades (I don't know exactly which ones), my VMWare Workstation 15.0.4 just doesn't open anymore.

VMWare Workstation 15.1 and earlier is not compatible with Windows 10 version 1903.  You will need to upgrade to VMWare Workstation 15.5 to resolve your problem.

Does anyone have any ideas?

You must have not installed VMWare Workstation 15.5 when you attempted to reinstall or upgrade WMWare Workstation.


text:
Q: Ingress with single service on docker on mac Completely new do K8s here, I'm trying to deploy/connect Ingress to a sample single service on docker for local (docker for mac) and be able to hit it to run the service
1- sample service looks like this (my_service.js) :
const express = require('express')
let app = express()

app.get('/', (req, res) => {
    res.send('Hello service')
})

const PORT = process.env.PORT || 9000
app.listen(
    PORT,
    () => console.log('Listening')
    )

and I build the image (with a docker file):
docker build . -t sample-service-image

2- Now from K8s perspective:
here's the deployment file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sample-service
  labels:
    app: sample-service
spec:
  replicas: 1
  selector:
    matchLabels:
      app: sample-service
  template:
    metadata:
      labels:
        app: sample-service
    spec:
      containers:
      - name: sample-service
        image: sample-service-image
        imagePullPolicy: Never
        ports:
        - containerPort: 9000

kubectl apply -f deployment.yaml

and expose it as a service:
kubectl expose deploy sample-service --type=NodePort

3- Now from Ingress (ingress-sample.yaml) :
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-sample
spec:
  backend:
    serviceName: sample-service
    servicePort: 80

kubectl create -f ingress-sample.yaml

[UPDATE] I deployed an ingress controller from here:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/provider/baremetal/service-nodeport.yaml

this is what I get
$kubectl get ingress
NAME             HOSTS   ADDRESS     PORTS   AGE
ingress-sample   *       localhost   80      8m

kubectl get services --all-namespaces | grep nginx
ingress-nginx   ingress-nginx    NodePort    10.106.47.48     <none>        80:31448/TCP,443:31512/TCP   2h

tried to hit it on http://localhost:31448/ but I get 503 from NGINX ... so I guess it's not properly connected to sample-service.
how should I hit Ingress to be able to call the sample-service?

A: You need to specify Host header while hitting your service. For example
curl -H "HOST: abc" http://localhost:31448/

Since your ingress definition did not specify any host configuration, you can pass any value.
For more information - see.