text:
Q: matrix of strings in C I'm studying C language , so i'm new to C . I studied in High School just Pascal . I have an problem :
I have to sort alphabeticaly a bunch of strings that are read from the keyboard until the word "over" it's introduced .
I got an error : incompatible error :

incompatible types when assigning to type 'char[10]' from type 'char'

The code is :
    char *word = (char *)malloc(30);
    int i = 0 ;
    char matrixs[20][10];
    if(word == NULL)
    {
        exit(-1);
    }

do
{
    printf("Insert the word ");
    scanf("%s",word);
    if(strcmp(word,"over") != 0)
    {
        matrixs[i] = *word;
    }

}
while(strcmp(word,"over") != 0);

free(word);


text:
Q: Converted .py file to .exe and .exe file wont open properly So I recently managed to convert a .py file into .exe but the problem is that the .exe file wont open properly. Basically what happens is the command prompt opens for a second and then shows some code for 1 milisecond and closes. I did manage to get a screenshot of what the command prompt says.This keeps happening when I try to open it but not with just that file, but every .py file I convert into .exe
I made a simple code to check if it was only like that for my previous code but its for every code that I make. I also used PyInstaller to convert the .py file into a .exe
import customtkinter as tk
import sys
import os

root = tk.CTk()
root.state('zoomed')
root.wm_title("Test File")

