text:
Q: Factory Pattern: Determining concrete factory class instantiation? I'm trying to learn patterns and I'm stuck on determining how or where a Factory Pattern determines what class to instanciate.  If I have a Application that calls the factory and sends it, say, an xml config file to determine what type of action to take, where does that logic for interpreting the config file happen?
THE FACTORY
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myNamespace
{
    public abstract class SourceFactory
    {
        abstract public UploadSource getUploadSource();
    }
    public class TextSourceFactory : SourceFactory
    {
        public override UploadSource getUploadSource()
        {
            return new TextUploadSource();
        }
    }
    public class XmlSourceFacotry : SourceFactory
    {
        public override UploadSource getUploadSource()
        {
            return new XmlUploadSource();
        }
    }
    public class SqlSourceFactory : SourceFactory
    {
        public override UploadSource getUploadSource()
        {
            return new SqlUploadSource();
        }
    }
}

THE CLASSES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myNamespace
{
    public abstract class UploadSource
    {
        abstract public void Execute();
    }
    public class TextUploadSource : UploadSource
    {
        public override void Execute()
        {
            Console.WriteLine("You executed a text upload source");
        }
    }
    public class XmlUploadSource : UploadSource
    {
        public override void Execute()
        {
            Console.WriteLine("You executed an XML upload source");
        }
    }
    public class SqlUploadSource : UploadSource
    {
        public override void Execute()
        {
            Console.WriteLine("You executed a SQL upload source");
        }
    }
}

A: The actual factory to instantiate is selected at runtime, often by a separate factory loader class. The loader may get the necessary configuration, e.g. in an xml config file, and read from it the class name of the concrete factory to load.
This in itself is not a very complicated logic; the reason to put it into a factory loader class is reusability. You can have many factories in your app, and often, most of the factory loading code is pretty similar, so putting it into a separate class (hierarchy) eliminates code duplication. And of course, the logic may be different and more complicated than this example.
E.g. a more dynamic scenario would be to specify a mapping between buttons / menu items and class names in the xml file, then on the GUI, the user could change the factory to be used by pressing a button / selecting a menu item.


text:
Q: C++ Application behaves differently from code I am writing a game in C++ using MS Visual Studio 2010. The game is almost at beta state but I'm facing a serious problem here, hopefully someone will be able to help.
So, if I run the game from VS (e.g. with F5 key) everything works perffect. But as soon as I run the newly compiled .exe file of the same game at some points in game I get crashes and some other strange things happen. Is there something I can do to fix it? Is there maybe a certain setting in VS? It's really confusing me, please help if someone knows a solution.

A: If I remember correctly the F5 key is used to start debugging, and when running in a debugger Visual Studio does things that does not happen when not running in a debugger.
First and foremost the debugger will clear all memory for you, meaning things like uninitialized variables becoming zero. This clearing include uninitialized pointer variables being initialized as null pointers.
If you have uninitialized pointer variables and have null-pointer checks for them, those checks will work fine when running in the debugger, but when not running in a debugger those variables will have an indeterminate value, a value that will be seemingly random and most likely not a null pointer. Thus when you run outside the debugger those non-null pointers will make your program think the pointers are valid and you will dereference them which will lead to undefined behavior.
What you need to do is to go through your code and look for uninitialized variables, especially pointers, and make sure they are properly initialized before you use them.

Like other mention, there are also many other things that can go wrong when running in a different environment than the Visual Studio debugger or by starting the program from Visual Studio. One major problem mentioned is that relative file paths may not be correct any more. The programs working directory when run from the command line at a different directory, or when running by double-clicking its icon, will be different than when started from withing Visual Studio. Having some sort of configuration-value stating things like a base-directory for game assets and other files you need is a good idea. Then you can change the process current working directory to that, or use it to resolve the absolute path for your assets yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tools for geospatial data visualization with custom 3D models I need a tool that does geospatial data visualization, but which will also allow me to import, or to create custom 3D models (e.g. to import .gltf files).
Kepler.gl seems a great choice for geospatial data visualization, yet I couldn't find the way to import certain .gltf file and I am not sure this is even possible in kepler.gl.
Any recommendations?

A: Have you explored the latest version of threebox?? It enables you to add as many models and 3D layers as you want on top of Mapbox using their support for 3D objects through CustomLayerInterface with only a few lines of code
    map.on('style.load', function () {
        map.addLayer({
            id: 'custom_layer',
            type: 'custom',
            renderingMode: '3d',
            onAdd: function (map, mbxContext) {

                window.tb = new Threebox(
                    map,
                    mbxContext,
                    { defaultLights: true }
                );

                var options = {
                    obj: '/3D/soldier/soldier.glb',
                    type: 'gltf',
                    scale: 1,
                    units: 'meters',
                    rotation: { x: 90, y: 0, z: 0 } //default rotation
                }

                tb.loadObj(options, function (model) {
                    soldier = model.setCoords(origin);
                    tb.add(soldier);
                })

            },
            render: function (gl, matrix) {
                tb.update();
            }
        });
    })

And you can do much more...
- 3D models built-in and custom animations

- Full raycast support MouseOver/Mouseout, Selected, Drag&Drop, Drag&Rotate, Wireframe

- CSS2D Tooltips and Labels that consider altitude

- Three.js and Mapbox cameras sync with depth adjustment

- Include geolocated models of monuments with sunlight & shadows build-in support

- Optimized to load thousands of 3D objects


text:
Q: Issues while validating snapcraft.yaml: '/home/Desktop/xxx-snappy/folder/' is not of type 'object' the below is my snap file. Can you explain me how to use copy plugin. I just want to copy the file form one folder to another.
name: xxx
version: 6.0
# The vendor for the snap (replace 'Vendor <email@example.com>')
vendor: xxx@gmail.com
summary: a sample package
description: blah blah blah
icon: icon.png

parts:
 glue:
 plugin: copy
 source: /home/Desktop/xxx-snappy/folder/
 files:
 .: /bin/xxx

A: This looks like you're using snapcraft v1.x, is that correct? Assuming so, this YAML looks good except for the indentation within parts; it's not actually valid YAML. Try this:
name: xxxx
version: 6.0
# The vendor for the snap (replace 'Vendor <email@example.com>')
vendor: xxx@gmail.com
summary: a sample package
description: blah blah blah
icon: icon.png

parts:
  glue:
    plugin: copy
    source: /home/Desktop/xxx-snappy/folder/
    files:
      .: /bin/folder


text:
Q: The Sphere of Discrete Metric Space Let $(X,d)$ denotes the usual discrete metric space. Specify the spheres for $\epsilon = 1, \frac12, 2$.
I strictly used the definition of the sphere such that whenever the metric is not equal to epsilon then we get empty set (all red colors). Can anyone check my result to approve or disprove my results?
We find all the spheres, $\partial{B}_\epsilon(x)$, as follows
\begin{align*}
d(x,y) & = \left.
\begin{cases}
{\color{red}1} {\color{red}\not= {\color{red}2,}} & {\color{red}x \ \not={\color{red}y}} \\ {\color{red}0 \not= {\color{red}2},} &\  {\color{red}x = {\color{red}y}}
\end{cases}
\right\} = \emptyset,  \text{ for } \epsilon = 2, \ \partial B_\epsilon(x) = \emptyset.
 \\
d(x,y) &=  \left.
\begin{cases}
1 = 1, & x \ \not=y \\ {\color{red}{0 \not= 1}}, & {\color{red}{x = y}}
\end{cases}
\right\} =  \{x \not= y\}, \text{ for } \epsilon = 1, \ \partial B_\epsilon(x) = \{x \not= y\} = \{x,y\}.
 \\
d(x,y) = \epsilon & =  \left.
\begin{cases}
{\color{red}1} {\color{red}\not= {\color{red}{1/2},}} & {\color{red}x \ \not={\color{red}y}} \\ {\color{red}0 \not= {\color{red}{1/2}},} &\  {\color{red}x = {\color{red}y}}\end{cases}
\right\} =  \emptyset, \text{ for } \epsilon = 1/2, \ \partial B_\epsilon(x) = \emptyset.
\end{align*}

A: You should not be limiting yourself to just two points. For each $x\in X$ the sphere of radius $1$ about $x$ is $X\setminus\{x\}$: every point of $X$ except $x$ itself is at distance $1$ from $x$. The spheres of radius $2$ and radius $\frac12$ are therefore empty, since there is no point at distance $2$ or $\frac12$ from $x$.
The closed balls of radii $\frac12$, $1$, and $2$ around $x$, however, are $\{x\}$, $X$, and $X$, respectively, and the corresponding open balls are $\{x\}$, $\{x\}$, and $X$.

A: In the discrete metric, the spheres of radii $1$ and $2$ and center $\{x\}$ are equal to $X\setminus\{x\}$ and $\emptyset$ respectively.  The sphere of radius $1/2$ centered at $\{x\}$ is $\emptyset$.

A: The quantity $d(x,y)$ is a number, not a set. It does not make sense to write $d(x,y)=\cdots =\emptyset$. And the expression $\{x\ne y\}$ does not make any sense.

Recall the definition of sphere  of radius $r$ centered at $x$:
$$
\partial B(x,r)=\{y\in X: d(x,y)=r\}\tag{1}
$$
On the other hand, given any $x,y\in X$, $d(x,y)$ is either $0$ or $1$. So the set in (1) must be empty whenever $r\ne 1$ and $r\ne 0$.
For $r=1$, observe that $d(x,y)=1$ for every $y\ne x$ and thus
$$
\partial B(x,1)=\{y\in X: d(x,y)=1\}=\{y\in X: y\ne x\}=X\setminus\{x\}.
$$