frame = tk.CTkFrame(master=root, height=300, width=600)
frame.pack_propagate(0)
frame.pack(pady=200)`

lbl = tk.CTkLabel(master=frame, text="I like chicken nuggets.", font=("Bahnschrift", 30))
lbl.pack(pady=120)

root.mainloop()

If something is unclear about my explanation, please ask. Im on Windows 11 and I use VS Code.
I asked for help on Discord but no luck. Im hoping somebody could help me here. I want my .exe file to open up like a charm and do its job.

A: I suggest using auto-py-to-exe since it's easier to use. To install type this:
pip install auto-py-to-exe

To run type this:
auto-py-to-exe

Then you'll see something like this:

*

*Add the path to your script and you can change any setting you want

*Then you'll need to add the path to your custontkinter package

*Go to Additional Files -> Add Folder -> locate your python folder -> Lib -> site-packages -> customtkinter and add it to your exe

*Scroll down and you'll see this button. Press it and your exe should work

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call web Service by condition I am using 2 web service RepoServe1 and RepoServe2
When a user login there's flag isNew
if(isNew)
{
  main.RepoServe1.RepoClient objClient = new main.RepoServe1.RepoClient();
}
else
{
  main.RepoServe2.RepoClient objClient = new main.RepoServe2.RepoClient();
}
main.RepoServe2.Customer objCusotmer = new main.RepoServe2.Customer();
objCusotmer  = objClient.GetData();

this is the ordinary way to call the service.
I want to make function that returns the ClientObject of service.
Anyone knows the way ??


text:
Q: Need help figuring out which direction to implement Structure Map for an MVC 3 project I have been reading a number of tutorials on implementing Structure Map IoC/di into a MVC 3 project.  Only to get to the comments on the article and find what appears to be less favorable methods being used in the article either because they didn't use the scanning capabilities of Structure Map, or because they are using an Activator class when its not needed or not encapsulating the registration from the application and the list goes on.
I have a MVC 3 application that "currently" only uses DI for wiring up a NHibernate, its session in a unit of work, and injecting my controllers with a repository.  However, I want to switch over to Structure Map (since that is what is used at work and I want the experience) but I want to implement it with the direction that I have the most flexibility to use Structure Map with Filters, Model Binders...etc as well.
Does anyone have a good walk through for this recommendation they can point me to?

A: This is a pretty good walkthrough.


text:
Q: converting a tmx file to *anything* I have a tmx file with multiple languages defined for each term, and I can't find any way to convert it into individual anything -- gettext, php arrays, anything. My translation service does not let me download it in other formats (other than one per line plaintext without any keys, but that's a whole other problem).
I've only seen a po2tmx utility, not the other way around. Zend Framework 2's Zend\I18n documentation says it supports Tmx and Xliff, but it seems to.. not. I have no idea why, but
Is there any way at all I can convert this into some kind of usable format or do I have to end up writing some kind of weird thing that uses SimpleXML?

A: This converter can import TMX files containing up to two languages, and has various download options including PHP and PO files.
The API will also convert a TMX file to PHP Zend format as follows (using command line cURL):
 $ curl --data-binary @file.tmx 'http://localise.biz/api/convert/tmx/file.phps'


text:
Q: Repeat values with in the GROUP in SQL I am trying to repeat a row value in the subsequent rows with in GROUP. A Group can have one or more TAG. The requirement is to populate NEW_TAG in the row where the TAG is populated and in the subsequent rows until another TAG populated with in the same group  or we reach end of that GROUP.
Current Table      Required Table

GROUPID SEQ TAG    GROUPID SEQ TAG NEW_TAG
------- --- ----   ------- --- --- --------
1       1           1       1
1       2           1       2
1       3           1       3
1       4   4       1       4   4   4
1       5           1       5       4
1       6           1       6       4
1       7           1       7       4
1       8           1       8       4
2       1           2       1
2       2           2       2
2       3           2       3
2       4           2       4
2       5   5       2       5   5   5
2       6           2       6       5
2       7           2       7       5
2       8           2       8       5
2       9   9       2       9   9   9
2      10           2      10       9
2      11           2      11       9

A: select
    groupid,
    seq,
    tag,
    last_value(tag) ignore nulls over (
        partition by groupid
        order by seq
    ) as new_tag
from t
order by groupid, seq;

GRO SEQ TAG NEW_TAG
1   1    -   -
1   2    -   -
1   3    -   -
1   4   4   4
1   5    -  4
1   6    -  4
1   7    -  4
1   8    -  4
2   1    -   -
2   2    -   -
2   3    -   -
2   4    -   -
2   5   5   5
2   6    -  5
2   7    -  5
2   8    -  5
2   9   9   9
2   10   -  9
2   11   -  9

19 rows selected.


text:
Q: MariaDB error on startup, keeps restarting Suddenly there is this MariaDB error when trying to start my mariadb container after pushing an update to my drupal container via docker. The container keeps restaring over and over again. I rolled back the drupal update but the error persists and i also tried removing the mariadb image and rebuilding it, also no success, same error.
I researched and found out that there is a similar bug related to Mac/Win Systems after an MariaDB update but
1) i am using and ubuntu 16 system
2) i didnt update MariaDB
Link to the issue: https://jira.mariadb.org/browse/MDEV-16015
Any ideas?
2019-11-25  9:47:30 0 [Note] InnoDB: Ignoring data file './development/cache_update.ibd' with space ID 2698. Another data file called ./development/#sql-ib2713.ibd exists with the same space ID.
2019-11-25  9:47:30 0 [Note] InnoDB: Starting final batch to recover 36 pages from redo log.
2019-11-25  9:47:31 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
2019-11-25  9:47:31 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2019-11-25  9:47:31 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2019-11-25  9:47:31 0 [ERROR] InnoDB: preallocating 12582912 bytes for file ./ibtmp1 failed with error 28
2019-11-25  9:47:31 0 [ERROR] InnoDB: Could not set the file size of './ibtmp1'. Probably out of disk space
2019-11-25  9:47:31 0 [ERROR] InnoDB: Unable to create the shared innodb_temporary
2019-11-25  9:47:31 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2019-11-25  9:47:31 0 [Note] InnoDB: FTS optimize thread exiting.
2019-11-25  9:47:36 0 [Note] InnoDB: Starting shutdown...
2019-11-25  9:47:36 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2019-11-25  9:47:36 0 [ERROR] Plugin 'InnoDB' init function returned error.
2019-11-25  9:47:36 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2019-11-25  9:47:36 0 [Note] Plugin 'FEEDBACK' is disabled.
2019-11-25  9:47:36 0 [ERROR] Unknown/unsupported storage engine: InnoDB
2019-11-25  9:47:36 0 [ERROR] Aborting
2019-11-25 09:48:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server  started.
2019-11-25 09:48:37+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2019-11-25 09:48:37+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server  started.
2019-11-25  9:48:37 0 [Note] mysqld (mysqld 10.4.10-MariaDB-1:10.4.10+maria~bionic) starting as process 1 ...
2019-11-25  9:48:37 0 [Note] InnoDB: Using Linux native AIO
2019-11-25  9:48:37 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2019-11-25  9:48:37 0 [Note] InnoDB: Uses event mutexes
2019-11-25  9:48:37 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2019-11-25  9:48:37 0 [Note] InnoDB: Number of pools: 1
2019-11-25  9:48:37 0 [Note] InnoDB: Using SSE2 crc32 instructions
2019-11-25  9:48:37 0 [Note] mysqld: O_TMPFILE is not supported on /tmp (disabling future attempts)
2019-11-25  9:48:37 0 [Note] InnoDB: Initializing buffer pool, total size = 256M, instances = 1, chunk size = 128M
2019-11-25  9:48:37 0 [Note] InnoDB: Completed initialization of buffer pool
2019-11-25  9:48:37 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2019-11-25  9:48:38 0 [Note] InnoDB: Starting crash recovery from checkpoint LSN=11785883154
2019-11-25  9:48:38 0 [Note] InnoDB: Ignoring data file './development/#sql-ib2713.ibd' with space ID 2698. Another data file called ./development/cache_update.ibd exists with the same space ID.
2019-11-25  9:48:38 0 [Note] InnoDB: Ignoring data file './development/cache_update.ibd' with space ID 2698. Another data file called ./development/#sql-ib2713.ibd exists with the same space ID.
2019-11-25  9:48:38 0 [Note] InnoDB: Starting final batch to recover 36 pages from redo log.
2019-11-25  9:48:38 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
2019-11-25  9:48:38 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2019-11-25  9:48:38 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2019-11-25  9:48:38 0 [ERROR] InnoDB: preallocating 12582912 bytes for file ./ibtmp1 failed with error 28
2019-11-25  9:48:38 0 [ERROR] InnoDB: Could not set the file size of './ibtmp1'. Probably out of disk space
2019-11-25  9:48:38 0 [ERROR] InnoDB: Unable to create the shared innodb_temporary
2019-11-25  9:48:38 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2019-11-25  9:48:38 0 [Note] InnoDB: FTS optimize thread exiting.
2019-11-25  9:48:43 0 [Note] InnoDB: Starting shutdown...
2019-11-25  9:48:43 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2019-11-25  9:48:43 0 [ERROR] Plugin 'InnoDB' init function returned error.
2019-11-25  9:48:43 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2019-11-25  9:48:43 0 [Note] Plugin 'FEEDBACK' is disabled.
2019-11-25  9:48:43 0 [ERROR] Unknown/unsupported storage engine: InnoDB
2019-11-25  9:48:43 0 [ERROR] Aborting

A: Nevermind, i found the solution. I thought i had enough disk space left but i actually had not.
Here is the solution: https://superuser.com/questions/1267663/docker-mariadb-instance-not-starting-after-update


text:
Q: ¿Cómo puedo crear un sidebar con jQuery? No entiendo que falla me da errores como que el símbolo $ no está definido y demases, cuando es código que ya por desesperación he tenido que copiar y pegar de tutoriales.
Lo que me gustaría hacer, por si no se entiende mediante el código, es conseguir que pulsando/clicando sobre toggle-btn se abra un menú desplegable, que en este caso no es mas que un cuadro azul (cuadrolat).
Mi código (hay que pulsar en "Página completa" para ver el menu desplazándose):

$(".toggle-btn").on("click", function() {
  $(".cuadrolat").toggleClass("cuadro");
})
* {
  padding: "0px";
  margin: "0px";
}

.cuadrolat {
  position: fixed;
  left: -350px;
  top: 200px;
  width: 300px;
  height: 400px;
  background: blue;
  transition: 0.8s all;
}

.cuadro {
  position: fixed;
  left: 0;
  top: 200px;
  background: blue;
}

.toggle-btn {
  position: absolute;
  left: 230px;
  top: 20px;
  cursor: pointer;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="estilos.css">

  <meta name="viewport" content="width=device-width initial-scale=1.0">

    &#9776

Edit: acabo de probar el sidebar a través de la opción que permite esta misma pagina y lo curioso es que funciona, pero lo raro es que en chrome no lo hace y me da problemas en la consola.

A: Si estás cargando tu jquery al inicio de tu código, asegúrate de usar $(document).ready(), de esta forma aseguras que tu script se cargue después de cargar el contenido.
$(document).ready(function() {
   $(".toggle-btn").on("click", function() {
     $(".cuadrolat").toggleClass("cuadro");
   })
});

Por otro lado es recomendable colocar los scripts justo antes del cierre de la etiqueta body


text:
Q: MVC best practice with custom model binding for a certain scenario I'm working on an application at the moment that replicates a spreadsheet like table. I've been doing it all with ASP.NET model binding and a combination of ajax and a form POST. I've run into some issues where I think I might be better off creating a custom model binder.
Here's my application:

What we have there are stages of a project, and then a bunch of columns corresponding to each month with the predicted cashflows.
There is a button to the right of that image that lets you add an extra month column, and you can add a stage using the add stage button. Those two are done with AJAX, and then when you submit the form I want it to save all changes in one go via a POST.
I've managed to manoeuvre my way around using HTML helpers, view models and default model binding to get it working with adding columns:
In my main view, I have this to generate the rows/columns in the TBODY

            @for (int stageIndex = 0; stageIndex < Model.Stages.Count; stageIndex++)
            {
                @Html.EditorFor(x => x.Stages[stageIndex])
            }

I have a partial view for CashflowStageViewModel which currently looks like:
@model BWInvoicing.Ui.Models.CashflowStageViewModel

    @Html.HiddenFor(x => x.Stage)

                @Model.Stage

       @Html.TextBoxFor(x => x.Amount, new { @Class = "totalFee emTotal", CashflowStage = Model.Stage })

        @Html.TextBox("summation", 0, new { @Class = "emTotal summation", CashflowStage = Model.Stage, @readonly = "true" })

    @for (int i = 0; i < Model.Months.Count; i++)
    {

            @Html.HiddenFor(x => Model.Months[i].Date)
            @Html.TextBoxFor(x => Model.Months[i].Amount, new { @Class = "prediction", CashflowStage = Model.Stage })

    }

        @Model.Stage

The model binding works by creating IDs and name's that look like this:
id="Stages_5__Months_4__Amount" name="Stages[5].Months[4].Amount"

This causes some issues as I can add/delete rows between the time that these are generated and the time they are sent back to the server. I always try to keep using the default binding, but now it's holding me back so I think it's time I just created a custom model binder, rather than try dirty hacks to keep the indexes right.
My questions are these:

*

*Do you agree a custom model binder is the way to go? or is there an easy trick I'm missing

*What do you recommend I do in my custom model binder in terms of the names and ID's of my fields and cells in order to read it back in the http post. Is there some sort of guidance on how you should try and name them? Or should I just do string splitting?

By this I mean, for each cell should I have a hidden with name of STAGENAME_DATE and value of whatever they enter in the text box? and then I can have a model binder split those strings up to split the stage name and the date, parse them, and assign a value to the stage on that certain date? Or is there a more appropriate way of doing it?

A: I would recommend you taking a look at the Steven Sanderson's excellent article on this matter. He uses a custom Html.BeginCollectionItem helper which takes care of generating proper names of the input fields so that you don't have to worry about the binding. The default model binder will work out of the box.

A: I ended up reading about how you can use your own arbritrary indexes here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Non-Sequential Indices Well that's all great and all, but what happens
  when you can't guarantee that the submitted values will maintain a
  sequential index? For example, suppose you want to allow deleting rows
  before submitting a list of books via JavaScript. The good news is
  that by introducing an extra hidden input, you can allow for arbitrary
  indices. In the example below, we provide a hidden input with the
  .Index suffix for each item we need to bind to the list. The name of
  each of these hidden inputs are the same, so as described earlier,
  this will give the model binder a nice collection of indices to look
  for when binding to the list.

As a result I updated my viewmodel output to be following:
@model BWInvoicing.Ui.Models.CashflowStageViewModel

    @* Setup custom indexer to allow for add/remove rows *@
    @Html.Hidden("Index", Model.Stage)

    @* Store stage to rebuild view model, use bracket notation to allow default model binder to work correctly *@
    @Html.Hidden("[" + Model.Stage + "].Stage",
                   Model.Stage)

                @Model.Stage

        @Html.TextBox("[" + Model.Stage + "].Amount", Model.Amount,
                    new { @Class = "totalFee emTotal", CashflowStage = Model.Stage })

        @* Readonly javascript display of summation *@
        @Html.TextBox("summation", 0,
                    new
                        {
                            @Class = "emTotal summation",
                            CashflowStage = Model.Stage,
                            @readonly = "true"
                        })

     @* Output the month inputs, setup the correct indexes *@
    @for (int i = 0; i < Model.Months.Count; i++)
    {

            @Html.Hidden("[" + Model.Stage + "].Months[" + i + "].Date",
                   Model.Months[i].Date)
            @Html.TextBox("[" + Model.Stage + "].Months[" + i + "].Amount",
                    Model.Months[i].Amount, new { @Class = "prediction", CashflowStage = Model.Stage })

    }

        @Model.Stage

I'm not very happy with how messy the concatenation is, but it works pretty well.


text:
Q: Why the state of port is not listen while I've created a UDP monitor on this port using Netty? this's the code to create a channel:
 public class StunServer {

    private StunServer(){
        boolean win = GeneralUtil.windows();
        if(win){
            System.out.println("windows");
            this.group = new NioEventLoopGroup();
        }else{
            System.out.println("linux");
            this.group = new EpollEventLoopGroup();
        }
        this.bootstrap = new Bootstrap();
        bootstrap.group(group).channel(win?NioDatagramChannel.class:EpollDatagramChannel.class)
//                .option(ChannelOption.SO_BROADCAST,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new StunUdpMsgDecoder())
                                .addLast(new StunUdpMsgEncoder())
                                .addLast(new StunUdpMsgHandler());
                    }
                });
    }

    private static StunServer instance = new StunServer();

    public static StunServer getInstance(){
        return instance;
    }

    private final Bootstrap bootstrap;
    private final EventLoopGroup group;

    public Channel getChannel(int port){
        System.out.println("bind port:"+port);
        ChannelFuture channelFuture = bootstrap.bind(port).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(!channelFuture.isSuccess()){
                    channelFuture.cause().printStackTrace();
                    channelFuture.channel().close();
                }
            }
        }).syncUninterruptibly();
        return channelFuture.channel();
    }

    public void stop(){
        group.shutdownGracefully().syncUninterruptibly();
    }
}

and this's the main method:
public static void main(String[] args) throws Exception{
        StunServer server = StunServer.getInstance();
        try {
            Channel channel = server.getChannel(VarEnums.server1.getPort());
            channel.closeFuture().sync();
        }catch(Exception  e){
            e.printStackTrace();
        }finally {
            server.stop();
        }
    }

quite simple,I'm pretty sure that the message was sent successfully.but the decoder was not excuted.
and found that the port was not listened.
netstat -nap | grep java
as you see.and it should be like this?I guess.
img
anyway dudes help me,thanks.


text:
Q: Three.js - 2D + 3D Meshes Is posible to use Canvas2D to draw in the scene? Or, to be more precise, is posible to draw shapes and/or meshes which are independent of the position/rotation/zoom of the camera. We need to do some drawing in the application(not a GUI, as there are already Three.js components available for that functionality).

A: You can draw multiple scenes in three.js.  If you want a static scene that has a few objects and doesn't move with another scenes camera/lights/etc - just make two:
        window.scene = new THREE.Scene()
        window.sceneStatic = new THREE.Scene()

There's an example of Chrome Experiments doing this in their population globe.  They're using a second scene to do a atmosphere glow around the globe: http://workshop.chromeexperiments.com/globe/


text:
Q: dataframe with two conditions on two different columns I want to filter a dataframe based on two conditions on two different columns. In the example below,  I want to filter the dataframe df to contain rows such that it contains uids with value counts for the val column greater than 4 is more than 2.
df = pd.DataFrame({'uid':[1,1,1,2,2,3,3,4,4,4],'iid':[11,12,13,12,13,13,14,14,11,12], 'val':[3,4,5,3,5,4,5,4,3,4]})
For this dataframe, my output should be
 df
   uid  iid  val
0    1   11    3
1    1   12    4
2    1   13    5
5    3   13    4
6    3   14    5
7    4   14    4
8    4   11    3
9    4   12    4

Here, I filtered out the uid 2 becuase number of rows with uid == 2 and val >= 4 is less than 2. I want to keep only uid rows for which number of val with values greater than 4 is greater than or equal to 2.

A: you need groupby.transform with sum once check where val is greater or equal ge than 4. and check that the result is ge to use it as a boolean filter on df.
print (df[df['val'].ge(4).groupby(df['uid']).transform(sum).ge(2)])
   uid  iid  val
0    1   11    3
1    1   12    4
2    1   13    5
5    3   13    4
6    3   14    5
7    4   14    4
8    4   11    3
9    4   12    4

EDIT: another way to avoid groupby.transform is to loc the rows where val is ge than 4 and the column uid, use value_counts on it and get True where ge 2. then map back to the uid column to create the boolean filter on df. same result and potentially faster.
df[df['uid'].map(df.loc[df['val'].ge(4), 'uid'].value_counts().ge(2))]


text:
Q: How to use where clause with local variable without passing a parameter in Laravel I joined 2 tables and I want to display document_name from parent table(document_control_reviews) whose ID is currently posted in a child table (initial_approvals). The foreign key that holds the child document is 3.
If I hardcode the query with the ID = 3, I get the correct result just for testing purposes. But I want the documents to be display dynamically using $id instead of 3.

*

*This hardcode test works fine when I use 3 as ID:
 public function initial_approval(){
      $approval_files = DB::table('document_control_reviews')
                   ->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
                   ->leftJoin('files', 'document_control_reviews.file_id', '=', 'files.id')
                   ->select('document_control_reviews.*', 'initial_approvals.*', 'files.*')
                   ->where('initial_approvals.document_control_review_id', '=', 3)
                   ->get();
 }

*But I need a dynamic ID which is a local variable $id (as showed below):
 public function initial_approval(){
      $id = 3 //hardcoded. Here is where I'm stuck.
      $docId = DocumentControlReview::find($id);
      $approval_files = DB::table('document_control_reviews')
                   ->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
                   ->leftJoin('files', 'document_control_reviews.file_id', '=', 'files.id')
                   ->select('document_control_reviews.*', 'initial_approvals.*', 'files.*')
                   ->where('initial_approvals.document_control_review_id', '=', $id)
                   ->get();
 }

*This is what I don't want. I dont need to pass any parameter. I don't need any argument in the method call.

 public function initial_approval($id){
      $approval_files = DB::table('document_control_reviews')
                   ->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
                   ->leftJoin('files', 'document_control_reviews.file_id', '=', 'files.id')
                   ->select('document_control_reviews.*', 'initial_approvals.*', 'files.*')
                   ->where('initial_approvals.document_control_review_id', '=', $id)
                   ->get();
 }

A: This piece of code won't work the way you intend to because here id is a collection not an integer.
$id = DB::table('document_control_reviews')->select('id')->get();

You think id will be an integer like $id = 3 but in fact here $id = Collection({"id"=>3},...) get() always return a collection.
What you are trying to do is unclear please elaborate with an example.

A: I finally figured it out. I simply use the where clause in my query where the child ID is a positive integer. And I get exactly what I wanted in this code below:
$approval_files = DB::table('document_control_reviews')
                      ->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
                      ->select('initial_approvals.*', 'document_control_reviews.*')
                      ->where('initial_approvals.id', '>', 0)
                      ->get();


text:
Q: How do I solve this overloading error (c1) condition? How can I use the operator keyword or any other way to solve this problem?
#include <iostream>

struct Counter {
    Counter(int count_) : count(count_) {}
    int count;
};

int main() {
    Counter c{0};
    // Error: could not convert 'c' from 'Counter' to 'bool'
    if (c) { std::cout << "true\n"; }
    else { std::cout << "false\n"; }
}

A: You can define a user-defined conversion function to bool.
#include <iostream>

struct Counter {
    Counter(int count_) : count(count_) {}

    // User-defined conversion to bool
    operator bool() const {
        // Arbitrary predicate: return false if 0, true otherwise.
        return count != 0;
    }

    int count;
};

int main() {
    Counter c{0};
    if (c) { std::cout << "true\n"; } else { std::cout << "false\n"; }  // false
    c.count++;
    if (c) { std::cout << "true\n"; } else { std::cout << "false\n"; }  // true
}

Note, however, that it is quite semantically unclear what is meant by checking whether a counter is "true" or "false" - this answer only covers how you may implement such a user-defined conversion function, although it is arguably not a semantically sound approach for this particular class. Instead, a user may want to know, for a given counter class, e.g.:

*

*whether it is zero (bool isZero() const { return count == 0; }),

*whether it is saturated to some maximum value.


text:
Q: System.InvalidCastException: Can't convert VarChar to Int32 at MySqlConnector.Core.Row.GetInt32(Int32 ordinal) I have an API whith a Controller called Token Controller which validates a user and gives a token.
The problem is it was working just fine until now, I didn't change anything so I have no idea what happened. Please help.
Here is the code of my Token controller
    public TokenController(IConfiguration configuration, ICrUserInfoService crUserInfoService, IPasswordService passwordService)
    {
        _configuration = configuration;
        _crUserInfoService = crUserInfoService;
        _passwordService = passwordService;
    }

    [HttpPost]
    public async Task<IActionResult> Authentication(UserLogin login)
    {
        //if it is a valid user
        var validation = await IsValidUser(login);
        if (validation.Item1)
        {
            var token = GenerateToken(validation.Item2);
            return Ok(new { token });
        }

        return NotFound("Unvalid User");
    }
    private async Task<(bool, CrUserInfo)> IsValidUser(UserLogin login)
    {
        var user = await _crUserInfoService.GetLoginByCredentials(login);
        bool isValid;

        if (user == null)
        {
            isValid = false;
        }
        else
        {
            isValid = _passwordService.Check(user.Password, login.Password);
        }

        return (isValid, user);

    }

    private string GenerateToken(CrUserInfo user)
    {
        //Header
        var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]));
        var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
        var header = new JwtHeader(signingCredentials);

        //Claims
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, user.Username),
            new Claim("User", user.Displayname),
            new Claim(ClaimTypes.Role, user.Role.ToString()),
        };

        //Payload
        var payload = new JwtPayload
        (
            _configuration["Authentication:Issuer"],
            _configuration["Authentication:Audience"],
            claims,
            DateTime.Now,
            DateTime.Now.AddMinutes(30)
        );

        var token = new JwtSecurityToken(header, payload);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

As I said it was working just fine till now and here is the error
System.InvalidCastException: Can't convert VarChar to Int32
   at MySqlConnector.Core.Row.GetInt32(Int32 ordinal) in /_/src/MySqlConnector/Core/Row.cs:line 223
   at MySqlConnector.MySqlDataReader.GetInt32(Int32 ordinal) in /_/src/MySqlConnector/MySqlDataReader.cs:line 242
   at lambda_method23(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Crijoya.Infrastructure.Repositories.CrUserInfoRepository.GetLoginByCredentials(UserLogin login) in C:\Users\USER\source\repos\Api Crijoya\Crijoya.Data\Repositories\CrUserInfoRepository.cs:line 15
   at Crijoya.Core.Services.CrUserInfoService.GetLoginByCredentials(UserLogin userLogin) in C:\Users\USER\source\repos\Api Crijoya\Crijoya.Model\Services\CrUserInfoService.cs:line 20
   at Api_Crijoya.Controllers.TokenController.IsValidUser(UserLogin login) in C:\Users\USER\source\repos\Api Crijoya\Api Crijoya\Controllers\TokenController.cs:line 51
   at Api_Crijoya.Controllers.TokenController.Authentication(UserLogin login) in C:\Users\USER\source\repos\Api Crijoya\Api Crijoya\Controllers\TokenController.cs:line 40
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ExceptionContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

I am not sure the issue is in the code as I said it was working minutes ago and giving a correct Token. Please help I don't know how to approach this.
EDIT:
The repository of my entity CrUserInfo which contains the user and password
public CrUserInfoRepository(db_crijoyaContext context) : base(context) { }

        public async Task<CrUserInfo> GetLoginByCredentials(UserLogin login)
        {
            return await _entities.FirstOrDefaultAsync(x => x.Username == login.User);
        }

Here is my entity CrUserInfo
public partial class CrUserInfo : BaseEntity
    {
       // public int IdUserInfo { get; set; }
        public int IdUser { get; set; }
        public string Displayname { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public RoleType Role { get; set; }

        public virtual CrUser IdUserNavigation { get; set; }
    }

My Dto entity
public class CrUserInfoDto
    {
        public int Id { get; set; }
        public int IdUser { get; set; }
        public string Displayname { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public RoleType Role { get; set; }
    }

My database

Here is the script
CREATE TABLE `cr_userInfo` (
  `id_userInfo` int(6) unsigned NOT NULL AUTO_INCREMENT,
  `id_user` int(6) unsigned NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role` varchar(30) NOT NULL,
  PRIMARY KEY (`id_userInfo`) USING BTREE,
  UNIQUE KEY `id_user` (`id_user`) USING BTREE,
  CONSTRAINT `cr_userInfo_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `cr_user` (`id_user`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8

This is what it did before it stopped working

ONMODELCREATING CODE:
modelBuilder.Entity<CrUser>(entity =>
            {
                entity.HasKey(e => e.Id)
                    .HasName("PRIMARY");

                entity.ToTable("cr_user");

                entity.HasIndex(e => e.IdCompany, "company");

                entity.Property(e => e.Id)
                    .HasColumnType("uint(6) unsigned")
                    .HasColumnName("id_user");

                entity.Property(e => e.Active)
                    .HasColumnType("tinyint(1) unsigned")
                    .HasColumnName("active")
                    .HasDefaultValueSql("'1'");

                entity.Property(e => e.IdCompany)
                    .HasColumnType("int(6) unsigned")
                    .HasColumnName("id_company");

                entity.Property(e => e.Warehouse)
                    .HasColumnType("int(6)")
                    .HasColumnName("warehouse")
                    .HasDefaultValueSql("'NULL'");

                entity.HasOne(d => d.IdCompanyNavigation)
                    .WithMany(p => p.CrUsers)
                    .HasForeignKey(d => d.IdCompany)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("cr_user_ibfk_1");
            });

            modelBuilder.Entity<CrUserInfo>(entity =>
            {
                entity.HasKey(e => e.Id)
                    .HasName("PRIMARY");

                entity.ToTable("cr_userInfo");

                entity.HasIndex(e => e.IdUser, "id_user")
                    .IsUnique();

                entity.Property(e => e.Id)
                    .HasColumnType("uint(6) unsigned")
                    .HasColumnName("id_userInfo");

                entity.Property(e => e.Displayname)
                    .IsRequired()
                    .HasMaxLength(50)
                    .HasColumnName("displayname");

                entity.Property(e => e.IdUser)
                    .HasColumnType("int(6) unsigned")
                    .HasColumnName("id_user");

                entity.Property(e => e.Password)
                    .IsRequired()
                    .HasMaxLength(255)
                    .HasColumnName("password");

                entity.Property(e => e.Role)
                    .IsRequired()
                    .HasMaxLength(30)
                    .HasColumnName("role");

                entity.Property(e => e.Username)
                    .IsRequired()
                    .HasMaxLength(50)
                    .HasColumnName("username");

                entity.HasOne(d => d.IdUserNavigation)
                    .WithOne(p => p.CrUserInfo)
                    .HasForeignKey<CrUserInfo>(d => d.IdUser)
                    .HasConstraintName("cr_userInfo_ibfk_1");
            });

A: You will have to update your OnModelCreating code from this:
entity.Property(e => e.Role)
    .IsRequired()
    .HasMaxLength(30)
    .HasColumnName("role");

To indicate that it should be string:
entity.Property(e => e.Role)
    .IsRequired()
    .HasMaxLength(30)
    .HasColumnName("role")
    .HasConversion<string>();

According to the documentation, this should automatically convert between the database varchar type and the RoleType in C#:

For example, enum to string conversions are used as an example above, but EF Core will actually do this automatically when the provider type is configured as string using the generic type of HasConversion:


text:
Q: Error when deserialize JSON in C# I try de-serialize using method with  JavaScriptSerializer but it doesnt work. Not sure what is diffrent between my code and this example.
public void Main()
            {
              var dataResponse =@"{\"access_token\": \"NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby\", \"expires_in\": 28800}"

              JSON elements = new JavaScriptSerializer().Deserialize<JSON>(dataResponse);

              foreach (var item in elements.data)
              {
                 MessageBox.Show(item.access_token.ToString());
              }

            }
        public class JSON
            {
                public List<JSONElements> data { get; set; }
            }
        public class JSONElements
            {
                public string access_token { get; set; }
                public int expired_in { get; set; }
            }

A: First:
Your json string doesn't match properties in JSONElements class.The int member name is different.
Second:
Use JSON.Net while working with json.And you're deserializing to a Wrong type. Your json string doesn't contain any property data.It is an JSONElements object instead.
Third:
If you use the @ symbol with a string then you cannot escape characters
So try like:
    var dataResponse =@"{'access_token':'NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby','expires_in':28800}";
    var data = JsonConvert.DeserializeObject<JSONElements>(dataResponse);

And it works.

A: Check string encoding. Maybe something like this will work
var dataResponse =@"{""access_token"": ""NAonCg8KBHBpYXMSABoAJRAluFUSFAD2I2fXOrgvxInfWWG0UUsoqsby"", ""expires_in"": ""28800""}";


text:
Q: I've started a process, how do I call a method in that process My VB6 macro (COM) has successfully called into my managed code, COM-visible stub. My COM-visible stub has successfully started my WPF process (.exe). "Life is good". Now, I need to access a method within my WPF process and pass in some parameters.
I know that I can start my WPF process with parameters, but my VB6 macro will occasionally call my COM-visible stub with new parameters and I need to pass this into my running process.
I've thought of stopping/re-starting my process with new parameters, but that seems somewhat extreme.
How do I access a method withing my running process?

A: From the operating system's point of view, a process doesn't have methods. So the only way to communicate between processes is to use some kind of inter-process communication. In C#, you could using a Remoting IPC channel or WCF. Take a look here.

A: You can host a WCF service inside your WFP application. You can then have your COM code call the service.


text:
Q: Can SPARK use multicore properly? I've read about spark and I found out that spark is written in scala. Since scala is a functional language, like erlang, it can use multi core properly. Is that correct?
I'm wondering if I can use spark in distributed system which have multicore processors. Can a single task use all cores at the same time? I've read YARN will assign different cores on each different tasks, but in this case, it is a single task
And, is it just enough to use multi thread programming in JAVA (hadoop) to use all cores in each computer? Since linux scheduler is based on threads?

A: Yes, it can, as this is its stated purpose — to split and parallelize what is parallelizeable.  You can even specify amount of memory to be used by each executor.
However, some tasks cannot be parallelized, which is why sometimes Spark only occupies one core.
If you use the Spark shell, make sure you set the number of cores to use, as it is said in the answer to this question Why is Spark not using all cores on local machine
Source: official Spark docs https://spark.apache.org/docs/latest/configuration.html


text:
Q: What are the different suit benefits? I just arrived to Wellspring and I need to change my outfit. Coffer has 4 different suites available and before deciding which to pick I would like to know a bit more about those.

Which are the practical benefits of each one?

A: There are four different armors available to choose from. It appears that once you make your selection, that you are stuck with that one, so choose wisely. From left to right in your photo:
Wastelander
Allows you to get a discount on all cash items. This does not include vehicle upgrades. The exact discount you receive is 5%.
Roughneck
This offers better protection. I assume this is an armor upgrade of some kind, but don't know an exact % of increased protection you get.
Fabricator
This is described as you build like a pro, and when equipped says the items you build are improved. I don't know of the exact improvement that items you build get, but I would venture a guess that this means turrets and other buildable items might be a bit more durable and last a bit longer than without.
Crimson Elite
This armor is only available to people who have the Anarchy Edition, but it is a combination of all of the above three armors. You get all 3 benefits: 5% cash discounts, increased armor, and better engineering.
If you have the Anarchy Edition, there's no reason not to pick the Crimson Elite, as it gives you the full benefit of the other items.


text:
Q: Recover emails from Qmail I installed Kloxo on a dedicated server (CentOS 5) a long time ago.  Now I'm moving everything to another dedicated server with another control panel.
I moved all the websites and databases, but not the emails as I didn't need them.  Now I need them (just some), and I would like to know if it's possible to get them even in raw plain text from a database or anything in the old dedicated server. (I can't access the webmail anymore cause I messed up kloxo installation, and the original server just messes up... I don't want to reintall it until I recover the emails.)
So the question is, does Qmail store its email in a database? If so, where is that database?

A: Typically Qmail is deployed to store e-mail messages in the Maildir format, where each message is stored as an unique file. They can easily be copied.
The actual location of those files depends on your setup.
$HOME/Maildir/ is quite a common location.
It is common to combine Qmail with vpopmail and you could try vuserinfo -d emailaddress to find a Maildirectory.


text:
Q: Couldn't deduce template parameter from function parameter's default argument I'm trying to make a function which finds the minimum element in a range which satisfies a given condition:
#include <functional>
#include <iostream>
#include <vector>

template <typename It, typename Pred, typename Comp>
It minElementWhere(
    It begin,
    It end,
    Pred pred = Pred(),

    // Use less-than as the default comparator.
    Comp comp = std::less<decltype(*std::declval<It>())>()
) {
    It minElement = end;

    for (It it = begin; it != end; ++it) {
        if (!pred(*it)) {
            continue;
        }

        if (comp(*it, *minElement)) {
            minElement = it;
        }
    }

    return minElement;
}

int main() {
    std::vector<double> foo;
    foo.push_back(6);
    foo.push_back(10);
    foo.push_back(-3);
    foo.push_back(7);

    std::cout << *minElementWhere(
        foo.begin(),
        foo.end(),
        [](double val) {
            return val >= 0;
        }
    ) << std::endl;
}

But I get this error:
main.cpp: In function 'int main()':
main.cpp:40:5: error: no matching function for call to 'minElementWhere(std::vector<double>::iterator, std::vector<double>::iterator, main()::__lambda0)'
     ) << std::endl;
     ^
main.cpp:40:5: note: candidate is:
main.cpp:6:4: note: template<class It, class Pred, class Comp> It minElementWhere(It, It, Pred, Comp)
 It minElementWhere(
    ^
main.cpp:6:4: note:   template argument deduction/substitution failed:
main.cpp:40:5: note:   couldn't deduce template parameter 'Comp'
     ) << std::endl;

Comp isn't the return type, so it's not trying to deduce the return type, and it doesn't seem to me like there are ambiguous overloads of Comp (since there can only be one return type of dereferencing an It). Why am I getting this error, and how can I fix it?

A: You may want the following:
#include <iterator>
struct always_true{
    template<typename T>
    bool operator()(T&& val) const{
        return true;
    }
};

template <
    typename It,
    typename Pred = always_true,
    typename Comp = std::less<typename std::iterator_traits<It>::value_type >
>
It minElementWhere(
    It begin,
    It end,
    Pred pred = Pred(),
    Comp comp = Comp()
    ){
    It minElement = end;

    for (It it = begin; it != end; ++it) {
        if (pred(*it) && (minElement == end || comp(*it, *minElement))){
            minElement = it;
        }
    }

    return minElement;
}

A: You're expecting the template parameter Comp to be deduced from the default argument you provided for the corresponding function parameter. However, this is explicitly listed as a non-deduced context, meaning template argument deduction will fail for that template parameter (unless it can be deduced from elsewhere).
From §14.8.2.5/5 [temp.deduct.type]

The non-deduced contexts are:
  — ...
  — A template parameter used in the parameter type of a
  function parameter that has a default argument that is being used in
  the call for which argument deduction is being done.

To have template argument deduction succeed, provide a default argument for the template parameter, instead of the function parameter.
template <typename It,
          typename Pred,
          typename Comp = std::less<decltype(*std::declval<It>())>>
It minElementWhere(
    It begin,
    It end,
    Pred pred = Pred(),
    Comp comp = Comp()
) {
...
}

Live demo

A: This works for me:
template <typename It, typename Pred,
          typename Comp = std::less<decltype(*std::declval<It>())>>
It minElementWhere(
    It begin,
    It end,
    Pred pred = Pred(),
    Comp comp = Comp()
) {
    It minElement = end;

    for (It it = begin; it != end; ++it) {
        if (!pred(*it)) {
            continue;
        }

        if (comp(*it, *minElement)) {
            minElement = it;
        }
    }

    return minElement;
}


text:
Q: Bored to write app name in every heroku command though I got only 1 app Heroku toolbelt is always forcing me to write an app name at the end like this:
heroku pg:reset DATABASE --app [app_name]

Is there a way to set the default app to which all my CLI heroku commands will apply?

A: Going to post this just in case it helps someone else out. I had the same problem even though there was only one app installed. I had to switch my heroku remote url from https to git.
https://git.heroku.com/[heroku-app-1234].git
to
git@heroku.com:[heroku-app-1234].git
Then everything worked normally for myself.
git remote remove heroku
git remote add heroku git@heroku.com:[heroku-app-1234].git

A: If heroku is claiming that there are multiple apps in the folder you must have more than one remote in your .git/config.
Remove the extra heroku remote or set the default using git config heroku.remote remote_name

A: If you have the heroku-accounts plugin installed, switching to the heroku branch worked for me, as discussed in this answer.
To swap out your existing version of the heroku-accounts plugin, use:
heroku plugins:install https://github.com/heroku/heroku-accounts.git

Note that if you've followed @Moemars answer, you'll need to switch your git remote back to https.

A: If you run heroku from the Git repo linked to your Heroku app, you don't have to specify an app name (unless the repo is connected to multiple apps).

A: This seems to be the easiest way to fix the issue:
heroku git:remote -a <app_name>

A: Since this wasn't mentioned until now:
Apart from the git remote, the Heroku CLI also looks into the HEROKU_APP environment variable.
By using direnv, dotenv or similar tools for project-specific environments you can easily set the respective Heroku app for each project or directory.


text:
Q: Angular 4 - Fill select form value based on fetch Http GET method I have successfully fetch data using GET method in Angular. However now I want to put this fetched values as options in the select form but I cannot figure it out.
Any workaround with this?

A: You could make the select accessable via #select directive in your -Tag. Then you could simply reset your select @ViewChild with the fetched options.
You also might want to check out the reactive form guide at:
https://angular.io/guide/reactive-forms#the-data-model-and-the-form-model

A: If you get the data as an array, you can use ngFor in options to loop through the data.
<select class="form-control" >
    <option value=""></option>
    <option *ngFor="let item of data">{{item.optionName}}</option>
  </select>

Please check if this is the case.


text:
Q: Sort Table Data Default Issue I am trying to sort the table data. I am able to sort the data of the column onClick using a doSort function in Javascript but couldn't sort the data default on table load
Any ideas?

    Code
    Name

Thanks for your time !!

A: If you're not using jquery or a table sorting library, then you need to rely on when the browser signals that it's finished loading, and then call your own sorting method.  Something like this in your page should get you started:


text:
Q: How to get failed hosts in fabric I am using fabric and have a lot of hosts I have to process.
If any hosts fails I continue with execution with:
env.warn_only = True

However I want to get a list of hosts at the end that failed.  How?  I tried the below and I get nothing for either a success or fail.
error_list= []
success_list = []
@parallel
def my_run():
    try:
        sudo('sh test.sh')
        success_list.append(env.host)
    except:
        error_this.append(env.host)

error_list= []
success_list = []

A: Here is a code I use:
@parallel
@roles(env.roles)
def dummy_workhorse():
    return run('hostname')

@task
@runs_once
@with_settings(hide('everything'), skip_bad_hosts=True)
@needs_host
def check_hosts():
    down_hosts = []
    for host, result in execute(dummy_workhorse).iteritems():
        if not isinstance(result, str):
            down_hosts.append(host)
    if down_hosts:
        print('Following hosts are down:')
        for host in down_hosts:
            print(host)
    else:
        print('All hosts are up and running!')

A: Try using 'env.host_string' instead of 'env.host'
Ref: http://docs.fabfile.org/en/1.8/usage/env.html#host-string
error_list= []
success_list = []
@parallel
def my_run():
    try:
        sudo('sh test.sh')
        success_list.append(env.host_string)
    except:
        error_list.append(env.host_string)

error_list= []
success_list = []


text:
Q: Error using barcode scanner in iOS PhoneGap I am working on barcode scanning App. I have download the sample code from GitHub. When I run that project I get an error. Please help me to solve it.
ERROR: Plugin 'NetworkStatus' not found, or is not a CDVPlugin. Check your plugin mapping in Cordova.plist.
2012-11-28 14:12:36.198 BarCodeScannerCDV[942:40b] FAILED pluginJSON = {"className":"NetworkStatus","methodName":"getConnectionInfo","arguments":["NetworkStatus0"]}

Thanks.

A: I suggest you to used updated phonegap framework (Cordova 2.2.0), because this was a bug in Cordova 1.6.0.
Please see following comment by Shazron Abdullah in Google Phonegap group:
There is a new Cordova.plist because of the unified JS changes. Check
out the "Cordova Upgrade Guide" in your .dmg (Guides subfolder), or:
"Upgrading Cordova 1.5.0 projects to 1.6.0" step 8 of
https://github.com/apache/incubator-cordova-ios/blob/master/guides/Cordova%20Plugin%20Upgrade%20Guide.md#upgrading-older-cordova-plugins-to-16x

The BarcodeScanner plugin for iOS-Phonegap is stable one, please update your phonegap framework to 2.2.0.
In Phonegap 1.6.0 and below, network connection class name is Network Status but for Phonegap 1.6.1 and above, network connection class name is CDVConnection.


text:
Q: Entity Framework - printing EntityValidationErrors to log I get the follo0wing error when I print my log
Message: Validation failed for one or more entities. See 'EntityValidationErrors'
property for more details.; Stack Trace:    at
System.Data.Entity.Internal.InternalContext.SaveChanges()

The EntityValidationErrors object holds the full detailed error in different nodes.
What is the best way to print it?

A: You can try something like this
   foreach (var failure in ex.EntityValidationErrors)
    {
       string validationErrors="";

        foreach (var error in failure.ValidationErrors)
        {
           validationErrors+=error.PropertyName+"  "+error.ErrorMessage;
        }
    }

A: cleaner syntax:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
     Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
     throw;
}

A: Here are some extension methods:
/// <summary>
///     A DbEntityValidationException extension method that formates validation errors to string.
/// </summary>
public static string DbEntityValidationExceptionToString(this DbEntityValidationException e)
{
    var validationErrors = e.DbEntityValidationResultToString();
    var exceptionMessage = string.Format("{0}{1}Validation errors:{1}{2}", e, Environment.NewLine, validationErrors);
    return exceptionMessage;
}

/// <summary>
///     A DbEntityValidationException extension method that aggregate database entity validation results to string.
/// </summary>
public static string DbEntityValidationResultToString(this DbEntityValidationException e)
{
    return e.EntityValidationErrors
            .Select(dbEntityValidationResult => dbEntityValidationResult.DbValidationErrorsToString(dbEntityValidationResult.ValidationErrors))
            .Aggregate(string.Empty, (current, next) => string.Format("{0}{1}{2}", current, Environment.NewLine, next));
}

/// <summary>
///     A DbEntityValidationResult extension method that to strings database validation errors.
/// </summary>
public static string DbValidationErrorsToString(this DbEntityValidationResult dbEntityValidationResult, IEnumerable<DbValidationError> dbValidationErrors)
{
    var entityName = string.Format("[{0}]", dbEntityValidationResult.Entry.Entity.GetType().Name);
    const string indentation = "\t - ";
    var aggregatedValidationErrorMessages = dbValidationErrors.Select(error => string.Format("[{0} - {1}]", error.PropertyName, error.ErrorMessage))
                                           .Aggregate(string.Empty, (current, validationErrorMessage) => current + (Environment.NewLine + indentation + validationErrorMessage));
    return string.Format("{0}{1}", entityName, aggregatedValidationErrorMessages);
}

Usecase 1:
catch(DbEntityValidationException e) {
    Logger.WriteError(e.DbEntityValidationExceptionToString());
    throw;
}

Should Output:
StackTrace
Validation errores:
[EntityName]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]
[EntityName2]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]

Usecase 2:
catch(DbEntityValidationException e) {
    Logger.WriteError(e.DbEntityValidationResultToString());
    throw;
}

Should Output:
[EntityName]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]
[EntityName2]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]


text:
Q: python silently transposing rank 1 arrays import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print("x1\n",x1,"\n")
x2 = np.arange(3.0)
print("x2\n",x2)
print(x2.shape,"\n")
print("Here, the shape of x2 is 3 rows by 1 column ")
print("x1@x2\n",x1@x2)
print("")
print("x2@x1  should not be possible\n",x2@x1,"\n"*3)

gives
x1
 [[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]

x2
 [0. 1. 2.]
(3,)

Here, the shape of x2 is 3 rows by 1 column
x1@x2 =
 [ 5. 14. 23.]

x2@x1  should not be possible, BUT
 [15. 18. 21.]

Python3 seems to silently convert x2 into (1,3) array so it can be multiplied by x1. Or am I missing some syntax?

A: The arrays are being broadcasted by Numpy.
To quote the broadcasting documentation:

The term broadcasting describes how numpy treats arrays with different
  shapes during arithmetic operations. Subject to certain constraints,
  the smaller array is "broadcast" across the larger array so that they
  have compatible shapes. Broadcasting provides a means of vectorizing
  array operations so that looping occurs in C instead of Python. It
  does this without making needless copies of data and usually leads to
  efficient algorithm implementations. There are, however, cases where
  broadcasting is a bad idea because it leads to inefficient use of
  memory that slows computation.

Add the following line to your code where you explicitly set the shape of x2 to (3,1) and you will get an error as follows:
import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print(x1.shape) # new line added
print("x1\n",x1,"\n")
x2 = np.arange(3.0)
x2 = x2.reshape(3, 1) # new line added
print("x2\n",x2)
print(x2.shape,"\n")
print("Here, the shape of x2 is 3 rows by 1 column ")
print("x1@x2\n",x1@x2)
print("")
print("x2@x1  should not be possible\n",x2@x1,"\n"*3)

Output
(3, 3)
x1
 [[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]

x2
 [[0.]
 [1.]
 [2.]]
(3, 1)

Here, the shape of x2 is 3 rows by 1 column
x1@x2
 [[ 5.]
 [14.]
 [23.]]

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-c61849986c5c> in <module>
     12 print("x1@x2\n",x1@x2)
     13 print("")
---> 14 print("x2@x1  should not be possible\n",x2@x1,"\n"*3)

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 3 is different from 1)


text:
Q: Can I use AWS Cognito + IAM tools to control data access of users inside a Laravel application? There is a web application (Angular front-end, Laravel Backend, Postgress DB).
Current approach:
Laravel auth package is being used for user management, but due to expanding of scale and managing permission at their most granular level, where every user may have multiple roles on different organizations (one of the entities of the system) and so they should have different access levels to the data of each organization (very similar to how GitHub is managing users and go).
Challenge:
Implementing a custome user management piece is time-consuming with costs. Also, it will end up with too much complexity.
Looking forward to:
Use AWS Authentication and Access management tools, so that it covers everything about the user, roles, and permissions, and integrate that with my application.
What I found so far:
It seems that these tools are mostly for managing access of the AWS resources rather than managing access inside an external application (As far as I have gone). So the main question that remains here is, can't these services even simplify the process? If they can, how far and how?
Note: The most closely related answer I could reach so far is Can I have dynamic User specific permissions using AWS IAM / Cognito?


text:
Q: Importing environment variables from another script into the current shell I have a shell script that sets some environment variables that I run through the source command to affect the current shell. I created another shell script that refers to this shell script and I thought calling source inside this other shell script would have the same effect as calling directly on the current shell, but apparently that's not the case. Is there anyway to tell this invoker script that whatever applies to the shell it's running in should be reflected to the current shell?
The script with the environment variables begin with set -a so I thought doing something like
$(cat env_script.sh)

would export everything to the invoking shell, but this too doesn't seem to work.

A: Your approach does not work for two reason.
First of all, let's assume that your env_script.sh contained a statement to set a variable, for instance
X=5

If you execute the statement
$(cat env_script.sh)

you are asking bash to run the content of this script as commands, i.e. to execute a program with the funny name X=5.
Hence, the correct way to bring the definitions into your shell would be
. env_script.sh

The second problem is that according to your writing, you want to propagate the variable to the "invoker script". Now it's not entirely clear what exactly you mean by "invoker script", but if this invoker script is not in turn sourcing the script you are about to write, but invoking it as a child process, there is technically no way to pass the variables directly to the invoker.
In short, if a shell needs variables to be set, and the settings are defined in a separate file, it needs a source command to import those.

A: Here an example
#!/bin/bash

CURR_DIR=$(dirname $(readlink -f $0))
. ${CURR_DIR}/set-env-script.sh

# Add here your code...


text:
Q: Calculating the determinant of a matrices Show that
$
det
\left[ {\begin{array}{cc}
0 & 1 & 1 & 1\\
1 & 0& x & x\\
1 & x & 0 & x\\
1 & x & x & 0
\end{array} } \right]
$ = $-3x^2$
I have calculated a 2x2 determinant and 3x3 but never 4x4 so im quite confused on this

A: You can use the Laplace formula directly:
$$
\det\begin{bmatrix}
0 & 1 & 1 & 1\\
1 & 0& x & x\\
1 & x & 0 & x\\
1 & x & x & 0
\end{bmatrix}
= -\det\begin{bmatrix}1& x & x\\1 & 0 & x\\ 1 & x & 0\end{bmatrix}
  +\det\begin{bmatrix}1& 0 & x\\1 & x & x\\ 1 & x & 0\end{bmatrix}
  -\det\begin{bmatrix}1& 0 & x\\1 & x & 0\\ 1 & x & x\end{bmatrix}
$$
Switching two rows negates the determinant. We see that we can get the first determinant by switching the rows of the second determinant once and also by switching the rows of the third determinand twice. We are left with
$$ {}=-3\det\begin{bmatrix}1& x & x\\1 & 0 & x\\ 1 & x & 0\end{bmatrix}$$
Applying the formula for $3\times3$ matrices yields
$${} = -3 (0 + x^2 + x^2 - 0 - x^2 - 0) = -3x^2. $$

A: after $-R_2+R_3\to R_3$, $-R_2+R_4\to R_4$, $-xR_1+R_3\to R_3$, $-xR_1+R_4\to R_4$, $R_2+R_3\to R_3$, $\frac{-1}{2}R_3+R_4\to R_4$ and $R_1\leftrightarrow R_2$ we have triangular below matrix thus
$
det
\left[ {\begin{array}{cc}
1 & 0& x & x\\
0 & 1 & 1 & 1\\
0 & 0 & -2x & -x\\
0 & 0 & 0 & \frac{-3}{2}x
\end{array} } \right]
$ = $3x^2$
hence
$$
det
\left[ {\begin{array}{cc}
0 & 1 & 1 & 1\\
1 & 0& x & x\\
1 & x & 0 & x\\
1 & x & x & 0
\end{array} } \right]
 = -3x^2$$
Note that $\color{red}{-}$ is because of $R_1\leftrightarrow R_2$


text:
Q: Where could these files be coming from? I have a directory on a laptop (a MacBook Pro, in case this is relevant) in which I just discovered a bunch of garbage files that I did not knowingly or manually put there.  They appear to be duplicates of all the other files in the directory, with weird names, like these examples:

.BC.T_03m1Tf
.BC.T_0E4TU2
.BC.T_2TRggX
.BC.T_37qD4l
.BC.T_3J38mh
.BC.T_3Uve81
.BC.T_3We1Qm
.BC.T_3n4qxQ

There are exactly 197 of these files, and there are exactly 197 other files that do not follow this naming pattern, and the one that I first discovered has a similar or identical file in the normal files, so I'm guessing that all of them are created as duplicates by some (really annoying!) program.
Where do files with this naming pattern come from?  (Searching has turned up nothing.)
Manually deleting them is not a solution, as I need to know if there's a legitimate reason for them to be there (I doubt it!) and whether anything will break if I delete them, and where else they might be.


text:
Q: How to extract tabular summary data from an lm command in R I have data structured the following way:
group_id, months_from_start, perc_total_downloads, experience_ratio
1             1                    1.2                4
1             2                    1.7                6
…
235           1                    6.7                3
235           2                   18                  8
…

There are about 300 groups, each of which have 70 or so consecutive data elements.
I've issued the following script to estimate a second order polynomial for each of the groups.
s.1<-lm(xts(s[s$group_id == 1,][,-2], order.by=as.Date(s[s$group_id == 1,][,2]))$perc_total_downloads ~ poly(xts(s[s$group_id == 1,][,-2], order.by=as.Date(s[s$group_id == 1,][,2]))$months_from_start, 2, raw=TRUE))
s.235<-lm(xts(s[s$group_id == 235,][,-2], order.by=as.Date(s[s$group_id == 235,][,2]))$perc_total_downloads ~ poly(xts(s[s$group_id == 235,][,-2], order.by=as.Date(s[s$group_id == 235,][,2]))$months_from_start, 2, raw=TRUE))
s.599<-lm(xts(s[s$group_id == 599,][,-2], order.by=as.Date(s[s$group_id == 599,][,2]))$perc_total_downloads ~ poly(xts(s[s$group_id == 599,][,-2], order.by=as.Date(s[s$group_id == 599,][,2]))$months_from_start, 2, raw=TRUE))
s.1111<-lm(xts(s[s$group_id == 1111,][,-2], order.by=as.Date(s[s$group_id == 1111,][,2]))$perc_total_downloads ~ poly(xts(s[s$group_id == 1111,][,-2], order.by=as.Date(s[s$group_id == 1111,][,2]))$months_from_start, 2, raw=TRUE))
s.1537<-lm(xts(s[s$group_id == 1537,][,-2], order.by=as.Date(s[s$group_id == 1537,][,2]))$perc_total_downloads ~ poly(xts(s[s$group_id == 1537,][,-2], order.by=as.Date(s[s$group_id == 1537,][,2]))$months_from_start, 2, raw=TRUE))

For each one of these new variables I can issue a summary statement to reveal interesting information:
> summary(s.44375)

Call:
lm(formula = xts(s[s$group_id == 44375, ][, -2], order.by = as.Date(s[s$group_id ==
44375, ][, 2]))$perc_total_downloads ~ poly(xts(s[s$group_id ==
44375, ][, -2], order.by = as.Date(s[s$group_id == 44375,
][, 2]))$months_from_start, 2, raw = TRUE))

Residuals:
       Min         1Q     Median         3Q        Max
-0.0064004 -0.0017315 -0.0002022  0.0012087  0.0078436

Coefficients: (3 not defined because of singularities)
                                                                                Estimate Std. Error t value Pr(>|t|)
(Intercept)                                                                                1.993e-03  1.137e-03   1.753    0.084 .
poly(xts(s[s$group_id == 44375, ][, -2], order.by = as.Date(s[s$group_id == 44375, ][, 2]))$months_from_start, 2, raw = TRUE)1.0  7.769e-04  6.707e-05  11.583   <2e-16 ***
poly(xts(s[s$group_id == 44375, ][, -2], order.by = as.Date(s[s$group_id == 44375, ][, 2]))$months_from_start, 2, raw = TRUE)2.0 -9.258e-06  8.404e-07 -11.017   <2e-16 ***
poly(xts(s[s$group_id == 44375, ][, -2], order.by = as.Date(s[s$group_id == 44375, ][, 2]))$months_from_start, 2, raw = TRUE)0.1         NA         NA      NA       NA
poly(xts(s[s$group_id == 44375, ][, -2], order.by = as.Date(s[s$group_id == 44375, ][, 2]))$months_from_start, 2, raw = TRUE)1.1         NA         NA      NA       NA
poly(xts(s[s$group_id == 44375, ][, -2], order.by = as.Date(s[s$group_id == 44375, ][, 2]))$months_from_start, 2, raw = TRUE)0.2         NA         NA      NA       NA
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.002866 on 69 degrees of freedom
Multiple R-squared: 0.6619,Adjusted R-squared: 0.6521
F-statistic: 67.53 on 2 and 69 DF,  p-value: < 2.2e-16

For my purpose I need to transcribe this information into a table, which is incredibly tedious and time consuming cutting and pasting from this format:
group_id   intercept est  intercept stnd err    intercept t value   …
44375         1.993e-03         1/137e-03           1.753          ...
…

It would also be convenient for me to have conventional notation rather than scientific notation, but I imagine I could live without that.
Is there any way for me to do this without cutting and pasting by hand?
Thanks  --sw

A: The summary function just returns an R list. For example,
R> x = runif(10);y=runif(10)
R> m = lm(y ~ x)

The part you are interested in is the fourth element:
R> summary(m)[[4]]
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.44041     0.1768  2.4911  0.03746
x           -0.05899     0.3143 -0.1877  0.85579

This is just a matrix.

The above answers your question, but you code makes me want to weep! In particular, Read up on for loops and the plyr package. For example, I suspect the final two lines pretty much does everything you want:
##Load the package and create some data
library(plyr)
dd = data.frame(group_id = sample(1:3, 10, TRUE), x = runif(10), y=runif(10))

##Split up dd by group_id and do some regression
dd1 = ddply(dd, .(group_id), summarise, summary(lm(y ~ x))[[4]])

##Label the column names
colnames(dd1)[2:5] = c("Estimate"   "Std. Error" "t value"    "Pr(>|t|)")


text:
Q: DirectInput Unresolved External Symbol This one is driving me nuts. I've tried everything I can think of. Here are the relevant parts of the DirectInput code.
BOOL CALLBACK EnumDevicesCallback(const DIDEVICEINSTANCE* DeviceInfo,   VOID* Context);

if(DirectInput8Interface == DI_OK)
{
  DirectInput8InterfacePointer->EnumDevices(
    DI8DEVCLASS_GAMECTRL,
    (LPDIENUMDEVICESCALLBACKA) EnumDevicesCallback,
    NULL,
    DIEDFL_ATTACHEDONLY);
}

When I try to compile, I get the error:

unresolved external symbol "int __stdcall EnumDevicesCallback(struct
  DIDEVICEINSTANCEA const *,void *)"
  (?EnumDevicesCallback@@YGHPBUDIDEVICEINSTANCEA@@PAX@Z) referenced in
  function _WinMain@16.

As you can see, the external symbol the compiler can't find is related to the DIDEVICEINSTANCE parameter of the EnumDevicesCallback function. That shouldn't be, because I've included dinput.h and linked to dinput8.lib and dxguid.lib. I even tried defining DIDEVICEINSTANCE in my own code and got a message that it conflicted with a previous definition.
What could that error message mean?

A: That is not how callbacks work.
EnumDevicsCallback is not a function that exists. You're supposed to write your own function that EnumDevices will call for each device. Your function doesn't have to be called EnumDevicesCallback - that's an example.
For example, if you just wanted to print the name of each device, you might write
BOOL CALLBACK PrintDevicesCallback(const DIDEVICEINSTANCE* DeviceInfo,   VOID* Context)
{
    _tprintf("%s %s\n", DeviceInfo->tszProductName, DeviceInfo->tszProductName);
    return DIENUM_CONTINUE;
}

and then pass PrintDevicesCallback to EnumDevices.

A: I dare say, the culprit is BOOL CALLBACK EnumDevicesCallback(const DIDEVICEINSTANCE* DeviceInfo,   VOID* Context); - the function is likely a C-function, but you declare it in your .cpp file as C++-function.
Instead of doing that, include a proper .h file with the declaration, which is likely to have correct extern specified.


text:
Q: How to specify regex to pick up files dated 2019-02-20 onwards? I'm trying to fetch some file having the format
user_registrations.log.2019-03-20_04.

have specified file patter like
"user_registrations.log." + "[._a-zA-Z0-9]*"

I need the files dated 2019-02-20th on wards till 2019-03-20.
How do I specify this?

A: user_registrations.log.2019-0(2-2\d|3-[0,1]\d|3-20)_\d+

gives the matchig of:

A: In your specified case you could use this:
user_registrations.log.((2019-02-2[0-8])|(2019-03-((0[1-9]|1[0-9])|(20))))

Explanation:

*

*(2019-02-2[0-8]) all days of February (2019 is not leap)

*| means OR

*(2019-03-((0[1-9]|1[0-9])|(20))) for desired days of March. In this part of regex there are another ORs for days from 01 to 19 OR just for 2019-03-20, excluding for example 2019-03-00 which is not a proper date.

A: I used a diff approach.
Fetch all files and extract the date from the file Name, then convert it to milliseconds.
Compare this with the expected start and end date in Milliseconds.


text:
Q: Annoying autorenaming in Guake I love Guake drop-down terminal, but it has an annoying issue. When I use many tabs, I hate when the tab names rename each time I execute a command or navigate in one of them. I want to rename any tab and maintain the name in all sessions. For instance, when I use Midnight Commander and I enter in a long path folder, the tab expands and it's horrible. I see tab name mc [user@machine_name]:/weird/long/infinite/path when I navigate to /weird/long/infinite/path folder.
Can I have always the same name for each tab, even when renaming it manually?

A: I have found a way to disable the annoying renaming. I found in my guake Python script (in version 0.4.3-3) in lines 996 to 1002:
def on_terminal_title_changed(self, vte, box):
    use_them = self.client.get_bool(KEY("/general/use_vte_titles"))
    if not use_them:
        return
    page = self.notebook.page_num(box)
    self.tabs.get_children()[page].set_label(vte.get_window_title())

As the script shows, /general/use_vte_titles key prevents the autorenaming feature. It is Guake uses GConf to configure his options (explanation). I had to install gconf-editor package to edit Guake options executing sudo apt-get install gconf-editor. Then I executed gconf-editor, I browsed to /apps/guake/general and unmarked use_vte_titles key. Closed the editor. Next time I executed Guake the autorenaming feature was disabled.
Now, all the tabs are named Terminal and if I rename one, it still named all the session with the same name.
It would be helpful to add this key into the Guake preferences dialogue. But this solution worked anyway.

A: On the command line:
vim ~/.gconf/apps/guake/general/%gconf.xml
There should be an entry something like this:
<entry name="use_vte_titles" mtime="1404143215" type="bool" value="true"/>

Just change it to:
<entry name="use_vte_titles" mtime="1404143215" type="bool" value="false"/>

Save the file and restart guake.

A: Consider simply shortening the terminal title. The algorithm is defined in .bashrc, the terminal title will be respected by Guake as you have noticed:
My .bashrc contains the following:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PROMPT_COMMAND='PS1X=$(pwd | sed -r "s-^$HOME/--;s-^$HOME-~-;s-^(.[^/]*)/.*/-\1/.../-")'
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}"'$PS1X'"\a\]$PS1"
    ;;
*)
    ;;
esac

The host name is not shown anymore, and only the first and the last path component is shown:
$HOME -> ~
$HOME/some/deep/sub/dir -> some/.../dir
/usr/local/deeply/inside/there -> /usr/.../there
With this setting, the tab buttons are narrow enough but still contain useful information.
See also:
https://stackoverflow.com/q/3497885/946850
https://unix.stackexchange.com/q/26844/19205

A: just run
gconftool-2 --set /apps/guake/general/use_vte_titles --type boolean false

and restart your terminal,
easy as pie(3.14)

A: Yeah I had this issue as well and I am so surprised that it still appears in recent Guake versions. In the latest version I think there is an option to name the terminals as Terminal 1, Terminal 2 etc which doesn't help much either.
In the past few years I have employed a simple script in my .zshrc (I use Zsh terminal, but you can apply something similar in Bash).
function chpwd {
 if [ -e ".guakerc" ]; then
   setupguake
 else
    guake -r ${PWD##*/}
 fi
}

function setupguake() {
  . $(pwd)/.guakerc

  if ((${+name})); then
    guake -r ${name}
  fi
}

Essentially what this does, it monitors any directory change (through chpwd) and if a .guakerc file is found it runs it. Inside that file you can setup the guake title and many other things.
If no .guakerc file is found (the most usual case), it just sets the folder name as the terminal name. So if you are in a folder named /home/username/Development/social-app it will rename the terminal as social-app.
Hope it helps!


text:
Q: jQuery $(function() {}) vs (function () {})($) I understand that the following is shorthand for $( document ).ready():
$(function() {
    console.log( "ready!" );
});

I also understand what an anonymous JS function is, but does jQuery does anything special when it's called using one. I.e.:
(function() {
    console.log( "ready!" );
})($);

Is the latter just a normal anonymous JS function that uses jQuery (ie. it will NOT be considered shorthand for $(document).ready() and so will execute immediately)?
I feel this MUST have been asked before, but I can't find it if it has.

A: The first one is, indeed, a shorthand for $( document ).ready(), as pointed here.
But the second one is Immediately-Invoked Function Expression (IIFE), an anonymous function that is declared and immediately called.
In fact, the correct syntax (the argument is missing in your example) is:
(function($) {
    //my $ object is local now
})(jQuery);

In this case, you're calling the anonymous function with an argument.
The main advantage of this pattern (IIFE) is: isolate your code (you can create as many variables as you want and it'll be restricted to your anonymous function scope, unless you return something). This pattern is used a lot to define "private" and "public" methods. Like this:
var myModule = (function() {

    function privateFunction() { console.log("I can't be accessed from outside :("; }

    var privateVar = "me too :(";

    function publicFunction() { console.log("Hey! I'm here!"; }

    /* expose what you want */
    return {
        publicFunction: publicFunction
    }

})();

myModule.publicFunction(); //Hey! I'm here!
myModule.privateFunction(); //undefined;

You can also call it module pattern.
In your second example, you're calling the recently-created anonymous function with an argument, and your anonymous function receives that argument. This is a way of dependecy injection.
This way, you manipulate your global variable inside the function as local. Note that in the first example, we're passing a jQuery object and manipulating it inside your function as $. It's more difficult to someone override jQuery object, but, some script can re-assign the global dollar symbol, specially if you don't have full control of your app. This way, you're allways passing te jQuery object and manipulating it as $.
At the end, let me list some other advantages of passing parameters to a IIFE grabbed from here:

*

*it's faster: JavaScript first lookup into the local scope (before
climbing up). It may improve performance a bit.

*helps minification: minifier can now rename variables inside your
scope to a one letter word, reducing code size.

A:
Is the latter just a normal anonymous JS function that uses jQuery (ie. NOT shorthand for $(document).ready() and so will execute immediately)?

Yup, exactly, it's just a normal IIFE which takes the $ global variable as an argument
(function(dollarSignArgument) {
    console.log( "not really ready!" );
})($)

it'll be executed immediately

A: As you mentioned, the former is indeed a shorthand for $(document).ready().
As for the latter, this is just an Immediately Invoked Function Expression.
(function ($) {
    console.log('ready');
})(jQuery);

This function is simply an anonymous function which receives a parameter named $. The function is immediately invoked with some value (in this case jQuery) as the parameter.
IIFEs can also be used to isolate scopes and to avoid global variables in web applications which contain multiple JavaScript files. In this case a parameterless IIFE could be used:
(function () {
    // x is only accessible within this IIFE
    var x;
    // do something...
})();

For more information regarding Immediately Invoked Function Expression, see this question: What is the purpose of a self executing function in javascript?


text:
Q: Grouping by a Pandas dataframe and putting column back I have the following pandas dataframe:

I want to replicate the following SQL Query:
SELECT
cars,
city,
CASE WHEN miles_travelled=100 THEN SUM(complaints)/SUM(calls) ELSE 0 END as ratio
FROM table
GROUP BY cars, city

Here's the closest I've been:
table.groupby(['cars','city','miles_travelled'])['complaints','calls'].sum()

Can anyone help.

A: If you want to make ratio for just combinations of city and cars and ignore the cases as the quotient of the sum of complaints and calls ignoring rows where miles_travelled is 100 then this will work.
# filter to ignore rows where miles_travelled = 100
(table[table['miles_travelled'] != 100]
 # groupby city and cars and select the complaint and calls columns
 .groupby(['city','cars'])['complaints','calls']
 # sum the selected columns
 .agg(sum)
 # make the ratio column which is the sum of complaints / sum of calls
 .assign(ratio = lambda x: x['complaints'] / x['calls']))


text:
Q: How to trigger editor programmatically I have set up a producttable (kind of a shopping-cart) with one editable column (product amount) like this :
{
    title:"Aantal",
    field:"product_amount",
    align:"center",
    responsive: 3,
    validator:["required","numeric"],
    editor:amountEditor,
    cellEdited:recalcPrices,
    validator:["required","numeric","min:1","max:10"]
},

I am using a custom jquery amountEditor because this one looks somewhat nicer than the builtin editor. Rows are added to the shopping cart tabel (copied from another producttable) by a button click. Everything works fine but I would like that the user doesn't have to click on the editable columnfield himself. So the only one editable field should be triggered automatically / programmatically after the row is added to the table.
I think I have to combine these commands somehow in the table definition:
rowAdded:function(row){
    var cell = row.getCell("product_amount");
    cell.edit();
},

I tried everything but I cannot find the right combination to get this work. I can get var rowElement = row.getElement(), however var cells = row.getCells() or var cell = row.getCell(column) look empty. Any help is much appreciated.

A: You need to scroll to the row using the scrollTo function on the row component to ensure it is visible before you can trigger an edit on the cell, so your rowAdded callback wants to look like this:
rowAdded:function(row){
    row.scrollTo().then(function(){
        row.getCell("product_amount").edit();
    });
},


text:
Q: Im writing a class called discount.java and i am having issues processing negative values for quantity and price As I mentioned, I am writing a class called discount.java and TestDiscount.java; so far everything works but i am having issues getting the error message to display instead of the actual value when either quantity or price and negative values. Here is a little more info about the required output and what i have done so far:
The output must be of the form:
The quantity is: xx The unit price is: $xx.xx       The discount is: $xx.xx
Or
The quantity is: -xx    Quantity is negative. Cannot compute discount
Or
The quantity is: 150    The unit price is: -$15.00    The money is negative, cannot
compute discount amount
    public class discount {

     int quantity;
     double price;
     public static int NINETY_NINE = 99;
     public static int TWENTY = 20;
     private static int TEN = 10, FORTY_NINE = 49;
     public static double TEN_PERCENT = 0.10, FIVE_PERCENT = 0.05,
             TWO_PERCENT = 0.02, THREE_PERCENT = 0.03, ONE_PERCENT = 0.01 ;
     private double discount;
    // public static double discount_amount = discount * quantity * price;

    discount(int quantity, double price)
    {
          double discount = 0;
         //double d = discount;
           this.quantity = quantity;
           this.price = price;
     }
     boolean quantityOutOfRange()
     {
        return quantity < 0;
     }
     boolean priceOutOfRange()
    {
         return price  <  0;
    }
     public double getDiscount()
    {
       return discount;
    }

    public int getQuantity()
    {
        return quantity;
    }

    public double getUnitPrice()
    {
        return price;
    }

   public void calculate()
   {
      if (quantity > NINETY_NINE)
     {
         if (price > TWENTY)
                discount = TEN_PERCENT;

         else if ( price > TEN)
                 discount = FIVE_PERCENT;
        else
                discount = TWO_PERCENT;
     }
     else if (quantity > FORTY_NINE)
     {
    // calculate discount
         if (price > TWENTY)
                discount = THREE_PERCENT;
         else if ( price > TEN)
                 discount = TWO_PERCENT;
        else
                discount = ONE_PERCENT;
     }
     else
     {
    // calculate discount
         if (price > TWENTY)
                discount = TWO_PERCENT;
         else if ( price > TEN)
                 discount = ONE_PERCENT;
        else
                discount = 1;
     }
     if (quantity < 0)
         {
            System.out.println("Quantity is negative. Cannot compute discount");
         }
    //double discount_amount = discount * quantity * price;

   }

}

public class TestDiscount {

    public static void main(String[] arg) {

      String input = JOptionPane.showInputDialog("Enter the quantity desired "
                + ", and unit price "
                + "\n(Separated by spaces)");

        Scanner in = new Scanner(input);

        int quantity = in.nextInt();
        double price = in.nextDouble();

        discount current = new discount(quantity, price);
        current.calculate();
        System.out.println("\nDiscounts:\n");
        System.out.println("The quantity is: " + current.getQuantity()+ "\tThe unit price is = $ " + current.getUnitPrice() +
                "\tThe discount is = $ " + current.getQuantity()* current.getUnitPrice() * current.getDiscount());
        System.exit(0) ;
    }
   }

A: create new method called like
public boolean validated() {

  boolean ok = true;

  if (quantity < 0)
     {
        System.out.println("Quantity is negative. Cannot compute
                             discount");
        ok = false;
     }

  if (price< 0)
     {
        System.out.println("Price is negative. Cannot compute
                            discount");
        ok = false;
     }

   return ok;

}
Then in main
discount current = new discount(quantity, price);
if (current.validated ()) {
   current.calculate ();
}

A: In method Calculate first check for negative values
if (quantity < 0)
 {
    System.out.println("error message");
 }

if (price < 0)
 {
    System.out.println("error message");
 }


text:
Q: Get the price of tokens with web3js I wanted to know if it was possible to get the price of tokens with web3.js
For example I would like to get the price of WBTC on Uniswap and on SushiSwap
If you have any documentation or tutorials I'm interested
Thanks in advance

A: If you need any price information you could use chainlink oracle. Here is official docs for evm data feeds;
https://docs.chain.link/docs/using-chainlink-reference-contracts/ .
For a simple implementation example you can take a look at freeCodeCamp.org 's 32-hour course/lesson4 on youtube.
Also you can take a look at uniswap API ;  https://docs.uniswap.org/protocol/V2/reference/API/entities

A: If you want it to be compatible across multiple chains and multiple DEXs, the easiest way I could think of is to call the router by using the method getAmountsOut.
router.methods.getAmountsOut(amountIn, [inAddress, outAddress]).call()

amountIn would be 1 * Math.pow(10, inAddress token decimals)
inAddress is WBTC address
outAddress is USDC address
The output will be:
100000000,22397189858

Output[0] is amount in. Output[1] is amount out. You then have to divide that by
(1 * Math.pow(10, out address decimal), where you will get WBTCprice: 22397.189858
The only caveat of doing this method is that you need to know the stable pair that exist on that dex. Some dex may use WBTC/USDT, some may use WBTC/USDC.


text:
Q: Display images with Greek in filenames I'm building an e-shop in greek and i've come across an important issue regarding the image filenames that users upload to the linux server. If the filename contains greek chars then the file is uploaded normally but the images won't display in the browser. It's important to us that greek filenames are supported as we are counting on searches in greek for both web and image results on Google.

A: Maybe it's because of server charset filename issue? While your filename is in greek
server translate it at something like Αήι;;΄'.jpgand you have to img srcΑήι;;΄'.jpg

A: Why aren't they displaying?  Do you have an example?
I guess your options depend on how the images are being stored and served back to the users.  One thing you could do, in order to preserve the Greek text on the page for search results, may be to serve up the files with a non-Greek name and write the Greek part to the image's alt tag.
This, however, is assuming that you're storing the image files in conjunction with a database of some kind which would contain the necessary meta-data.  Basically, upon upload, the image's meta-data (alt text, maybe mime type, anything else important about it) would be written to a record in a database table and then the image file itself can be saved on the file system.  Its actual file name could just be the primary key from the table, which can just be an auto-increment field.


text:
Q: Structured Streaming - Running different function by key for message in the same batch I have implemented a Kafka consumer in PySpark (Spark 2.2.1)
I'm using the structured-streaming technology.
Each receiving batch contains messages where the value column is from different types (distinguish by the key), and its schema is different.
Now, I want to run different logic on the value column according to the message column key.
How can I group (by key) the received messages, and run specific logic for each group in PySpark?
Here is a snippet from my code, which works when all messages are of the same type:
lines = spark.readStream.format("kafka")...

schema_struct = get_schema_struct(...)

udf_identical_func = udf(
    lambda k,msg: do_something_identical_to_all_types(k,msg)), schema_struct
)

res = lines.select(udf_identical_func("key","value"))

udf_specific_toEach_type_func = udf(
    lambda k,msg: do_something_specific_to_each_type(k,msg)), schema_struct
)

res= res.select(udf_specific_toEach_type_func)
q = res.writeStream....
q.awaitTermination()

Thanks for any help


text:
Q: fontawesome pro in azure devops Has anyone been able to get CI builds working with fontawesome pro? Locally my build and fontawesome pro works because I've run these commands
npm config set "@fortawesome:registry" https://npm.fontawesome.com/ && \
npm config set "//npm.fontawesome.com/:_authToken"

However my CI build fails with the message
npm ERR! 404 Not Found: @fortawesome/fontawesome-pro@5.7.1

I've tried setting a .npmrc file but it didn't help. I also tried adding fontawesome's repo in service connections.

A: You should set the npm config to project level, by adding a .npmrc in the same folder as package.json
The contents of the .npmrc should be
@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken={your token}


text:
Q: Execute Thread 2 only after Thread 1 finishes Would any of the following codes snippets give a guarantee that pool1 will start only after the pool finished its execution?
Snippet 1
    ExecutorService pool = Executors.newFixedThreadPool(numberOfThreads);
    for (FObject action : list) {
        if (action instanceof FObject) {
            Runnable run = new ImageProcessRunnable(action);
            pool.execute(run);
        }
    }
    pool.shutdown();
    if (pool.awaitTermination(10, TimeUnit.SECONDS)) {
        pool.shutdownNow();
    }
    ExecutorService pool1 = Executors.newFixedThreadPool(numberOfThreads);
    synchronized (ImageHelper.getFilePaths()) {
        for (String file :ImageHelper.getFilePaths()) {
            pool1.execute(() -> {
                UploadFileAsAppUser.uploadFileAsBoxAppUser(file, boxLocation);
            });
        }
    }

    pool1.shutdown();
    if (pool1.awaitTermination(10, TimeUnit.SECONDS)) {
        pool1.shutdownNow();
    }

Snippet 2
    for (FObject action : list) {
        if (action instanceof FObject) {
            ImageProcessor processor = new ImageProcessor();
        }
    }

    ExecutorService pool1 = Executors.newFixedThreadPool(numberOfThreads);
    synchronized (ImageHelper.getFilePaths()) {
        for (String file :ImageHelper.getFilePaths()) {
            pool1.execute(() -> {
                UploadFileAsAppUser.uploadFileAsBoxAppUser(file, boxLocation);
            });
        }
    }

    pool1.shutdown();
    if (pool1.awaitTermination(10, TimeUnit.SECONDS)) {
        pool1.shutdownNow();
    }

In snippet 1, I am prcessing as well as uploading images in multiple threads. In snippet 2, I am processing images in single thread and uploading them in multiple threds.

A: A CountDownLatch is usually useful if you want to wait for one or more task to complete before starting another.


text:
Q: CSS3 sticky footer conflict with with jquery widgets I have implemented a sticky footer using CSS3.It works fine for the footer.But in the same page I have datepickers and other jquery widgets which popout from elements.
The problem occurs when scrolling.
On scrolling the widgets also move from their corresponding position that is not needed.
when removing the sticky footer style especially
body {
    height : 100%;
}

everything works fine like the datepickers an pop ups stay in their respective positions on scrolling.