A: Ok, although others have already pointed out, I will try to be direct and precise.
Sphere is defined as follows, for a metric space $(X,d)$:
$$s(x_o,r) = \{x \in X : d(x,x_o)=r\}$$
Radius $r >0$ and centered at $x_o$.
Discrete metric is the usual $$d(x,y) =1, x \neq y
\\  =0, x=y.$$
So, all the $x$ which have a distance $1$ from $x_o$ are precisely all the points in $S = X - \{x_o\}$. Now, any $r \neq 1$ means that the $x  \in X$ at a distance $r$ from $x_o$ does not exist because of the 'discreteness' of the metric. Hence, for any $r \neq 1$ the sphere will always be $\phi$.
If $r=0$ then sphere would be a singleton. Namely, the centre of the sphere i.e. $\{x_o\}$.


text:
Q: MVC: What is the difference between a model and a service? Why in some frameworks the logic layer is called "Model" whereas in some it is called "Service". Are they different from each other or just different by naming conventions?

UPDATE 1
The reason I'm asking is because in Zend Framework, a classical MVC framework, everybody uses the concept of Model. Now I'm learning AngularJS and it seems that the word Model disappeared and was replaced by the word service.
What I noticed is that a service is more like a singleton that can be reused again and again (example: a REST client) whereas a model is more related to the data manipulations coming from the controller in the MVC pattern.

A: According to my experience, the Model layer within the MVC design pattern refers to every software component involved with data manipulation (POJOs, DAO, all the way to SQL, JDBC, and so on).
Whereas the service layer is actually an addition to MVC:
We know that the Model layer components are invoked inside the Controller layer. Once the latter is built, you come to realize that it doesn't look concise (messy with dirty code); the Controller may not afford extra details (e.g. formatting request parameters before calling a DAO method that are going to consume them ...). Therefore, you might include this extra layer, namely the Service layer.
Eventually, you may encompass your dirty code inside static methods with a meaningful name, parameters and so forth, which would outcome a synthetic Controller layer.
Take a look at this link:
https://stackoverflow.com/questions/2762978/the-purpose-of-a-service-layer-and-asp-net-mvc-2

A: Model: Fields that belong to the object, methods that help to get/set data from the object (a fullname accessor that returns first + last name)
Service: Methods to perform operations with one or more models, see 'unit of work', transactions, etc...

Employee::create should just take a set of data, perform model validation if necessary, and return an Employee Object.
EmployeeService::hireEmployee might create the employee, send them a welcome email, create a mailbox, make them a sandwich, etc... it may return the set of data, or a result code, etc...

This can also affect validation:
Model Validation: Employee must have a id, first and last name, and birthday
Service Validation: Employees for the bartender position must be 21 or over, and approved by a manager.

A: Structurally these base classes are the same, however they are used to classify a different concerns of the Service and Model tiers of the MVCS implementation
Service:- A concrete service class defines the API of an external Service.

Model :- Defines the API of the applications data model.

So, whilst the base classes are alike, the concrete classes created by extending these base classes serve two entirely different purposes.


text:
Q: Control synergy programmatically I'm trying to toggle switchInDirection() from a window manager (dwm, written in c). As there seems to be no way to control synergy actions from the command line, I tried to fire appropriate key combinations from the wm.
Scenario: on super+,(comma) event, which is caught by the wm, it should fire another keycombo that synergys is listening for. For some reason XTestFakeKeyEvent (xlib function) didn't work at all, and simulating keypress with XSendEvent doesn't work with modifiers, so I had to make a system call to xdotool:
xdotool keyup comma key control+alt+shift+F11 // note the required comma key up;

It seems to work as a POC, but at some point it'll cause segfault in synergys. Note that triggering the same keycombo without xdotool does not result in segfault.
What, if any, options do I have?
Edit:
one obvious solution would be listening to the super+, event with synergy in the first place, and handling the logic there (whether switch screen or send another keycombo to dwm). This should work, but implies different dwm configurations for server and client, as super+, should still be handled by dwm in the client (otherwise controlling client via its native keyboard wouldn't work as expected).


text:
Q: What should be used in Flux/Mono to join couple items In JS promises you can use
Promise.join
But I couldn't find such solution for Flux/Mono. What is best practice when you deal with the different item then have to use them together later?

A: That depends on how you want to combine them.
Sequentially? Use Flux.concat
All in parallel? Use Flux.zip
If you expect only one result, Mono.zipWith might work for you.

A: There is a good number of 'merging operators'
zip, concat, merge, combineLatest are the main three.
Zip allows you to combine streams, where the items will be grouped in a 1-to-1 relationship within the stream. That is why you lost the last element.
When you are not sure about how numerous each stream will be and how often it will feed events you can use concat (add the other stream on the end of the first one), merge (where items are placed on the final stream in order of appearence from both streams), or combine latest (to mutate the two last events of each stream into something else).
Your case sounds like a merge to me.

A: After some changes, my code looks like this
public Mono<Item> createItem(final @NonNull String userName, String description, String[] tags,
                             @NonNull Flux<ImageDTO> photos) {
    val item = initItem(userName);
    item.setDescription(description);
    if (null != tags) {
        item.getTags().addAll(Arrays.asList(tags));
    }

    return photos.flatMap(photo -> imageService.storeImage(photo.getStream(), photo.getExt()))
        .reduce(item, (item1, photoIri) -> {
            item1.getPhotos().add(photoIri);
            return item1;
        })
        .flatMap(itemRepository::save)
        .flatMap(createdItem -> {
            val itemHistory = getHistoryForCreatedItem(userName, createdItem);
            return itemHistoryRepository.save(itemHistory).then(Mono.just(createdItem));
        });
}

Currently I don't like:

*

*.reduce(item, (item1, photoIri) ->

*.then(Mono.just(createdItem))


text:
Q: How to intercept AsQueryable() of mongodb c# driver 2.x? I have a wrapper class for IMongoCollection<T> Collection.
I expose a function for AsQueryable():
public virtual IQueryable<T> AsQueryable()
{
    return Collection.AsQueryable();
}

I need to intercept the execution of queries (start and end of the query)
e.g. to catch errors and general logging or log long queries execution times.
How can I achieve that?


text:
Q: How in Kotlin can I make function injectable and pass that function as function type to other functions? As in Kotlin function is considered data type also ,I'm wondering is it possible to make that function injectable and then can  I  pass that to other method.

What I mean is to make this function injectable
fn: (data) -> Component and then I will pass this to method

A: Yes you can reference a function using :: operator that will create a KFunction1<data, Component> which is considered as (data) -> Component or data.() -> Component in kotlin.
Example:
fun acceptLambda(block: (String) -> Unit) {
    block("Test")
}

// Create function having same argument and return type
// Both of them in same package won't work use either of these
fun String.t1() {
    println(this)
}
fun t2(s: String) {
    println(s)
}

// Call them, by passing the reference
test(String::t1) // Prints: Test
test(::t2)       // Prints: Test

Thing to be noted is that if you create an extension function as a member function in any class (just like t1) then it cannot be referenced, so I'll recommend using functions like t2 instead.
Here is more info about how to reference constuctors, or memeber functions.

A: Please have a look here.

Kotlin functions are first-class, which means that they can be stored
  in variables and data structures, passed as arguments to and returned
  from other higher-order functions. You can operate with functions in
  any way that is possible for other non-function values.

Example:
fun takeFunction(func: (Int) -> Component) {
  val component = func(1)
}

fun foo(data: Int) : Component = TODO()

fun main() {
  takeFunction({ if(it == 1) Component else error("wrong data") })
  takeFunction(::foo)
  takeFunction { foo(it) }
}


text:
Q: alternative to cvPyrSegmentation i've tried cyPyrSegmentation to segment a image in different parts.

cvPyrSegmentation(in, out,storage, contours, level, 80, 20);

the segmentation of the output is very good. So in my continued process i want to work with the position of the different segments. But now i notice that cvPyrSegmentation only save the rectangle coordinates and not the whole pixels from segments :/. But the rectangle is too unexact.
Does someone have an idea?
greeting

A: Okay,
now i've implemented a very fast segmentator which based on a weighted union graph(Effcient Graph-Based Image Segmentation). The results look awesome i think.


text:
Q: RAM/memory based databases I am looking for a RAM/memory based database, and these two seem to be interesting:

*

*SQLite

*Oracle Berkeley DB
Do you have any other suggestions?
I need more than one executable to be able to access the DB concurrently.
Thank you.

More details:
I want to use a database as a high level communication channel among executables, instead of using the file system or shared memory.
File system pros: persistent storage (I do not care about it in this project).
File system cons: slow; hardware stress (both for hard disk and SSD).
Shared memory pros: speed.
Shared memory cons: data size; non persistent storage; low level access.
RAM Database pros: speed; high level, query-like access.
RAM Database cons: data size; non persistent storage (not a problem in my case).

A: I see two competing/conflicting requirements:

RAM/memory based database

and

more than one executable to be able to access the DB concurrently

They are competing/conflicting because modern operating systems normally enforce strict segregation for RAM allocated to specific processes (there are exceptions, but in the main this holds).
One option here is to copy your database to a RAM disk. That would allow separate apps to treat the database as if it were a file. The downside here is that the contents of a RAM disk won't survive a reboot of the host machine, and so you need a very robust system to keep your database saved to a real hard disk as well.
But really, if you want multiple apps sharing the same db, you're much better off using a database server. Enforcing safe, concurrent access is one of two main reasons databases exist as distinct entities from flat file stores (the other is efficient joins).

A: SQLLite is single user (in practice) and embedded. That fails the "more than one executable to be able to access the DB concurrently" requirement.
Otherwise, all RDBMS are in memory once the data is loaded from disk so you can use any you want (SQL Server (not CE), MySQL, PostgreSQL, whatever).

A: Apache Derby or JavaDB may be worth a look too.
SQLite is pretty awesome provided you can live with the fact that only one user/process can write to the database at a time. Many processes/users can in fact read data and access the DB at the same time however (as mentioned by the SQLite FAQs).

A: Not sure what exactly you mean with "RAM/memory based database" but you can have a look at the Memory storage engine in MySQL.


text:
Q: wxWidgets and boost::thread? I want to use boost to do background networking stuff in a loop while wxWidgets processes the GUI. I just started using wxWidgets so my first idea was to just start in the thread with networking loop inside OnInit of the app, but that wasn't a really good idea as the ap cannot continue running as the thread stops it.
How does one use boost::thread for multithreading and wxWidgets library together?

A: you can start your networking part in OnInit() if you want but the listener needs to fork out to a different thread.having an io_service and at least one boost::thread that calls run on the io_service should do the trick.your network stuff will be carried on by the thread(s) calling io_service::run() and the master thread can return to doing wxWidgets stuff.


text:
Q: Replacing key-value pair in app.config using a batch file I have a app.config which looks something like this:
   <!-- Device Configuration goes here -->
         <DinoConfig Alpha="aaa" Beta="bbb" Gamma="ccc" Theta="">
      <Dino Zeta="ooo" Delta="hhh" Tau="rrr" Rho="ddd" />
    </DinoConfig>

Now I would like to change Beta to "yyy" and Gamma to "zzz" in DinoConfig Parent node using a batch file. Also i would like to change Key-Value Pair in child nodes (Dino).
The way i'm using the batch script currently:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "string=^<DinoConfig Alpha="nnn" Beta="mmm" Gamma="iii" Theta=""^>"
set "dir=%temp%" & set "file=Dino.config" & pushd "!dir!"
for /f "tokens=*" %%G in (%file%) do (set cstring=%%G
    if "!cstring:~6,8!"=="Beta" set "cstring=%%G"
    echo "!cstring!" | findstr /r /b /c:".*jjj.*" >nul 2>&1 && echo %string% || if defined cstring echo !cstring!
) >> %file:.config=_mod.config%
del %file% & ren %file:.config=_mod.config% %file% & popd
exit /b

Using this i'm changing Beta="bbb" and in next iteration i'm changing ="vvv" (it would be convinient if i can change both at once).

A: Script below works well for me. Replace dir and file values with your own, target file is saved in dir, batch file can run from a different folder:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "string=    ^<Dino DinoName="mmm" Key1="nnn" Key2="pqr" Key3="stu" /^>"
set "dir=%temp%" & set "file=app.txt" & pushd "!dir!"
for /f "tokens=*" %%G in (%file%) do (set cstring=%%G
    if "!cstring:~6,8!"=="DinoName" set "cstring=    %%G"
    echo "!cstring!" | findstr /r /b /c:".*jkl.*" >nul 2>&1 && echo %string% || if defined cstring echo !cstring!
) >> %file:.txt=_mod.txt%
del %file% & ren %file:.txt=_mod.txt% %file% & popd
exit /b

It outputs to file:
<DinoConfig Key1="abc" Key2="def" Key3="ghi" >
    <Dino DinoName="mmm" Key1="nnn" Key2="pqr" Key3="stu" />
    <Dino DinoName="vww" Key1="xyz" Key2="aaa" Key3="bbb" />
</DinoConfig>

Alternatively, you can modify and try the script snippet you posted in the question:
setlocal enabledelayedexpansion
for /f "tokens=*" %%i in ('findstr...

A: The code which worked for me:
@echo off &setlocal
set "search=jkl"
set "replace=mmm"
(for /f "delims=" %%i in ('findstr "^" "%""C:\App.config""%"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%""C:\NewApp.Config""%"
del c:\App.config & ren c:\NewApp.config App.config
set "search=mno"
set "replace=nnn"
(for /f "delims=" %%i in ('findstr "^" "%""C:\App.Config""%"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%""C:\NewApp.Config""%"
del c:\App.config & ren c:\NewApp.config App.config


text:
Q: Immersive limit of embeddings is injective on the interior? $\newcommand{\pl}{\partial}$
$\newcommand{\M}{\mathcal{M}}$
$\newcommand{\N}{\mathcal{N}}$
Let $\M,\N$ be smooth compact, connected, oriented manifolds of the same dimension. $\M$ can have a boundary.
Let $\,f_n:\M \to \N$ be a sequence of smooth orientation-preserving embeddings, which converges uniformly to a smooth immersion $f:\M \to \N$.
Is it true that $f|_{\M^o}$ is injective? ($\M^o$ is the interior of $\M$).


text:
Q: Odoo Webservices in PHP using XMLRPC I am using the Odoo web services in PHP via XMLRPC.
It is working well and showing up the data, however I want to decrease my workload using the (Odoo ACL) access rights to show and hide the data for different type of the users based on the role.
Is it possible to show the data based upon the user roles? If possible please give me the snippet of the code to do this. I just want to use the XMLRPC not the RIPCORD Library because whole my code is already worked and i use the XMLRPC for this.


text:
Q: Bonded devices do not appear in the connected devices list of settings on Android My Android application can call BluetoothAdapter's getBondedDevices method to retrieve a list of bonded BLE devices that I know have no names. However, if I look in settings -> connected devices, I don't see these devices appear in the settings UI. Therefore, I'm unable to "unbond" them. Any ideas on why these bonded devices wouldn't show up in the list? Could it be because these peripheral devices advertise with no names? I'm using Android 9.

A: In my phone (Android 10) I had to turn on "Show Bluetooth devices without names" in the developer options under "Networking".


text:
Q: How to append DTW clusterings results from tslearn into a pandas DataFrame I'm currently learning how to use the python package tslearn for time series clustering. I have time series for various products I would like to cluster together and used the following code:
# DBA-k-means
print("DBA k-means")
dba_km = TimeSeriesKMeans(n_clusters=n_clusters,
                          n_init=2,
                          metric="dtw",
                          verbose=False,
                          max_iter_barycenter=10,
                          random_state=1)
y_pred_dba_km = dba_km.fit_predict(X_train)
print("DBA silhoutte: {:.2f}".format(silhouette_score(X_train, y_pred_dba_km, metric="dtw")))

I then used the following code in order to create plots of each of the clusters:
for yi in range(n_clusters):
    plt.subplot(4, 3, yi+1)
    for xx in X_train[y_pred_dba_km == yi]:
        plt.plot(xx.ravel(), "k-", alpha=.2)
    plt.plot(dba_km.cluster_centers_[yi].ravel(), "r-")
    plt.xlim(0, 22)
    plt.ylim(0, .9)
    plt.text(0.55, 0.85,'Cluster %d' % (yi + 1),
             transform=plt.gca().transAxes)
    if yi == 1:
        plt.title("DBA $k$-means")

What I would like to do is create a DataFrame such that I have the name of each of my products in one column, with its corresponding Cluster Name/Number in another column. The names of each product is currently in a list called namesofMySeries.
I'm reading through the online documentation but can't seem to find a way to do this. Anyone aware of a good way of doing this?


text:
Q: String Boolean in Bash I'm trying to create a script that takes two parameters: a word and a character, then returns how many times the character appears in the word.
Here is my code:
#!/bin/bash
((counter=0))
for i in $1
do
if i == $2
then
((counter=counter+1))
fi

echo $counter
done

My script returns 1 every time. I'm only versed in python, so my bash syntax is poor. Thanks in advance.

A: You should try the following simple bash code
#!/bin/bash

for ((i=0; i<${#1}; i++)); do
    [[ $2 == ${1:$i:1} ]] && ((count++))
done

echo "There's $count occurrences of $2 in $1"

A: Given that you use Bash syntax,
grep -c "$2" <<<"$1"

For POSIX shell, you need to echo or (preferably) printf the string and pipe to grep.
The shell does not decompose a token into individual characters when you loop over it (and, some argue, neither should Python actually :-) -- for i in foo simply sets i to foo.


text:
Q: How can I deploy a fasttext model on google cloud? I just want to have a model I can reach via  REST API, and the model just has to be this :
import fasttext
ft = fasttext.load_model('pretrained model location')

But I want it to be on the Google Cloud platform because the model takes 7GB of RAM. How can I accomplish this?


text:
Q: Replacing text within a long URL using regex I am trying to setup a htaccess redirect, but I need some help with the writing regex expression. Here s what I am trying to get to:
Before: example.com/[wildcard1]/9-3/[wildcard2]/ref/[wildcard3]/[wildcard4]
After: example.com/[wildcard1]/wis/9-3/[wildcard2]/ref/[wildcard3]/[wildcard4]

A: Try Regex: ^([^\/]+)(\/9-3\/[^\/]+\/ref\/[^\/]+\/.+)$
Demo


text:
Q: 64bit atomicAdd in CUDA I have a problem using atomicAdd under CUDA 7. atomicAdd is defined for "int", "unsigned int" and "unsigned long long int" stating it uses "the 32 or 64 bit value".
In our code we use uint32_t and uint64_t for safety. However gcc defines this in the following way:
#if __WORDSIZE == 64
typedef unsigned long int   uint64_t;
#else
__extension__
typedef unsigned long long int  uint64_t;
#endif

So when I pass an uint64_t to atomicAdd it complains because it is not defined for "unsigned long int".
Is it save to assume uint64_t == long long int for CUDA compilation as stated in the programming guide?

A: To answer that for future reference:
There are 2 options: Either use a typedef to define 64 bit cuda types like:
typedef long long int int64_cu
typedef unsigned long long int uint64_cu

And probably guard these by (boost-)static_asserts to be the same size(of)
Or as suggested by @Anastasiya Asadullayeva use a reinterpret_cast in the call which is better also guarded by a static_assert.


text:
Q: Server nodes unble to discover each other in Apache Ignite I'm trying to setup 3 server nodes in my local machine. Each node starts but unable to join the cluster.
I can see the below message being logged in the log file for each server node.

Topology snapshot [ver=1, servers=1, clients=0, CPUs=4, heap=0.1GB]

Here is my code to start the server.
IgniteConfiguration config = new IgniteConfiguration();
TcpDiscoverySpi spi = new TcpDiscoverySpi();
TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
ipFinder.setAddresses(Arrays.asList("192.168.0.3","192.168.0.3:47100..47120"));
spi.setIpFinder(ipFinder);
config.setDiscoverySpi(spi);
// Start Ignite node.
ignite = Ignition.start(config);

Can anyone please suggest if I was missing something here!

A: Try removing the address without the port and leave only the one that specifies the range:
ipFinder.setAddresses(Arrays.asList("192.168.0.3:47100..47120"));

A: Struggled with this for hours and could only solve it by doing the following.

*

*Ensure that you've set the local interface and port range on which your servers are litening:
TcpDiscoverySpi spi = new TcpDiscoverySpi();

//This address should be accessible to other nodes
spi.setLocalAddress("192.168.0.1");
spi.setLocalPort(48500);
spi.setLocalPortRange(20);

*Configure your IP finder accordingly. Supposing that the node is to find peers on the same machine configured similarly (i.e., as per [1] above):
TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder();
ipFinder.setAddresses("192.168.0.1:48500..48520");

spi.setIpFinder(ipFinder);

As instances start up in turn, they'll use ports within the configured range, and within that range, they'll discover one another using TCP discovery.
This is the only way I managed to connect 2+ server nodes on the same machine, without using multicast discovery.


text:
Q: Concrete range example The Go documentation on the text/template package is so abstract that I'm having trouble figuring out how to actually range over a slice of objects.  Here's my attempt so far (This outputs nothing for me):
package main
import (
    "os"
    templ "text/template"
)
type Context struct {
    people []Person
}
type Person struct {
    Name   string //exported field since it begins with a capital letter
    Senior bool
}
func main() {
    // Range example
    tRange := templ.New("Range Example")
    ctx2 := Context{people: []Person{Person{Name: "Mary", Senior: false}, Person{Name: "Joseph", Senior: true}}}
    tRange = templ.Must(
    tRange.Parse(`
{{range $i, $x := $.people}} Name={{$x.Name}} Senior={{$x.Senior}}  {{end}}
`))
    tRange.Execute(os.Stdout, ctx2)
}

A: The range is correct. The problem is that the Context people field is not exported. The template package ignores unexported fields. Change the type definition to:
type Context struct {
   People []Person // <-- note that People starts with capital P.
}

and the template to:
 {{range $i, $x := $.People}} Name={{$x.Name}} Senior={{$x.Senior}}  {{end}}

playground


text:
Q: How to download media files in WhatsApp API which send users? I am currently writing a chatbot for WhatsApp.
I use the 360dialog platform, which makes it possible to work with the WhatsApp Business API.
When the client sends a message, I see the following JSON object in the logs of my application:
{
    "messages": [
        {
            "from": "77773336633",
            "id": "ABGGd3c1cGY_Ago61ytHsZknvtLv",
            "image": {
                "id": "ffd23134-2dae-4fed-b5f8-0ce7867b6ddd",
                "mime_type": "image/jpeg",
                "sha256": "bd02100d961b5a1dbaae1dd645485ebbfeda77b44e82c015f1cf29b05654ccb9"
            },
            "timestamp": "1605703542",
            "type": "image"
        }
    ],
    "contacts": [
        {
            "profile": {
                "name": "Nurzhan Nogerbek"
            },
            "wa_id": "77773336633"
        }
    ]
}

I can't find any information in the documentation about how to download this file.
In my case, I want to upload this image file that the client sends to my file storage.
Please tell me which URL method from the WhatsApp API is responsible for this mechanism?
P.S. At the same time, I can send files to clients. This information is available on the official documentation.

A: May be it will help, just try, take a look:-
const URL = `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=1104480873777230&ext=1662705250&hash=ATuMx352sLrhKUegbQZSC8oLl3J5Vy3Z49lO4HwTUKWRYQ`;
const FROM = `video`;

const config = {
  method: 'get',
  url: URL, //PASS THE URL HERE, WHICH YOU RECEIVED WITH THE HELP OF MEDIA ID
  headers: {
    'Authorization': `Bearer ${token}`
  },
  responseType: 'arraybuffer'
};
axios(config)
  .then(function (response) {
    const ext = response.headers['content-type'].split("/")[1];
    fs.writeFileSync(`${FROM}.${ext}`, response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

A: It was very tricky because postman worked, but c# didn't work for me, and I spent two days trying to find the solution and finally did the following code, which works in C#:
using HttpClient _httpClient = new HttpClient();
Uri uri = new Uri(mediaUrl);
var fileName = $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.jpeg";
string filePath = $"Files\\{fileName}";

// NOTE: to save bandwidth, request compressed content
_httpClient.DefaultRequestHeaders.AcceptEncoding.Clear();
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));

// NOTE: accept all languages
_httpClient.DefaultRequestHeaders.AcceptLanguage.Clear();
_httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("*"));

// NOTE: accept all media types
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));

var productValue = new ProductInfoHeaderValue("ScraperBot", "1.0");
var commentValue = new ProductInfoHeaderValue("(+http://www.API.com/ScraperBot.html)");
_httpClient.DefaultRequestHeaders.UserAgent.Add(productValue);
_httpClient.DefaultRequestHeaders.UserAgent.Add(commentValue);

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", {WhatsApp_Access_Token});

HttpResponseMessage response = await _httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
var mediaType = response?.Content?.Headers?.ContentType?.MediaType ?? string.Empty;

var imageBytes = await response.Content.ReadAsByteArrayAsync();
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    fs.Write(imageBytes, 0, imageBytes.Length);
}

Here, {WhatsApp_Access_Token} is your Whatsapp API permanent token.
Ping me in a comment, please, if you have any issues or questions.

A: The official documentation has a session for this in https://developers.facebook.com/docs/whatsapp/api/media.
Basically you must make a GET request to download the media.
curl --request GET \
  --url https://waba.360dialog.io/v1/media/{media id} \
  --header 'D360-API-KEY: {your api token}'


text:
Q: Is there a Project Euler-alike for machine learning? I found Project Euler http://projecteuler.net/ to be incredibly useful in learning programming languages. Is there a similar site for Machine Learning?
I did see http://www.kaggle.com/, but it is not nearly as accessible to beginners as Project Euler.

A: UCI is well-known in the machine learning community for their repository if datasets. Many journal articles include results of their techniques on some UCI datasets, so you can try yourself and see how you do.

A: How about: http://www.ml-class.org/? It has good introduction and some programming excersises. AFAIK Euler has much more sophisticated examples, but ml-class is still a good beginning.
As it was pointed in the comments this course has next edition: http://jan2012.ml-class.org/#

A: Though the stakes are higher than for Project Euler, as you've pointed out, Kaggle is an excellent source of data for use in your own experiments.  Many of their contests require you to be signed in to access the datasets (for legal agreements and so forth), but if you don't actually finish an entry, there's no penalty that I know of.
That being said, if you look for data sets that are specific to testing statistics procedures, like the ones at Princeton, you can test the data on different network architectures and compare it to plain regression, etc. as a benchmark.
See also here for a comprehensive list, which includes all of the Google natural language processing data.
So, Project Euler provides a great service with specific problems, but in the case of machine learning, you can use existing datasets with an architecture of your creation and compare the "answers" to conclusions that are presented online or in research papers.


text:
Q: Whats the brief factual difference between Kubernetes, Helm and Rancher (and others) As a new starter in the world of DevOps, I've tried to find a one-pager that explains side by side what each of the following technologies do best and how they are orchestrated together in typical deployment scenario.
Its all a bit overwhelming coming in cold.
Seems like there's a technology for every single step of the deployment. Have some been superseded by others? Are the differentiated in the granularity of the artifact?
No opinions please of which is better, just resources of hey they are used together.

*

*Docker

*Kubernetes

*Helm

*Terraform

*Rancher

A: Docker is the de facto standard for building containers and running them in various environments.
Kubernetes is a complex framework for orchestrating containers.
Helm is a component of Kubernetes, a package manager for running apps on Kubernetes.
(Rancher is a framework for managing and orchestrating containers. It could also manage Kubernetes clusters)

A typical scenario 'devops' scenario would involve builiding Docker images from source, and running them in A kubernetes cluster in production, as described in a Helm chart. The underlying infrastructure for Kubernetes could be deployed with Terraform.


text:
Q: How do I pull from remote git? I'm a total git noob. I've been given the task of making some changes to a website but for some of those changes I have to access files on a git repository. The link I've been given is so:
/opt/git/repositories/*******_site.git
How do I use this link to connect to the repository?

A: If the path you have been given is accessible to you, it would be just as simple as;
git clone /opt/git/repositories/*******_site.git
Then you can interact with it like any other Git repo. You may need to specify the full filepath though. For example;
git clone D:/Projects/opt/git/repositories/*******_site.git


text:
Q: How can I make an unordered list of item transition on hover I have an unordered list of image items with a text overlay at the bottom. The text at the bottom are inline elements with different backgrounds and the right block has a p element that displays on hover.
I do not want a bland quick display, I want it to transition in about 0.4s. I seem not to get the targeted style. This is what my code looks like

SOME SERVICES:

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam

SOME SERVICES:

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam

.slideList {
  width: 100%;
}
.slideList li {
  position:relative;
}

.slideList .service-highlight {
  background-color: #0088ff;
  position: absolute;
  color: white;
  bottom: 0;
  left: 0;
  right:0;
}

.slideList .service-highlight p {
  display: inline-block;
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.slideList .service-highlight .services-box{
  text-align: center;
  background-color: #003768;
  width: 270px;
  font-weight: bold;
  float: left;
}

.slideList .service-highlight .services-detail{
  width:calc(100% - 270px);
  float: left;
  padding-left: 5px;
}

.slideList .hide-description {
  display: none;
  font-weight:normal;
}

.slideList .hide-description p {
  font-weight:normal;
  padding-top: 10px 5px 10px;
}
.hide-description {
  display: none;
}

.services-box {
  height: 26px;
  background: #0bf;
}
.service-highlight {
}

.service-highlight:hover .hide-description {
  display: block;
  transition: all 0.4s ease-in-out 0s, visibility 0s linear 0.3s, z-index 0s linear 0.01s;
}

.service-highlight:hover .services-box {
  height: 110px;
}
@media (max-width: 992px) {
      .slideList .service-highlight p {
        display: block;
      }

      .slideList .service-highlight .services-box{
        width: 100%;
      }

      .slideList .service-highlight .services-detail{
        width:100%;
        text-align: center;
      }
}

A: .hide-description {
  opacity: 0;
}
.slideList .hide-description {
  opacity: 0;
  font-weight:normal;
}
.service-highlight:hover .hide-description {
  display: block;
  transition: all 0.4s ease-in-out 0s, visibility 0s linear 0.3s, z-index 0s linear
    0.01s;
  opacity: 1;
}

This will work for you, transition is applied for thing that are present. Or, for display: none to block transition  will not work. If doesnot work then provide a codepen link. Will be happy to help you.

A: try this code

.slideList {
  width: 100%;
}
.slideList li {
  position:relative;
}

.slideList .service-highlight {
  background-color: #0088ff;
  position: absolute;
  color: white;
  bottom: 0;
  left: 0;
  right:0;
}

.slideList .service-highlight p {
  display: inline-block;
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.slideList .service-highlight .services-box{
  text-align: center;
  background-color: #003768;
  width: 270px;
  font-weight: bold;
  float: left;
}

.slideList .service-highlight .services-detail{
  width:calc(100% - 270px);
  float: left;
  padding-left: 5px;
}

.slideList .hide-description {
  opacity:0;
  transition: all 0.4s;
  font-weight:normal;
}

.slideList .hide-description p {
  font-weight:normal;
  padding-top: 10px 5px 10px;
}

.services-box {
  height: 26px;
  background: #0bf;
}
.service-highlight {
}

.service-highlight:hover .hide-description {
      opacity: 1;

  transition: all 0.4s ease-in-out 0s, visibility 0s linear 0.3s, z-index 0s linear 0.01s;
}

.service-highlight:hover .services-box {
  height: 110px;
}
@media (max-width: 992px) {
      .slideList .service-highlight p {
        display: block;
      }

      .slideList .service-highlight .services-box{
        width: 100%;
      }

      .slideList .service-highlight .services-detail{
        width:100%;
        text-align: center;
      }
}

SOME SERVICES:

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam

SOME SERVICES:

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam


text:
Q: Push from Server to Blackberry Playbook Is possible to make a "push", initiated by a server, to send data down to a Blackberry playbook application?
If so how is this best implemented in Flex/Actionscript? ie. How do we capture this on the client?

A: You'll need to use a server that has push technology like BlazeDS, GraniteDS, LCDS, Wowza Server, FMS, etc.  Although BlazeDs and GraniteDS isn't 'true' push (it's long polling), it should be more than adequate for 99% of all projects, plus it's completely free to use.
On the Flex end, you only need to setup the consumer to point to the AMF channel (your server) for it to work:
<s:Consumer destination="MessagingDestination" message="onMessage(event)">
    <s:channelSet>
        <s:AMFChannel url="YourServerURL" />
    </s:channelSet>
</s:Consumer>


text:
Q: checar se está logado numa session específica Boa tarde, pessoal. Estou com um problema e não imagino lugar melhor para resolver isso do que aqui:
Tenho um site que tanto logins de administradores com acessos à funções e membros comuns acessarão. A dúvida é em como vou separar para somente exibir as funções  para os administradores, pois até então estava usando isso:
session_start();

if(!isset($_SESSION["email"]) || !isset($_SESSION["senha"])){
    session_write_close();
    header("Location: index.php");
    exit; //encerra todas as funções e leva para o index
}
else{
    echo "Você está logado.";
}

Mas agora que coloquei o cadastro de membros não sei o que fazer. Obrigado!


text:
Q: Clicking on a comment in your feed which has been moved to chat ... fails to load question at all. (Error msg box.)

*

*App Version: 1.0.95

*Device Manufacturer: samsung

*Device Model: SM-N950U1

*

*OS Version: 8.0.0 (N950U1UES4CRE1)


text:
Q: How to find averages? I'm trying to make a program to find the Mean average with a set of numbers. It works at the moment but I was wondering if there is any way to make it easier or cleaner. It is pretty messy and bad. Is there anyway I can use loops or anything to make it easier?
NON = raw_input("How many numbers are there? ")
NON = int(NON)

if NON == 2:
    n1 = raw_input("First Number: ")
    n1 = int(n1)
    n2 = raw_input("Second Number: ")
    n2 = int(n2)
    mean = (n1 + n2)/2
    print mean
    print mean

It keeps going after this, all the way up to 15. I just made it manually.

A: You can just write it so that the user can just indefinitely input numbers:
numbers = []
while True:
    numbers.append(int(raw_input("What is the next number?")))
    done = raw_input("Are you done? (Y/N) ")
    if done.lower() == "y":
        break
print("The average is {}".format(sum(numbers)/len(numbers)))

A: A common way of handling this is with a for() loop
NON = raw_input("How many numbers are there? ")
NON = int(NON)
sum = 0
for i in range(NON):
    number = raw_input("Enter Number #"+str(i)+": ")
    number = int(number)
    sum += number
average = sum / NON
print("Average is: "+str(average))

A: Try a function. Function will group the codes and can be used to call multiple of times.
An example
def average(number1, number2):
    return (int(number1) + int(number2)) / 2

NON = raw_input("How many numbers are there? ")
NON = int(NON)

    if NON == 2:
        n1 = raw_input("First Number: ")
        n2 = raw_input("Second Number: ")
        print average(n1,n2)

A: Try to store the user's input in an array then perform the following:
sum = 0
list = [11,22,33,44,55,66,77]
for num in list:
    sum = sum +num
average  = sum / len(list)
print ("Average of list element is ", average )

A: I have one method to do it which is a nested loop
students = int(input("How many students do you have? "))
tests = int(input("How many test for your module? "))
for x in range(students):
    x += 1
    total = 0
    print(f'****** Student # {x} ******')

    for y in range(tests):
        y += 1
        score = float(input(f'Test number {y}: '))
        total = (total + c)
    ave = total/tests
    print(f'The ave for student # {x} is: {ave:.1f}')


text:
Q: vertical centering div without defined height and content I have a Wordpress site which I want to vertically center content in the Jumbotron div (site uses Bootstrap framework) No tables if possible as it ruins other functionality in the jumbotron.
EDIT: The child div is centered but the content inside is not
html
...

            <?php echo $content ?>  (function to generate content not shown)

css
.jumbotron {
position: relative;
min-height: 600px;
width: 100%;
border-radius: 0 !important;
margin: 0; padding: 0;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}

#s-text {
position: absolute;
text-align: center;
margin: auto;
max-width: 60%;
top: 0; right: 0; left: 0; bottom: 0;
transform:translateY(-50%)
}

.jumbotron {
  position: relative;
  min-height: 600px;
  width: 100%;
  margin: 0;
  padding: 0;
  border-radius: 0 !important;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}
#s-text {
  position: absolute;
  display: inline-block;
  text-align: center;
  margin: auto;
  max-width: 60%;
  top: 50%;
  right: 0;
  left: 0;
  bottom: 0;
  transform: translateY(-50%)
}
#s-text p {
  position: relative;
  font-weight: 500;
  font-size: 1em;
  line-height: 1.4em;
  color: #fff;
}
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

content content content content content content content content content content content content content content content content content content content content content


text:
Q: Save input from bash script I making a form using bash script.
I want the user to choose the name of the save file.
echo whats your name?
read name?
echo how old are you?
read age?
what do u want to call the save file?
Myname

A: Yad may be useful in this regard, it is a fork of zenity with more features, one of them the ability to create forms.
For install yad goto
http://www.webupd8.org/2010/12/yad-zenity-on-steroids-display.html
You can create simple form by
#!/bin/bash

frmdata=$(yad --title "Test Form" --form --field "Address" --field="Name")

frmaddr=$(echo $frmdata | awk 'BEGIN {FS="|" } { print $1 }')
frmname=$(echo $frmdata | awk 'BEGIN {FS="|" } { print $2 }')

echo $frmaddr > test.txt
echo $frmname >> test.txt

After you enter your data and click ok or hit enter on the keyboard, the form data will be written to a text file called test.txt
more example
http://code.google.com/p/yad/wiki/Examples


text: Q: QSpinBox digit grouping I would like to implement (already implemented a scratch but not satisfied with that) a custom QSpinBox with the extra feature of a digit grouping. I would like to use this with small and large numbers as well like 1.000 ... 10.000.000. I found this but I think I need a locale independent solution. I'd appreciate any advice.


text:
Q: Could not load file or assembly Microsoft.EntityFrameworkCore.Design version 6.0.1 when trying to run app after publishing I'm facing issues with an ASP.NET Core 6 web app that has multiple projects and some of them have Views and Controllers due to requirements, so I marked them with as <Project Sdk="Microsoft.NET.Sdk.Razor"> and added application parts in the Startup as follows:

Due to the fact I run Scaffolding command line to build entity classes based on SQL Server Database, to create also the migration files, I use a technique to have entities singularized/pluralized at design-time when they are created. To achieve that I had to use DesignTime services provided by Microsoft.EntityFrameworkCore.Design by creating the DesignTimeDbContextFactory, DesignTimeServices and Pluralizer classes to provide db-connection and pluralization services, so I added Microsoft.EntityFrameworkCore.Design package to the main project and to the backend (dbcontext repository) project.
To avoid this package copied to the output publishing folder (this package should not be part of production), I added following configuration in the csproj of the projects referencing the package, according internet documentation found:
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <!--<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>-->
    </PackageReference>

The problem comes out when I try to run the published project by running dotnet SicotX.dll command-line (is the main project). The app try to run but do nothing

I check the logs I added to the app, and this is the list of stack trace:
2022-03-02T21:31:07.8101308-05:00 [INF] () Creating the web host ...
2022-03-02T21:31:09.0961070-05:00 [FTL] (Microsoft.AspNetCore.Hosting.Diagnostics) Application startup exception
Could not load file or assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado.
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart.get_Types()
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFeatureProvider.PopulateFeature(IEnumerable`1 parts, ControllerFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetControllerTypes()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.<>c__DisplayClass11_0.<Subscribe>b__0()
   at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func`1 changeTokenProducer, Action changeTokenConsumer)
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Subscribe()
   at Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource..ctor(ControllerActionEndpointDataSourceIdProvider dataSourceIdProvider, IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory, OrderedEndpointsSequenceProvider orderSequence)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllerRoute(IEndpointRouteBuilder endpoints, String name, String pattern, Object defaults, Object constraints, Object dataTokens)
   at SicotX.Startup.<>c.<Configure>b__6_2(IEndpointRouteBuilder endpoint) in D:\Proyectos\Repositorios\Enterprise\.Net\SicotX\SicotX\Frontend\SicotX\Startup.cs:line 266
   at Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseEndpoints(IApplicationBuilder builder, Action`1 configure)
   at SicotX.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log) in D:\Proyectos\Repositorios\Enterprise\.Net\SicotX\SicotX\Frontend\SicotX\Startup.cs:line 264
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado.
File name: 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
2022-03-02T21:31:09.6087813-05:00 [FTL] () A fatal error ocurred creating the web host.
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart.get_Types()
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFeatureProvider.PopulateFeature(IEnumerable`1 parts, ControllerFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetControllerTypes()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.<>c__DisplayClass11_0.<Subscribe>b__0()
   at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func`1 changeTokenProducer, Action changeTokenConsumer)
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Subscribe()
   at Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource..ctor(ControllerActionEndpointDataSourceIdProvider dataSourceIdProvider, IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory, OrderedEndpointsSequenceProvider orderSequence)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllerRoute(IEndpointRouteBuilder endpoints, String name, String pattern, Object defaults, Object constraints, Object dataTokens)
   at SicotX.Startup.<>c.<Configure>b__6_2(IEndpointRouteBuilder endpoint) in D:\Proyectos\Repositorios\Enterprise\.Net\SicotX\SicotX\Frontend\SicotX\Startup.cs:line 266
   at Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseEndpoints(IApplicationBuilder builder, Action`1 configure)
   at SicotX.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log) in D:\Proyectos\Repositorios\Enterprise\.Net\SicotX\SicotX\Frontend\SicotX\Startup.cs:line 264
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at SicotX.Program.Main(String[] args) in D:\Proyectos\Repositorios\Enterprise\.Net\SicotX\SicotX\Frontend\SicotX\Program.cs:line 47
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado.
File name: 'Microsoft.EntityFrameworkCore.Design, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

I'm looking in all projects to see if some of them are also referencing this package but only the main project and the backend project were marked in the csproj as mentioned above.
I'm trying to search if the problem is caused by any application part loaded in the startup but no success.
Important: My goal is to avoid Microsoft.EntityFrameworkCore.Design published to production since that package only works in design-time and overcome the log errors I'm facing according the things I've been doing.
I'm not facing issues while debugging.
I appreciate any help

A: Workaround
After analyzing alternatives, I achieved to overcome the issue by doing following:
After checking out that DEBUG conditional directive is enabled only for Debug:

I used the compilation directives in all code referencing Microsoft.EntityFrameworkCore.Design package, to avoid that final published assemblies would require to have this package in the output directory, and because publishing is in release mode, the code was supressed, like this:

Now, the app is working as expected.


text:
Q: Template method need an object declared in the child constructor a child class extending a mother class which, in its constructor call a template method instianted in the child class because it need a value obtained in the child constructor.
How Can I do something like this, without changing my Parent constructor (Foo, here. I cannot do any changes in the real Foo class):
public abstract class Foo{
    public Foo(){
        register();
    }

    public abstract void register();

    public void aMethod(int aValue){
        // body
    }

}

public class Bar extends Foo{

    public Foo(int aValue){
        // body
    }

    register(){
        aMethod(aValue);
    }
}

Here, even if I put aValue in a field, aValue is not even created at
aMethod(aValue);.

How can I solve my problem?
I am looking for any pattern, ULM, solution.

A:
a child class extending a mother class which, in its constructor call a template method instianted in the child class because it need a value obtained in the child constructor.

Why doesn't the subclass constructor simply pass the value up to the superclass constructor?
public abstract class Foo {
    protected Foo(int value) {
       ... use value ...
   }
}

public class Bar extends Foo {
    public Foo(int value) {
        super(value);
    }
    ...
}

Note that calling virtual methods in a constructor is a dangerous practice, as the subclass won't have had the opportunity to initialize itself yet.

A: Your class structure is pretty messed up. Do you have something this in legacy code that you cannot change parent ? If not change it:-)

A: Calling abstract method in a constructor is a bad design. Some tools like PMD indicates it as warning by default (or maybe even error). So it's hard to talk about any pattern here I think. What i would do is to implement Bar class as below.
public class Bar extends Foo{

    private int aValue;
    private boolean initialized = false;

    public Bar(int aValue){
        this.aValue = aValue;
        initialized = true;
        register();
    }

    public void register(){
       if (initialized)
       aMethod(aValue);
    }

}


text:
Q: JavaEE webApp with GlassFish Server and Firebase showing java.lang.NoClassDefFoundError I am trying to build a webapp with JavaEE and glassfish server with firebase admin sdk. The server runs properly until it crashes after a login screen with a java.lang.NoClassDefFoundError:

com/google/firebase/FirebaseOptions$Builder root cause :
  java.lang.ClassNotFoundException:
  com.google.firebase.FirebaseOptions$Builder in my browser.

I searched and tried many solutions but none have led me anywhere. For example  it was recommended to make sure my artifact has all the dependencies. I've done that, and still now.... I do get the fact that the firebase classes are available at compile time but somehow are not available at runtime.
My pom.xml :
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>groupId</groupId>
<artifactId>CustomerNetwork</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>23.6-jre</version>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>6.12.2</version>
    </dependency>
</dependencies>

My artifact: (a screenshot from intellij)

If you need more info or the code in my classes, let me know. Or if this question is a duplicate, lead me to the question that hopefully has the answer am looking for.


text:
Q: pointers passed to functions I am using the Arduino IDE to to write a sketch that passes data saved in progmem to a function, the function then writes the progmem data to local array.
The code is below:
const uint8_t Data_3 [256] PROGMEM = {0x11, 0x39.....}
void setup() {
Serial.begin(57600);
Data(Data_3, 0x00, 256);
}

void loop() {
}

void Data(const uint8_t *data, uint8_t bank, uint16_t bytes) {
uint8_t buff1 [256];
buff1[0] = data[0];
Serial.println(buff1[0],HEX);   // <--Works fine prints the correct value
for ( uint16_t x = 0; x < bytes + 1; x++ ) {
  buff1[x] = data[x];
  Serial.println(buff1[x],HEX); // <--Just prints garbage
  }
}

When I assign buff1[0] = data[0] and print the result the answer is correct. When I loop a print function with buff1[x] = data[x] I just get rubbish. Does anyone know the reason for this?

A: You have to use #include <avr/pgmspace.h> and Serial.print(pgm_read_byte(data+x)); otherwise it'll try to get data from the same address but from RAM, not from Flash memory.
Or copy into the buffer by memcpy_P(buff, data, bytes);


text:
Q: How to query number of changes in a column in MySQL I have a table that stores items with two properties. So the table has three columns:
 item_id  |  property_1  |  property_2  |  insert_time
  1       |   10         |  100         |  2012-08-24 00:00:01
  1       |   11         |  100         |  2012-08-24 00:00:02
  1       |   11         |  101         |  2012-08-24 00:00:03
  2       |   20         |  200         |  2012-08-24 00:00:04
  2       |   20         |  201         |  2012-08-24 00:00:05
  2       |   20         |  200         |  2012-08-24 00:00:06

That is, each time either property of any item changes, a new row is inserted. There is also a column storing the insertion time.  Now I want to get the number of changes in property_2. For the table above, I should get
item_id  |  changes_in_property_2
 1       |    2
 2       |    3

How can I get this?

A: This will tell you how many distinct values were entered. If it was changed back to a previous value, it will not be counted as a new change, though. Without a chronology to your data, hard to do much more.
select item_id, count(distinct property_2)
from Table1
group by item_id

A: Here is the closest that I could get to your desired result. I should note however, that you are asking for the number of changes to property_2 based on item_id. If you are analyzing strictly those two columns, then there is only 1 change for item_id 1 and 2 changes for item_id 2. You would need to expand your result to aggregate by property_1. Hopefully, this fiddle will show you why.
SELECT a.item_id,
  SUM(
    CASE
      WHEN a.property_2 <>
        (SELECT property_2 FROM tbl b
          WHERE b.item_id = a.item_id AND b.insert_time > a.insert_time LIMIT 1) THEN 1
      ELSE 0
    END) AS changes_in_property_2
FROM tbl a
GROUP BY a.item_id

A: My take :
SELECT
    i.item_id,
    SUM(CASE WHEN i.property_1 != p.property_1 THEN 1 ELSE 0 END) + 1
      AS changes_1,
    SUM(CASE WHEN i.property_2 != p.property_2 THEN 1 ELSE 0 END) + 1
      AS changes_2
FROM items i
LEFT JOIN items p
  ON p.time =
    (SELECT MAX(q.insert_time) FROM items q
        WHERE q.insert_time < i.insert_time AND i.item_id = q.item_id)
GROUP BY i.item_id;

There is one entry for each item that is not selected in i, the one that has no predecessor. It counts for a change though, that's why the sums are incremented.

A: I would do it this way, with user-defined variables to keep track of the previous row's value.
SELECT item_id, MAX(c) AS changes_in_property_2
FROM (
    SELECT IF(@i = item_id, IF(@p = property_2, @c, @c:=@c+1), @c:=1) AS c,
        (@i:=item_id) AS item_id,
        (@p:=property_2)
    FROM `no_one_names_their_table_in_sql_questions` AS t,
    (SELECT @i:=0, @p:=0) AS _init
    ORDER BY insert_time
) AS sub
GROUP BY item_id;


text:
Q: How to declare in Typescript a dictionary of Generic (in the TS sense) functions I want to create a series of functions of a Generic type called Handler. Each function gets different but quite specific parameters and returns specific responses, all stated in the Generic definition. A message containing a request with RequestParams comes in and a reply goes back.
A dictionary of such functions is passed to a dispatcher function that will, when called with the handler name and the arguments, to return whatever that function does. To make it simple I declared functions for CRUD operations (plus list) just because everyone knows those.
But my problem is that I have not been able to get rid of the last error, shown in the comment at the end. I tried several ways to do it and been playing whack-a-mole fixing one function and getting another popping up.
I believe I declared too much and made it too restrictive or didn't state the options right. What am I missing? Thanks for your patience.
type ID = string;
type VALUE = string | number | boolean | Date;
type AnyRow = Record<string, VALUE>;

// Default types for Id, In and Out
type DefaultId = ID | undefined;
type DefaultIn = AnyRow | undefined;
// Listings always return an array, even if an empty one, never undefined.
// Reads might return a row or undefined. Tried with `null` as well, to no avail.
type DefaultOut = AnyRow[] | (AnyRow | undefined);

// A handler might receive an Id or not, and it might accept (In) and return (Out) various responses
// - the return is actually a Promise.
// - There is actually a third input, a series of options,
//   such as, sort order, field to sort by, page to select
export type Handler<
  Id extends DefaultId,
  In extends DefaultIn,
  Out extends DefaultOut
> = (params: { id: Id; data: In }) => Out;

export type Handlers = Record<
  string,
  Handler<DefaultId, DefaultIn, DefaultOut>
>;

// Given a series of handlers, `createDispatcher` will return
// a function that when called with the key to a handler and
// an object with the id and data
// returns whatever that keyed function returns, if anything.
export const createDispatcher =
  (handlers: Handlers) =>
  (fnName: string, requestData: { id: DefaultId; data: DefaultIn }) =>
    handlers[fnName](requestData);

// These are the types for a typical CRUD series of handlers, plus list
// They represent the most common combinations of inputs and outputs.
type Resolvers<T extends AnyRow> = {
  list: Handler<undefined, undefined, T[] | undefined>;
  create: Handler<undefined, T, T>;
  read: Handler<ID, undefined, T | undefined>;
  update: Handler<ID, T, T>;
  delete: Handler<ID, undefined, undefined>;
};

type Data = { a: number };

const handlers: Resolvers<Data> = {
  list: () => [{ a: 1 }, { a: 2 }],
  read: ({ id }) => (id ? { a: 1 } : { a: 2 }),
  create: ({ data }) => data,
  update: ({ id, data }) => (id ? data : data),
  delete: ({ id }) => (id ? undefined : undefined),
};

// And here I create the actual dispatcher for the Data above
// with the text of the error shown below
export const dataDispatcher = createDispatcher(handlers);
//                                             ^^^^^^^^
// Argument of type 'Resolvers<Data>' is not assignable to parameter of type 'Handlers'.
//   Property 'list' is incompatible with index signature.
//     Type 'Handler<undefined, undefined, Data[] | undefined>' is not assignable to type 'Handler<DefaultId, DefaultIn, DefaultOut>'.
//       Type 'DefaultId' is not assignable to type 'undefined'.
//         Type 'string' is not assignable to type 'undefined'.

Playground link

A: As @kelly pointed out in the comments, the solution is in changing this declaration:
export type Handlers = Record<
  string,
  Handler<DefaultId, DefaultIn, DefaultOut>
>;

to:
export type Handlers = Record<
  string,
  Handler<any, any, any>
>;

The issue was unrelated to the rest of the code shown above.
Sorry for the trouble and thanks.


text:
Q: mysql procedure parameter and FIND_IN_SET performance I have a table with over 1 MIO rows and I like to create a stored procedure instead of calling a direct sql statement, but I have performance issues with the FIND_IN_SET function.
Start from the scratch:
My existing query is:
SELECT id
FROM `tablex`
WHERE id=1 OR id=2 OR id=3;

The WHERE clause is built by PHP form a previous result. Its much more complex as here in this example .-).
This query works fine for me and I´m happy with the performance.
Now want to create a stored procedure like this:
CREATE DEFINER=`root`@`localhost` PROCEDURE `FOO`(**IN `p_ids` VARCHAR(255)**)

The p_ids are comma separated and this is running but very slow, because FIND_IN_SET is not
using the index on the ids.
SELECT id
FROM `tablex`
WHERE FIND_IN_SET(id,p_ids)

I like to find a way to get the complete WHERE clause from my first query into the stored procedure, or to find a faster solution as the Find_in_set thing.

A: Use PREPARE to create dynamic SQL.
SET @sql = CONCAT('SELECT id FROM tablex WHERE id in (', p_ids, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

A: no code in comments :-)
Here are the syntax corrected version.
SQL CALL:
CALL `db`.`FOO`("2,3,4");

Procedure CODE:
CREATE DEFINER=`root`@`localhost` PROCEDURE `FOO`(IN `p_ids` VARCHAR(255))
BEGIN
    SET @sql = CONCAT('SELECT id FROM tablex WHERE id in (', p_ids, ')');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END


text:
Q: Python: how to create a distance network with a given distribution? I have N agents to place in a grid n x n following the (truncated Levy) distribution
px =  (r + r0)**(-beta)*exp(-r/k)
Each agent has two favorite cells: home and work and px is the probability for each agent to move from  home and work with a distance r.
def returnLevy(r, beta):
    r0 = 100
    k = 1500
    px = (r + r0)**(-beta)*exp(-r/k)
    return px

I have compute the distance among all the cells in my grid, so
allDistances.head(5):

    distances   cell_a  cell_b
0   1.322959      0       1
1   0.717737      0       2
2   0.454170      0       3
3   0.321495      0       4
4   0.454248      0       5

I would like to know if there is a way to randomly assign to each agent a distance r from home and work following the aforementioned distribution. At the end I would like to have a dataframe:
agentsCells

    distance    home    work
0   1.322959     320    1089
1   0.717737      4      765
2   0.454170     2100    388

A: You can define your own custom pdf using scipy and use this to calculate useful metrics of your probability density
import scipy.stats as st

class LevyPDF(st.rv_continuous):
    def _pdf(self,r):
        r0 = 100
        k = 1500
        return (r + r0)**(-beta)*exp(-r/k) #Normalized over its range [minValue,maxValue]

my_cv = LevyPDF(a=minValue, b=maxValue, name='LevyPDF')

To randomly draw values you have to calculate at first the cumulative distribution function (cdf) and then invert it to get the icdf. This can now be used the draw the random values following your pdf (you can find more details here).
If you have calculated the cdf, you can check your result using the numerical result of my_cv.cdf().


text:
Q: How do I get the Id of artworkrequests table instead of the id of the table where I join with artworkcontroller:
$leads = Artworkrequest::join('artworks', 'artwork_id', '=', 'artworks.id')->where('artworks.user_id', auth()->user()->id)->get();
What I want to do is delete the Artworkrequest by passing the {{$lead->id}} but the problem is that it is selecting the id of the table artworks instead of the id of artworkrequest. How can I pass the id of artworkrequest in my blade?
leads.blade.php:
@foreach($leads as $lead)

                                picture }}" width="100px" style="width: 100px" alt="">

                                {{ $lead->title }}

                                    user_id]) }}"><button class="btn btn-dark">bekijk contactgegevens</button>

                                    id])}}"><button class="btn btn-success">Delete</button>

                                    <form action="{{ route('lead.delete') }}" method="POST">
                                    @csrf

                                        <input type="hidden" name="id" value="{{$lead->id}}">
                                        <button type="submit" class="btn btn-danger">delete</button>
                                    </form>

@endforeach

A: For this example, why don't you use Eloquent Relation instead of join?
To Do eloquent relationship you have to define the relationships in respective model.
Artwork.php
class Artwork extends Model
{

    public function artworkRequest()
    {
        return $this->hasMany(ArworkRequest::class);
    }
}

ArtworkRequest.php
class ArtworkRequest extends Model
{

    public function artwork()
    {
        return $this->belongsTo(ArworkRequest::class);
    }
}

Then in ArtworkController.php you can get the data this way. You don't have to include the with('artwork') if you don't need artwork data too.
$leads = ArtworkRequest::with('artwork')->whereHas('artwork', function($q) {
    $q->where('user_id', auth()->user()->id);
})->get();

Then in blade file you can call it with
@foreach($leads as $lead)
{{ $lead->id }}

// additionally, you can also call Artwork data by using
{{ $lead->artwork->name }}
@endforeach

A: Controller:
public function lead()
    {
        $user = auth()->user()->id;
        $leads = Artworkrequest::with('artwork', 'profile')->get();
        return view('artworks.leads', compact('leads'));
    }

and blade.php:
                        @foreach($leads as $lead)
                        @if(Auth::user()->id == $lead->artwork->user_id )

                           {{$lead->artwork->user_id }}
                           {{ $lead->id }}

                           {{ $lead->artwork_id }}
                           {{ $lead->user_id }}

                           {{ $lead->artwork->title }}

                           {{ $lead->profile->first_name }}

                                <form action="{{ route('lead.delete') }}" method="POST">
                                @csrf

                                    <input type="hidden" name="id" value="{{$lead->id}}">
                                    <button type="submit" class="btn btn-danger">delete</button>
                                </form>

                        @endif

                        @endforeach


text:
Q: Eclipse ignoring the CLASSPATH variable? I had the idea any java application would look up the CLASSPATH variable to check for classes at runtime.
But that does not seem to be the case, as a application I'm running from Eclipse. In which concrete situations is the CLASSPATH variable used, then? How can I make sure Eclipse always makes use of my CLASSPATH variable?

A: The CLASSPATH variable is used when the java (or javaw) command is launched without the -classpath or -jar or -cp option. But Eclipse follows best practices, and always uses these options.
IMHO, you should NEVER rely on CLASSPATH. Always specify the classpath explicitely, in the command line options. It's quite rare to want ALL your java programs to share the same libraries. That's why the CLASSPATH global environment variable is a bad idea.


text:
Q: Coloring Provinces with Google Maps API I'm trying to color provinces using the map styling features of Google maps. I've defined a style but it doesn't seem to work. If I change geometry.fill to just geometry, I get the color on the province borders, so the style seems to be wired properly to the map, but I can't get the fill to work/
          var styleProv = [
            {
                featureType: 'administrative.province',
                elementType: 'geometry.fill',   //this doesn't seem to work
                stylers: [
                    { hue: '#eff00' },
                    { saturation: 200 },
                    { lightness: 5 },
                    { visibility: 'on' }
                ]
            }
            ];

A: Problems with your custom style:

*

*your hue hexadecimal code has 5 characters

*saturation is over 100

Besides, it turns out that only province strokes can be shown. For example, after hiding all map elements and giving province geometries colors with the Google Maps Wizard, only dashed province contours are shown.
Custom style only showing provinces (JSON format):
[
  {
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry",
    "stylers": [
      {
        "visibility": "on"
      }
    ]
  }
]


text:
Q: Javascript addeventlistener hitting click multiple times The below mentioned code will change icon from watched(-) to unwatched(+) and vice-versa in a list of data(list of icon):-
ts code:-
const watchListComponent = document.querySelectorAll('.addtoWatchlist');
        if (watchListComponent.length) {
            watchListComponent.forEach((watchItem) => {
                watchItem.addEventListener('click', () => {
                    console.log('here');
                    watchItem.querySelector('.icon').classList.toggle('iconWatched');
                    watchItem.querySelector('.icon').classList.toggle('iconWatchList');
                });
            });
        }

HTML code :-

                            Add to Watchlist

In the above case, first time if I click on the unwatched(+) icon it is getting changed to watched(-) for ex:- (+) to (-), and the next time if I click it should change from (-) to (+) but the icon is not changing. If I click twice the icon is getting changed from(-) to (+) then if I click twice changing from (+) to (-).
Need to change the icon from (+) to (-) and (-) to (+) on single click.

A: Use event delegation. A minimal reproducable example for you

document.addEventListener("click", toggleAddIcon);

function toggleAddIcon(evt) {
  const origin = evt.target;
  if (origin.classList.contains("icon")) {
    origin.classList.toggle('iconWatchList');
  }
}
.icon {
  cursor: pointer;
}

.icon.iconWatchList:after {
  content: ' (on list)';
}

click

click

click


text:
Q: Create date object and compare to todays date I have an object containing time. For example x.time = 10:20:00.
I want to take the current time minus my objects time.
This is my code so far, but i get the error message ="Invalid Date":
for(var i = 0; i<x.length; i++){
    nowDate = new Date();
    minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(),    nowDate.getDate() + x[i].time);
    text +- "It is "+ minutesLeft[i] + " milliseconds left";
 }

A: In order to convert your time property into a date object you can do:
var timepieces = x.time.split(':');
var date = new Date();
date.setHours(timepieces[0]);
date.setMinutes(timepieces[1]);
date.setSeconds(timepieces[2]);

Then you can directly compare the two dates by using the getTime() method of the Date object.
nowDate.getTime() === date.getTime()
nowDate.getTime() > date.getTime()
nowDate.getTime() < date.getTime()

You can also get the difference of two dates in milliseconds:
var milliseconds = nowDate.getTime() - date.getTime();

A: There are a bunch of problems with your code. I'll go through and hopefully catch everything.

*

*Use var to declare your variables inside your loop. (further reading)

*When you create the variable minutesLeft you are doing a bit of weird concatenation. You told us that x.time is a string such as "10:20:00" but you are (string) concatenating that with Date.prototype.getDate which returns a number in the range 1-31 (representing the day of the month). You are essentially doing this:
minutesLeft = new Date(2017,0,1910:20:00);

Which I hope you see will not create a new date. You perhaps wanted something along the lines of
minutesLeft = new Date(2017,0,19, 10, 20, 0);

Which should give you what you want (todays date set to the appropriate time defined by x.time.

*text +- does not make any sense. I suspect a typo, you meant text += which will append the value on the right to the variable text. Or, perhaps text = which will assign the value, replacing what was there

*"It is "+ minutesLeft[i] + " milliseconds left" using minutesLeft[i] will take a single character from a string (or an item from an array, if the value is an array). Yours is just a date object, and is not an array, so I suspect you just meant to leave off the [i] part altogether.

*If you're trying to get the difference between the current date/time and your selected date/time you need to do some arithmetic with nowDate and minutesLeft. I'm assuming this is a difference you're after.

var x = [{time:"10:20:20"}];
var text = "";
for(var i = 0; i<x.length; i++){
    var nowDate = new Date();
    var timeSplit = x[i].time.split(":");
    var minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(),    nowDate.getDate());
    minutesLeft.setHours(timeSplit[0]);
    minutesLeft.setMinutes(timeSplit[1]);
    minutesLeft.setSeconds(timeSplit[2]);
    text += "It is "+ (nowDate-minutesLeft) + " milliseconds left";
 }

console.log(text);

A:
For example x.time = 10:20:00. I want to take the current time minus my objects time.

Your code seems quite confused, it seems you're trying to do the following:

var time = '10:20:00';
var timeParts = time.split(':');
var now = new Date();

// Current date and time
console.log(now.toString());

// Subtract the hours part of the time from the hours part of the current time
now.setHours(now.getHours() - timeParts[0]);

// Subtract the minutes part of the time from the minutes part of the current time
now.setMinutes(now.getMinutes() - timeParts[1]);

// Subtract the seconds part of the time from the seconds part of the current time
now.setSeconds(now.getSeconds() - timeParts[2]);

// Adjusted date and time
console.log(now.toString());

// You can set the time parts all in one go:
var now2 = new Date();
now2.setHours(now2.getHours() - timeParts[0],
              now2.getMinutes() - timeParts[1],
              now2.getSeconds() - timeParts[2]);
console.log(now2.toString());

Lastly, copying a date is as simple as:
var date1 = new Date();
var date2 = new Date(date1);


text:
Q: Given: $\int_{a}^{b}f=\int_{a}^{b}g$, Can we always find some point $\theta$ in $[a,b]$ such that $f(\theta)=g(\theta)$ I noted something today, I don't know whether the result holds in general setting or not.

Suppose $f$ and $g$ are continuous function on $[a,b]$ such that
  $\int_{a}^{b}f=\int_{a}^{b}g$.
Can we always find some point $\theta$ in $[a,b]$ such that
  $f(\theta)=g(\theta)$

Example: Take $f=x^2$ and $[a,b]=[0,1]$ then $\int f=1/3$. Take $g=1/3$ then $\int_{[0,1]} g=1/3$
Now we can easily find some points which satisfy $x^2=1/3$.
There are lot of examples that I checked and every time I found that resullt holds good.
Can we write a proof?
Thanks for reading and helping out.

A: This is just Rolle's theorem disguised.
Let $h : [a,b] \to \mathbb R$ be defined as $h(x)  = \int_a^x (f(t)-g(t))dt$, then $h$ is differentiable on $(a,b)$ with $h'(x) = f(x) - g(x)$ and $h(a) = h(b) = 0$. By Rolle's theorem you can find a $\theta \in [a,b]$ such that $h'(\theta) = 0$, the same as saying $f(\theta) = g(\theta)$.

A: An equivalent formulation (via $h=f-g$) is

Suppose $h$ is a continuous function on $[a,b]$ such that
  $\int_{a}^{b}h(x) \, dx=0$.
Can we always find some point $\theta$ in $[a,b]$ such that
  $h(\theta)=0$?

and that is true. If  $h$ has no zeros then the intermediate value theorem implies that $h$ is strictly positive or strictly negative in the interval, and consequently
$\int_{a}^{b}h(x) \, dx \ne 0$.
(Strictly speaking, we must assume that $a \ne b$, because otherwise  $\int_a^b h(x) \, dx = 0$ for arbitrary functions $h$.)

A: Let $F(x):= \int_a^x f(t) dt, G(x):= \int_a^x g(t) dt$ and $H(x)=F(x)-G(x).$ Then we have:
$H(a)=H(b)=0$ and $H'(x)=f(x)-g(x).$  By Rolle, there is $\theta \in [a,b]$ such that $H'( \theta)=0.$

A: As $\int_a^b{f(x)dx} = \int_a^b{g(x)dx}$, we have
$$\int_a^b{(f(x)-g(x))dx} = 0$$
The Mean Value Theorem for Integrals shows that $f(c)-g(c)=0$ for some $c \in (a,b)$, hence $f(c)=g(c)$.


text:
Q: Standard horizontal vector fields on the bundle of linear frames I'm reading Kobayashi & Nomizu Fondation of differential geometry and I got stuck in understanding what makes the standard horizontal vectors $B_{k}$ defined globaly on $P$ where $P$ is the bundle of linear frames? in the following proposition from kobayashi P.122 .

A: Let $M$ be an $n$-dimensional manifold,  the bundle of linear frames $p:P\rightarrow M$ is the bundle such that for every $x\in M$, $P_x$ the fibre of $x$ is $\{u:T_xM\rightarrow \mathbb{R}^n\}$. This enables to define the fundamental form $\theta:TP\rightarrow \mathbb{R}^n$ such that for every $y\in P$ with $p(y)=x$ (remark that $y$ is linear map $y:T_xM\rightarrow\mathbb{R}^n$), $v\in T_yP$, $\theta_y(v)=y(dp_y(v))$. where $dp$ is the differential of the bundle map.
Let $\omega$ be a connection. It is defined by a distribution $H$ supplementary to the fibre of $p$, therefore the restriction of $\theta_y$ to $H_y$ is bijective. For every $u\in \mathbb{R}^n$ one can define $(\theta_y)_{\mid H_y}^{-1}(u)$ which is differentiable and globally defined.