text:
Q: Knockout template not loading? I have the following template:

I'm calling it in an onClick event like this:
        $("
", {
            class: "itemView",
            id: name,
            "data-bind": "template: { name: 'testTemplate' }"
        }).appendTo("body").draggable();

When I click the button to view the item, the div pops up but it's empty.  The HTML is just an empty DIV like this:

What am I missing?
update I have greatly simplified this question

A: I think you would need to call ko.applyBindings() again. But the usual approach in Knockout is to put the div in your HTML and use the visible binding to control whether the div is rendered.

A: Personally this is not how I would go about this sort of functionality.
I would have the div already on the page but hidden.
CSS
.itemView{ display: none; }
.show{ display: block; }

HTML

Hello World

This is a template that pops up

Then when you raise the click event, populate the myObject object with the selected object. Knockout will take care of everything.


text:
Q: How to make a mobile app screen size aware I want to make a Cordova (Phonegap) app that can be used on all devices. Including PC screens. I want the layout to adjust the number and layout of panels (views) acording to some simple instructions. I chose the Dojox.app because of the way the config.json file controls the MVC structure of the app.
A Dojox.app uses controllers to handle size and orientation events. The config.json file contains "controllers", "views" and other elements to define the MVC structure of the app
//Mandatory,listen App.emit events,implement dojox/app/Controller
"controllers": [
    //listens to "app-init, app-load"
    "dojox/app/controllers/Load",
    //listens to "app-transition, app-domNode"
    "dojox/app/controllers/Transition",
    //listens to "app-initLayout,app-layoutVIew,app-resize"
    "dojox/app/controllers/Layout"
],
//Mandatory, one or a set of views view1+view2+view3
"defaultView": "home+rightPane",
//Mandatory, Specify Application child views
"views": {
    "home":{
        //Mandatory set template for defaultViews
        "template": "app/views/home/home.html",
        "controller" : "app/views/home/home.js",
        "defaultView": "rightPane",
        /* when transitioning between tabs, use a flip animation by default */
        "defaultTransition": "slide",
        /* the views available to this scene */
        "views": {
            "rightPane":{
                //Mandatory set template for defaultViews
                "template": "app/views/rightPane/right.html",
                "controller" : "app/views/rightPane/right.js",
                "defaultView": "general",
                /* when transitioning between tabs, use a flip animation by default */
                "defaultTransition": "slide",
                /* the views available to this scene */
                "views": {
                    "about":{
                        "template": "app/views/about/about.html",
                        "controller" : "app/views/about/view.js"
                    },
                    "wifi":{
                        "template": "app/views/wifi/wifi.html",
                        "controller" : "app/views/wifi/wifi.js"
                    },
                    "general":{
                        "template": "app/views/general/general.html",
                        "controller" : "app/views/general/general.js"
                    },
                    "picture":{
                        "template": "app/views/picture/picture.html",
                        "controller" : "app/views/picture/picture.js"
                    },
                    "bright":{
                        "template": "app/views/bright/bright.html",
                        "controller" : "app/views/bright/bright.js"
                    }
                }
            }
        }
    }
},
...

I want to create a custom controller by changeing the "dojox/app/controllers/Layout" to allow for the addition and subtraction of views depending on the screen sizs.
Dojo already has the experimental 'dojox/mobile/ScreenSizeAware' module but it is limited to two panels and does not work (well I haven't been able to) in a MVC environment.
How to go about defining the views in the config.json file and how to create the controller.
I'll give it some serious thought over the next few days. If you have any suggestions please jot them down here.

A: You should take a look at the dojox/app/tests/mediaQuery3ColumnApp, it will show 1, 2 or 3 columns depending upon the screen size.  It includes a custom layout controller which uses css to handle the layout, and a custom navigation controller to try to handle which views to show when transitioning. It is not perfect, there are some issues with the navigation between views when the displayed columns has changed, but it should get you started.
You can run it here:
http://archive.dojotoolkit.org/nightly/checkout/dojox/app/tests/mediaQuery3ColumnApp/
And you can see the code here:
https://github.com/dmachi/dojox_application/tree/master/tests/mediaQuery3ColumnApp
Regards,
Ed

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Winforms Tabpage Size and ClientSize wrong I have created a user control that contains a TabControl with 2 TabPages. The position of the child controls on both TabPages is adapted programmatically in the Layout event of the user control.
The problem is, that the 2nd TabPage has not been drawn yet when the event is called and therefore this TabPage has a wrong Size and ClientSize.
How can I work around that?
I tried a loop with var oHandle = tabpage.Handle and tabctrl.SelectedTab = each tabpage already to force the creation of the TabPages, but this hasn't helped.
EDIT #1
I have found a first "bug" which is observed in the VS Designer:
When you drag a TabControl on the Form and then resize the it in the Designer, the size of the currently visible TabPage is updated. But the sizes of all other tabpages are not; they stay the same until any additional change is done on any control (tested!).
I admit that this situation is quite uncommon, so the sizes usually are updated, but nonetheless in my opinion it's a design flaw in the TabControl.
This design flaw becomes very relevant when the TabControl is resized at runtime! Here's a minimal example for repro (without UC, just a TabControl in a Form):
Form1.cs:
public Form1 ()
{
  InitializeComponent ();

  Debug.Print ("ctor before resize");
  Debug.Print ("TC: " + tabControl1.Size);
  Debug.Print ("T1: " + tabPage1.Size);
  Debug.Print ("T2: " + tabPage2.Size);

  tabControl1.Size = tabControl1.Size + new Size (10, 10);
  Debug.Print ("ctor after resize");
  Debug.Print ("TC: " + tabControl1.Size);
  Debug.Print ("T1: " + tabPage1.Size);
  Debug.Print ("T2: " + tabPage2.Size);
}

private void Form1_Load (object sender, EventArgs e)
{
  ... same as ctor, prints adapted ("load before/after resize)
}

private void Form1_Layout (object sender, LayoutEventArgs e)
{
  Debug.Print ("Layout");
}

private void button1_Click (object sender, EventArgs e)
{
  ... same as ctor, prints adapted ("button before/after resize)
}

Form1.Designer.cs:  (irrelevant parts removed)
private void InitializeComponent ()
{
  this.tabControl1 = new System.Windows.Forms.TabControl ();
  this.tabPage1 = new System.Windows.Forms.TabPage ();
  this.tabPage2 = new System.Windows.Forms.TabPage ();
  this.button1 = new System.Windows.Forms.Button ();
  this.tabControl1.SuspendLayout ();
  this.SuspendLayout ();
  //
  this.tabControl1.Controls.Add (this.tabPage1);
  this.tabControl1.Controls.Add (this.tabPage2);
  this.tabControl1.Size = new System.Drawing.Size (300, 120);
  //
  this.tabPage1.Size = new System.Drawing.Size (292, 91);
  //
  this.tabPage2.Size = new System.Drawing.Size (292, 91);
  //
  this.button1.Click += new System.EventHandler (this.button1_Click);
  //
  this.AutoScaleDimensions = new System.Drawing.SizeF (96F, 96F);
  this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
  this.ClientSize = new System.Drawing.Size (384, 262);
  this.Controls.Add (this.tabControl1);
  this.Controls.Add (this.button1);
  this.Load += new System.EventHandler (this.Form1_Load);
  this.tabControl1.ResumeLayout (false);
  this.ResumeLayout (false);
}
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.Button button1;

Debug prints:
ctor before resize
TC: {Width=300, Height=120}
T1: {Width=292, Height=91}
T2: {Width=292, Height=91}
Layout
Layout
ctor after resize
TC: {Width=310, Height=130}
T1: {Width=292, Height=91}    (wrong)
T2: {Width=292, Height=91}    (wrong)

Load before resize
TC: {Width=310, Height=130}
T1: {Width=302, Height=101}    (now correct because updated after ctor)
T2: {Width=302, Height=101}    (now correct because updated after ctor)
Layout
Layout
Load after resize
TC: {Width=320, Height=140}
T1: {Width=312, Height=111}    (correct because visible)
T2: {Width=302, Height=101}    (wrong again)
Layout

(TabPage1 selected, TabPage2 is not updated)
button before resize
TC: {Width=320, Height=140}
T1: {Width=312, Height=111}
T2: {Width=302, Height=101}    (still wrong: TabPage2 HAS NOT BEEN UPDATED WHILE THE UI-THREAD WAS IDLE)
Layout
Layout
button after resize
TC: {Width=330, Height=150}
T1: {Width=322, Height=121}
T2: {Width=302, Height=101}    (even more wrong)

(TabPage1 selected, TabPage2 is not updated)
button before resize
TC: {Width=330, Height=150}
T1: {Width=322, Height=121}
T2: {Width=302, Height=101}    (still wrong)
Layout
Layout
button after resize
TC: {Width=340, Height=160}
T1: {Width=332, Height=131}
T2: {Width=302, Height=101}    (again more wrong)

(TabPage2 selected, now TabPage1 is not updated)
button before resize
TC: {Width=340, Height=160}
T1: {Width=332, Height=131}
T2: {Width=332, Height=131}    (now correct because visible)
Layout
Layout
button after resize
TC: {Width=350, Height=170}
T1: {Width=332, Height=131}    (now wrong)
T2: {Width=342, Height=141}    (still correct because visible)

Based on this behaviour, the only solution that I currently have is calling the UpdateLayout() function of my UC on every call of tabControl1_SelectedIndexChanged (..).
EDIT #2
The "solution" of Edit #1 does not work because:
If the TabPages have little width, the controls on the pages are arranged vertically, causing a greater height of the respective TabPage. The overall height of the UC depends on the height of the TabControl, whose height depends on all TabPages, so the UpdateLayout() needs to have correct sizes of all TabPages, otherwise the UC height would change again later when another tab is selected, but it should be correct already at design time.

A: I found a quite simple solution to get the correct size of the TabPages:
All TabPages belong to the same TabControl, thus all TabPages have the same size, no matter what the Size property of the respective TabPage says.
Additionally, there's allways one TabPage that reports the correct size, which is the currently selected TabPage.
Therefore the size of every TabPage is TabControl.SelectedTab.Size.
EDIT:
Unfortunately this does NOT work if the whole TabControl is not visible, maybe because it's placed on a TabPage of another TabControl which is currently not selected.
However, I found another solution, which I posted as an answer on this question Can I force a TabControl's TabPages to resize *before* they're selected?, which actually is more or less a duplicate question of mine.
The relevant part of that answer:

[...]
  You have to add just 1 line to your code:
var oSize = i_oTabControl.DisplayRectangle.Size;

and avoid that it's probably optimized away by the compiler:
[MethodImpl (MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
public static void TabControlForceUpdateOfTabpageSize (this TabControl i_oTabControl)
{
  if (i_oTabControl == null)
    return;
  var oSize = i_oTabControl.DisplayRectangle.Size;
}

[...]


text:
Q: Booting stuck at : "A start job is running for /dev/mapper/cryptswap1" I'm using Ubuntu 19.04 on a Dell XPS 13 (9360) and Ubuntu booting gets stuck at the following step:
A start job is running for /dev/mapper/cryptswap1

I have to reboot 1 or 2 times before getting rid of it. But it keeps happening on the following boot.
The problem presumably started after updating the linux kernel from 5.0.0-16 to 5.0.0-17. So I thought it may be linked so I tried to reboot with previous kernel versions (5.0.0.0-* and even 4.15) but I still got the same problem.
Both fstab and crypttab are unmodifed since the first installation (2 years ago):
/etc/fstab
UUID=e15636da-994d-47db-a074-cfccedf6a740 /               ext4    noatime,errors=remount-ro 0       1
# /boot/efi was on /dev/nvme0n1p1 during installation
UUID=222E-0C93  /boot/efi       vfat    umask=0077      0       1
# swap was on /dev/nvme0n1p4 during installation
#UUID=10aaab21-f2ae-4e25-8f0b-55f444620108 none            swap    sw              0       0
/dev/mapper/cryptswap1 none swap sw 0 0

/etc/crypttab
cryptswap1 UUID=10aaab21-f2ae-4e25-8f0b-55f444620108 /dev/urandom swap,offset=1024,cipher=aes-xts-plain64

I'm out of ideas. Any thoughts about it ?

A: Two stabs in the darks.
Could you try to modify the swap description in /etc/fstab to
/dev/mapper/cryptswap1 none swap defaults 0 0

and in /etc/cryptab to
cryptswap1 UUID=10aaab21-f2ae-4e25-8f0b-55f444620108 /dev/urandom swap,offset=1024,cipher=aes-xts-plain64,size=512

A list idea would be to refer to the swap volume by its path rather than by its UUID, resulting in something like
cryptswap1 /dev/mapper/whatever--vg0-whatever /dev/urandom swap,offset=1024,cipher=aes-xts-plain64

Please not that it will not be crypt /dev/mapper/cryptswap1 as this is the device name after being turn in an encrypted swap by dm-crypt.

A: The problem is no longer happening since I upgraded from Ubuntu 19.10 (Eoan) to 20.04.1 (Focal). I don't know which part of the upgrade fixed it but it clearly did.

A: it worked for me
Step 1: Create new swap partition
Step 2: Open the /etc/crypttab file and change the UUID present in the file to the UUID of the new SWAP partition


text:
Q: What's the better way: 1 pipe and 1 socket, or 1 socket? I have a server-program which processes audio-data and passes it thru to the audio-drivers.
The server-program copies the audio-data and puts the copy in a named FIFO in a seconds thread.
If there is no client reading on the other side of the FIFO it does not matter, because it just blocks the FIFO-thread.
Now I would like to add a "control"-functionality like "increase volume, play faster etc." so the eventually connected client can control the server-program.
The important thing is: If the client eventually disconnects (through close() or abort) the server has detect this and should fall back into normal mode and forget all the commands from the client.
I have never used sockets until now, so I'm not sure what's the best way:

*

*use the FIFO from server->client as it is and add a socket just for client->server communication?

*use one socket to stream server->client and give commands from client->server (in byte-format?)
I would use "AF_UNIX, SOCK_STREAM" for the socket. Is #2 the better variant? And how can I determine if the client disconnected without a close()?

A: i vote option nr.2 and a possible solution for that is:
1-create socket[sock_stream....];
2-fork()[inherits the socket descriptor];
-father[use to read];
-son[use to write];

you can implement to detect a client disconnection when read() from socket descriptor returns 0bytes


text:
Q: Javascript Loan Calculator with While loop The program is supposed to determine how many months it will take to pay off the loan. Cannot seem to figure out how to fix my mathematical calculations. Not sure if it's the while loop that's wrong. Instead of determining the monthly payment based on user input, the input shows the total number of months (which i do not want. the program is supposed to do that). It is supposed to look like this: http://snag.gy/9vzGi.jpg Here is the code:

<title></title>

Javascript Loan Calculator

<form>

Enter Loan Amount

<input type="text" id="loanAmt" class="style">

Interest Rate (%)

<input type="text" id="intRte" class="style">

Monthly Payment Amount

<input type="text" id="monthlyPay" class="style">

<input type="button" value="Process Data" id="button" onClick="buildTable()">

</form>

A: If you want the input to be the monthly payment, please don't call the respective variable numpay.
In your case, it seems more practical not to calculate the number of months beforehand. You can use the while loop to build the table and calculate the duration of the loan at the same time:
function buildTable() {

    var amount = parseFloat(document.getElementById("loanAmt").value );
    var monthly = parseInt(document.getElementById("monthlyPay").value );
    var rate = parseFloat(document.getElementById("intRte").value );

    rate = rate / 100 / 12;

    var m = 0;    // number of months

    while (amount > 0) {
        var interest = amount * rate;
        var principal = monthly - interest;

        if (principal > amount) {
            principal = amount;
            amount = 0.0;
        } else {
            amount -= principal;
        }

        // build table: m + 1, principal, interest, amount

        m++;
    }

    // display table
}


text:
Q: Conditional Panel after acctionbutton clik does not work second time I am trying to create a Shiny Dashboard with different tabs and screens. The idea is that inside the Forecast tab; after clicking the "forecast details" button it apears a new screen with the forecast details. And after you can click the "back" button to go to "forecast" general screen again.
It work first time, but the second time I want to access the "forecast details" through the actionbutton it doesn't work any more; and it just displays the conditional pannel below in the same screen. Any idea about what I am missing?
Here is the ui.R
ui <- dashboardPage(
 dashboardHeader(title = "BLABLA",
              dropdownMenu(type = "notifications",
                           notificationItem(
                             text = "5 new products today",
                             icon("users")
                           ),
                           notificationItem(
                             text = "12 items reviewed",
                             icon("truck"),
                             status = "success"
                           ),
                           notificationItem(
                             text = "Data load at 86%",
                             icon = icon("exclamation-triangle"),
                             status = "warning"
                           )
              ),
              dropdownMenu(type = "tasks", badgeStatus = "danger",
                           taskItem(value = 20, color = "aqua",
                                    "Task 1"
                           ),
                           taskItem(value = 40, color = "green",
                                    "Task 2"
                           ),
                           taskItem(value = 60, color = "yellow",
                                    "Task 3"
                           ),
                           taskItem(value = 80, color = "red",
                                    "Task 4"
                           )
              )
   ),
  dashboardSidebar(
  sidebarMenu(id = "tabs",
            menuItem("Main", tabName = "Main", icon = icon("dashboard")),
            menuItem("Forecast", tabName = "Segments", icon = icon("th")),
            menuItem("KPI", tabName = "KPI", icon = icon("th"))
  )
 ),
dashboardBody(
shinyjs::useShinyjs(),
#First Tab
 tabItems(

  tabItem(tabName= "Main",h2("Welcome back Niek !",style="text-
   align:left;color:DarkSlateBlue ;font-size:300%; "),
          fluidPage(

            fluidRow((column(width = 12,
                             box("This app is an automated decision tool
             that...",br(),"Brief explanation on how to use the tool",
                                 width = NULL, height = 600, solidHeader =
       TRUE, status = "primary"
                             )
            )
            )
            )
          )
     ),

    tabItem(tabName= "Segments",
                        conditionalPanel(condition = "input.graph % 2 == 0
     || input.Back % 2 !=0",
            fluidPage(
              br(),
              br(),

              fluidRow(
                box(title="Newly Promotional Items",
                    width = 3,height = 200, background = "blue",br(),
                    actionButton(inputId="graph", label="Forecast Details", icon=icon("bar-chart")),
                   box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")

                ),
                box(
                  title = "Promotional forecast products", width = 3,height = 200, background = "light-blue",br(),
                  actionButton(inputId="graph2", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                ),
                box(
                  title = "Products with higher number of promotions", width = 3, height = 200,background = "light-blue",br(),
                  actionButton(inputId="graph3", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                ),
                box(
                  title = "Title 6",width = 3, height = 200,background = "light-blue",br(),
                  actionButton(inputId="graph4", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                )
              ),
              br(),

              # valueBoxes
              fluidRow(
                box(title="AX Products",
                    width = 3,height = 200, background = "purple",br(),
                    #splitLayout(
                    actionButton(inputId="graph5", label="Forecast Details", icon=icon("bar-chart")),
                    box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                    #)
                ),
                box(
                  title = "Historical High Bias products", width = 3, height = 200,background = "purple",br(),
                  actionButton(inputId="graph6", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                ),
                box(
                  title = "Low FCA products", width = 3, height = 200,background = "purple",br(),
                  actionButton(inputId="graph7", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                ),
                box(
                  title = "Number of alerts",width = 3,height = 200, background = "purple",br(),
                  actionButton(inputId="graph8", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                )
              ),
              br(),
              fluidRow(
                box(title="Products by Segment",
                    width = 3, height = 200,background = "yellow",br(),
                    actionButton(inputId="graph9", label="Forecast Details", icon=icon("bar-chart")),
                    box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                ),
                box(
                  title = "Products by SKU", width = 3,height = 200, background = "yellow",br(),
                  actionButton(inputId="graph10", label="Forecast Details", icon=icon("bar-chart")),
                  box(solidHeader =TRUE,"blabla",title="Product Details",align="right",height = 100, color="black")
                )
              ),
              verbatimTextOutput("debug")
            )
          )
  ),
  tabItem(tabName = "KPI",
          h2('KPI DASHBOARD'),br()
          #,img(src='Picture1.png', align = "right")
  )
),

conditionalPanel(
  condition= "input.graph % 2 != 0 ",
  fluidPage(
    fluidRow(column(width = 12,
                    box(
                      title = "Product Forecast 1", align = "center", width = NULL, height = 200, solidHeader = TRUE, status = "warning"
                    )
    )
    ),
    fluidRow(column(width = 12,
                    box(
                      title = "Product Forecast 2", align = "center", width
= NULL, height = 200, solidHeader = TRUE, status = "warning"
                    )
    )
    ),
    fluidRow(column(width = 12,
                    box(
                      title = "Product Forecast 3", align = "center", width
  = NULL, height = 200, solidHeader = TRUE, status = "warning"
                    )
    )
    ),
    actionButton("Back", "Back")
    )

   )
  )
)

And here is the server.R
shinyServer(function(input, output,session) {

   observe({
  if (input$graph == 0) {
  return()
 }

 })

observe({

  if (input$Back== 0) {
  return()
   }
  })


text:
Q: Cannot convert char to an item in classlibrary in c# Completely new to coding and thought I had a good chunk down before this issue. I want to save a new record to sql but trying to capture the id of a chosen item from another table. Thought I could use the same foreach structure I did when I was capturing a list of data, but this is of a single record in a combobox. What am I doing wrong here?
Public Usermodel createnewlogin(Usermodel model)
{
    Using(IdataConnection connections = new System.data.Sqlclient.SqlConnection(
        GlobalConfig.cnnstring(db))
    {
        var x = new DynamicParameters();
        x.Add("@name1", model.user1);
        x.Add("@name2", model.user2);

        foreach(Profession p in model.professionid)
        {
            x = new DynamicParameters();
            x.Add("@name1", model.user1);
            x.Add("@name2", model.user2);
            x.Add("@professionid", p.id);

            Connection.Execute("dbo.madeup_insert", x,
                commandType: CommandType.StoredProcedure);
        }

        return model;
    }
}

The foreach gives the following error: "Cannot convert type 'char' to classlibrary.Profession"
professionid is of type int. It is the incremented id that idenifies the Profession class as a whole in the Usermodel class. When the user selects this value, they are selecting the ProfessionName from the Profession class, which is a type string. So I am trying to save the id associated with that string  from one class, in another based on the ProfessionName chosen in the combobox drop-down. The user never sees and would not know the id qt any point, which is why they select the ProfessionName, not the id itself.

A: In your line of code:
foreach(Profession p in model.professionid)

model.prefessionid is an object of type char.  Under that code you are adding the paramter p.id.  I'm assuming that is the chosen item id you are looking for?  You need to determine what list of data the chosen id is from.  You said that the value you are looking for is supposed to be a single record in a combobox.  So then, instead of the model.professionid you should grab the SelectedValue property or the Text value of the combobox after the user has made their selection.  You will not need a foreach statement for this.
I will need a little more in-depth explanation or code to help you get the desired outcome you are looking for.


text:
Q: Grails createCriteria and executeQuery let's say i have this classes which are being mapped to SQLServer:
class Statistic {
    Servicos servico
    int totalTime
    Date date

    static constraints = {
    }
}

class Servicos {

    String name
    String description

    static constraints = {
    }
}

Using SQL Queries like this:
select name, description, media,frequencia from TvMagazinePlus.dbo.servicos as t1 join (

    SELECT TOP 1000
          [servico_id]
          ,avg([total_time]) as 'media'
          ,COUNT([servico_id]) as 'frequencia'
      FROM [TvMagazinePlus].[dbo].[statistic] where date between now and yesterday  group by [servico_id]) as t2 on t1.id = t2.servico_id

I get this table:

I now need to render the result in JSON. My problem is, i find executeQuery too difficult to accomplish this. Is there any way i can do this using HQL like createCriteria?

A: You could easily set that result in a list of beans and then serialize them in JSON with any framework like Jackson or anything...
I don't know grails but with Hibernate you can use criteria to execute subqueries, according to the hibernate documentation:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html
DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)
    .setProjection( Property.forName("weight").avg() );
session.createCriteria(Cat.class)
    .add( Property.forName("weight").gt(avgWeight) )
    .list();

This obviously return the cats that have a weight greater than the average cat' weight, using a subquery to get that average cat's weight.
To map the result into an XML/JSON serializable bean you can simply use a AliasToBeanResultTransformer on that criteria and then serialize your objects ;)


text:
Q: How to remove a blank page after maketitle, scrbook There appears a blank page between the title page and the table of content. Many had this problem, but no solution works for me, because no one used the scrbook class.
\documentclass[DIV=10,openany]{scrbook}

\title{Documentation}

\begin{document}

\maketitle

\tableofcontent

\end{document}

A: Before I provide a solution, I want to quote the KOMA manual.

With the standard classes, the back of the title page of a double-side
  print is left empty. However, with KOMA-Script the back of the full
  title page can be used for other information. Exactly two elements
  which the user can freely format are recognized: titlebackhead and
  titlebackfoot . The head can reach up to the foot and vice versa. If
  one takes this manual as an example, the exclusion of liability was
  set with the help of the \uppertitleback command.

 Scrguien page 60
So the blank page is related to the information provided by \uppertitleback{} and \lowertitleback{}. There is no way to suppress this by options if you use the standard maketitle definition.
You  can do the following:

*

*Use the option titlepage=false. In this way the environment titlepage isn't used and all elements are part of the text.

*Use either \uppertitleback{} or \lowertitleback{}. So you need the extra page.

*Redefine the default command \maketitle (see below)

*Use an alternative titlepage (German): http://komascript.de/titlepage
ad 3:
\usepackage{xpatch}
\makeatletter
\xpatchcmd{\maketitle}{\if@twoside\next@tpage}{\iffalse}{}{}
\makeatother


text:
Q: How can i keep class that extends android.support.v4.app.FragmentActivty? How can i keep class that extends FragmentActivty ?
I used -keep public class * extends android.support.v4.app.FragmentActivity
after that the class exists but when i start the application it doesn't work and i have an error that he can't find the class


text:
Q: How is time of supplied real time clock module maintained without battery? I am thinking about purchasing this RTC ( real time clock ) module.
Since this particular item comes supplied without a battery, I wonder how the time is being kept running in the chip since it's manufactured and until a battery is plugged in the socket ?
EDIT :
After checking the plenty of nice answers that this question has received, I believe I didn't form my question well.
Real time clock is supposed to give you information about year ( counting leap years ), month, day of the week, time ( hours, minutes, seconds ). So if the module arrives without battery installed, what time will it show ? And how can you set the correct time on the chip ?

A: Page 8 of DS1307 datasheet states the following:

On first application of power to the device the time and date registers are typically reset to 01/01/00 01 00:00:00.

So, when you apply power to the RTC, it will typically come with its time reset to zeroes. However, as James Cameron pointed out in his answer, the only guaranteed response to power failure is the clock halt (CH) bit 7 of register 0. So, the data may be corrupt at start up. In any case, after you apply power to the device, you'll have to set the time yourself. Then it will start ticking by itself.
Communication with the DS1307 RTC is done via the I2C protocol. One would usually use an MCU to control it. I usually use an ATmega328P to do so without problems. You can use a PIC, Raspberry Pi or an Arduino, or any other popular MCUs out there.
Wiring it is simple enough. Just follow the DS1307 datasheet. The most usual setup is the following:

*

*Wire 5V and GROUND terminals to your board main power supply.

*Place a 3V coin cell on its holder. That will let the RTC to keep time while main power is disconnected.

*Wire the SDA and SCL to the corresponding pins at your MCU board. On the ATmega328P, those are pins 27 and 28, respectively. On Arduino Uno, these are analog input pins A4 and A5 respectively.

*The SQ terminal is likely to be wired to the DS1307 SQW/OUT output pin (Square Wave/Output Driver). When enabled, the pin outputs one of four square-wave frequencies (1Hz, 4kHz, 8kHz, 32kHz). It is useful for triggering interrupts in your code, to let the program know when the time (seconds) has changed, for example.

*There is another terminal, DS, that I'm not familiar with. Make your you find and read the module manual and understand what it is for while designing the board that will use the RTC.

In your program, you need make your MCU talk to the RTC using the I2C protocol. You can do it by yourself, but the easiest is to just find a library that makes the communication simpler to you. For Arduinos, there's a few libraries out there that were developed specifically to control the DS1307. These libraries will provide functions that you can call from your program to set the initial (current) time and then to read the time whenever needed.
I hope this update addresses your question.

A: It needs a battery.  It is shipped without a battery so as to avoid triggering regulations on shipping batteries, and to avoid having to stock batteries that will eventually lose shelf life.

A: The module doesn't come with a battery. But from the picture, it does come with the battery holder. Meaning you just have to buy your own battery.
As for the default date/time, it will be set to either epoch (arbitrary start date chosen by the designers), or more likely reset to all Zeros, at powerup, and immediately should start counting up. It will keep time until VCC goes bellow its minimum (if VBat is also bellow its minimum or no battery installed). This can be confirmed in the datasheet for which ever specific IC your module has, or a similar IC with the same eeprom format like the Maxim/Dallas DS1037.
To set/read the time, apply power, and use i2c messages as specified by the datasheet.

A: I disagree with Ricardo a little bit, where he says

it will come with the time reset

The reset data pattern is only typical, it isn't guaranteed.  In the datasheet, the only guaranteed response to power failure is the clock halt (CH) bit 7 of register 0.  If you care about the data, your software must check the CH bit, and if it is set clear the date and time, even if it is clear already most of the time you see it.
I've spent days characterising the response to partial and total power failure of RTC chips on the OLPC XO laptop, and captured plenty of evidence of corruption of the data registers when VBAT was marginal.  CH was reliable.

A: The time isn't kept running: you have to set it every time the RTC loses power (this is why it will often have a separate battery). It is only running when it has power.


text:
Q: Improper DataGrid Height Resizing with Text Wrapping The Problem
I have a DataGridin a wpf application.
The problem has to do with how the DataGrid looks after certain window resizing events.
Whenever the user shrinks the window and then enlarges it again, the rows of the DataGrid shrink back down (because of the text wrapping), but the height of the DataGrid itself doesn't shrink.
The resulting effect is that there appears to be a border around the DataGrid that is too long.
This border shrinks back down as soon as the user decreases the height of the window. This border is also too long when the application is started.
Xaml
<Window x:Class="SampleApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="WrappingTextBlock" TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
        <Style x:Key="WrappingTextBox" TargetType="TextBox">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </Window.Resources>

    <Grid>
        <Border>
            <ScrollViewer>
                <StackPanel>
                    <DataGrid ItemsSource="{Binding Objects}" HorizontalAlignment="Stretch" Margin="5" AutoGenerateColumns="False" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
                        <DataGrid.Columns>
                            <DataGridTextColumn MinWidth="15" Width="Auto" Header="#" Binding="{Binding Number}"/>
                            <DataGridTextColumn MinWidth="65" Width="Auto" Header="Style" Binding="{Binding Style}"/>
                            <DataGridTextColumn MinWidth="80" Width="*" Header="Description" Binding="{Binding Description}" ElementStyle="{StaticResource WrappingTextBlock}" EditingElementStyle="{StaticResource WrappingTextBox}"/>
                        </DataGrid.Columns>
                    </DataGrid>
                </StackPanel>
            </ScrollViewer>
        </Border>
    </Grid>
</Window>

Code-Behind
using System.Collections.Generic;
using System.Windows;

namespace SampleApp {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            DataContext = new ViewModel();
        }
    }

    public class ViewModel {
        public ViewModel() {
            Objects = new List<MyObject>() {
                new MyObject() { Number=1, Style="Good Style", Description="Small description", },
                new MyObject() { Number=2, Style="Bad Style", Description="This is a medium length description that you are reading.", },
                new MyObject() { Number=3, Style="Awesome Style", Description="This is a long description that you are reading because I repeat the message. This is a long description that you are reading because I repeat the message.", },
            };
        }
        public List<MyObject> Objects { get; set; }
    }

    public class MyObject {
        public MyObject() { }
        public int Number { get; set; }
        public string Style { get; set; }
        public string Description { get; set; }
    }
}

A: Set the TextWrapping to Wrap for that column in your code behind after it's loaded. Worked for me.


text:
Q: Angular js phonecat with Firebase instead of .json files I am new to firebase and I am trying to retrieve the data in this service from firebase instead of json files but I haven't been able to get it to work. It is based on the angularjs phonecat example
.factory('Article', ['$resource', FIREBASE_URL, $firebaseArray,
function ($resource, FIREBASE_URL, $firebaseArray) {
  var ref = new Firebase(FIREBASE_URL + "articles");
  var posts = $firebaseArray(ref);
   return $resource('views/:articleId', { }, {
  query: {method:'GET', params:{articleId: 'articles'}, isArray:true}
 });
}]);

And the controllers:
.controller('blogCtrl', ['$scope', 'Article',
  function($scope, Article){
       $scope.articles = Article.query();
 }]);

 .controller('blogpageCtrl', ['$scope','$routeParams','Article',
function($scope, $routeParams, Article){
  $scope.article = Article.get({articleId: $routeParams.articleId}, function(article){
 });
}]);

A: https://docs.angularjs.org/tutorialHere is my solution using AngularFire for https://docs.angularjs.org/tutorial. I didn't use the 'service' since we have AngularFire providing functions.
phonecatControllers.controller('PhoneListCtrl', ['$scope','$firebaseArray',
  function($scope, $firebaseArray) {
      var ref = new Firebase("https://your-app.firebaseio.com/phones/");
    $scope.phones = $firebaseArray(ref);
    $scope.orderProp = 'age';
  }]);

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$firebaseObject',
  function($scope, $routeParams, $firebaseObject) {
      $scope.phoneId = $routeParams.phoneId;
      var ref = new Firebase("https://your-app.firebaseio.com/phones/"+$scope.phoneId);
    $scope.phone = $firebaseObject(ref);
}]);


text:
Q: designing for failure when polling/retrying/queueing is not possible I'm designing a website/web service to be hosted in the cloud (specifically AWS although that's mostly irrelevant), and I'm spending a lot of time thinking about "designing for failure". I want my system to seamlessly handle node failures, i.e. without any significant user impact or engineer intervention.
In most cases, it's easy to see how to handle sudden node failure. If my app has an API handled by 4 servers behind a load balancer, polled by AJAX or an iPhone app, the poller can simply detect the failed TCP/IP transmission and retry... assuming the load balancer behaves correctly, it will hit a healthy instance.
If the app is more processing-oriented, a queue service like SQS can be used to allow stateless nodes to pick up where the failed nodes left off.
The difficulty I see is with "points of entry", where no retry/polling is possible because the application hasn't been loaded yet, and where a failure means the app never starts. For example, the index.html on a webpage... if a node fails while transmitting that file, the user's browser will likely hang and not automatically retry (they will need to refresh).
The Load Balancer is also a single "point of entry/failure". However, in this case it appears we can solve the problem by creating multiple Load Balancers, and load balancing them using DNS Load Balancing as described here: http://blog.rightscale.com/2012/10/23/dns-load-balancing-and-using-multiple-load-balancers-in-the-cloud/
Is this a solution that would work for the simpler index.html case? Overall, how can we create redundancy where polling/retrying/queuing is not possible?
EDIT: Another idea is to have the index.html hosted statically on a CDN, S3, etc (where resource availability is more dependable), although that prevents using dynamic content. Dynamic content could be added if the page populates itself using JS, but that adds a dependency on JS as well as latency for the user.


text:
Q: Powershell color formatting with format operator I'm using a format operator inside a script with a following example:
$current = 1
$total   = 1250
$userCN  = "contoso.com/CONTOSO/Users/Adam Smith"

"{0, -35}: {1}" -f "SUCCESS: Updated user $current/$total", $userCN

This excpectedly shows the following output:
SUCCESS: Updated user 1/1250       : contoso.com/CONTOSO/Users/Adam Smith
The format operator is there to keep the targeted output text in place with current / total running numbers varying between 1-99999. Without the format operator I could highlight the success line like this:
Write-Host -BackgroundColor Black -ForegroundColor Green "SUCCESS: Updated user $current/$total: $userCN"
But the question is how could I use the highlight-colors combined with the format operator? There's only the -f parameter and it doesn't allow the color parameters because, well, it's not the same thing as Write-Host in the first place.

A: Unlike other shells, PowerShell allows you to pass commands and expressions as command arguments simply by enclosing them in parentheses, i.e by using (...), the grouping operator.
When calling PowerShell commands (cmdlets, scripts, functions), the output is passed as-is as an argument, as its original output type.
Therefore, Theo's solution from a comment is correct:
Write-Host -BackgroundColor Black -ForegroundColor Green `
           ("{0, -35}: {1}" -f "SUCCESS: Updated user $current/$total", $userCN)

That is, the -f expression inside (...) is executed and its output - a single string in this case - is passed as a positional argument to Write-Host (implicitly binds to the -Object parameter).

Note that you do not need, $(...), the subexpression operator, in this case:
(...) is sufficient to enclose an expression or command.
In fact, in certain cases $(...) can inadvertently modify your argument, because it acts like the pipeline; that is, it enumerates and rebuilds array expressions as regular PowerShell arrays (potentially losing strong typing) and unwraps single-element arrays:
# Pass a single-element array to a script block (which acts like a function).
# (...) preserves the array as-is.
PS> & { param($array) $array.GetType().Name } -array ([array] 1)
Object[]  # OK - single-element array was passed as-is

# $(...) unwraps it.
PS> & { param($array) $array.GetType().Name } -array $([array] 1)
Int32  # !! Single-element array was unwrapped.

# Strongly-typed array example:
PS> & { param($array) $array.GetType().Name } ([int[]] (1..10))
Int32[] # OK - strongly typed array was passed as-is.

# Strongly-typed array example:
PS> & { param($array) $array.GetType().Name } $([int[]] (1..10))
Object[] # !! Array was *enumerated and *rebuilt* as regular PowerShell array.

The primary use of $(...) is:

*

*expanding the output from expressions or commands  inside expandable strings (string interpolation)

*To send the output from compound statements such as foreach (...) { ... } and if (...) { ... } or multiple statements directly through the pipeline, after collecting the output up front (which (...) does as well); however, you can alternatively wrap such statements & { ... } (or . { ... } in order to execute directly in the caller's scope rather than a child scope) in order to get the usual streaming behavior (one-by-one passing of output) in the pipeline.

*

*Taking a step back: Given that you already can use compound statements as expressions in variable assignments - e.g., $evenNums = foreach ($num in 1..3) { $num * 2 } - and expressions generally are accepted as the first segment of a pipeline - e.g., 'hi' | Write-Host -Fore Yellow - it is surprising that that currently doesn't work with compound statements; this GitHub issue asks if this limitation can be lifted.

In the context of passing arguments to commands:

*

*Use $(...), the subexpression operator only if you want to pass the output from multiple commands or (one or more) compound statements as an argument and/or, if the output happens to be a single object, you want that object to be used as-is or, if it happens to be a single-element array (enumerable), you want it to be unwrapped (pass the element itself, not the array.

*

*Of course, if you're constructing a string argument, $(...) can be useful inside that string, for string interpolation - e.g., Write-Host "1 + 1 = $(1 + 1)"

*Use @(...), the array subexpression operator only if you want to pass the output from multiple commands as an argument and/or you want to ensure that the output becomes a array; that is, the output is returned as a (regular PowerShell) array, of type [object[]], even if it happens to comprise just one object. In a manner of speaking it is the inverse of $(...)'s behavior in the single-object output case: it ensures that single-object output too becomes an array.


text:
Q: color conversion from RGB to YIQ I want to convert RGB color to YIQ. AS my knowledge the formula is below:

To practice this math i went a to this link Color Conversion.
I enter here RGB values 32,65,32. I found the result is YIQ = (0.201, -0.035, -0.068);link of the Result.
My problem is that i have calculated the YIQ value by using my calculator Casio fx-991es. But my result and the result of this web page is not same.
My result is 51.371,-9.042,-17.32.
In the calculator i have first set the constant values in a 3x3 matrix named as MatA and then the RGB value in a 3x1 matrix named as MatB. Then multiply them.
Can anyone tell why my result is not same as the website result?
i have got a solution that i have to divide the result by 255 to get these value as YIQ value .But i want to know that why i have to divide by 255.
 And when i want to convert YIQ to RGB, i have to multiply the result by 255 to get as RGB value.
My problem has solved but i want to know the reason.Please anyone clarify it.


text:
Q: Line break in TeX I'm using XeTeX and I want to specify a line break. There seem to be several ways to do this for LaTeX, but I have not found any for TeX.

A: To break a line in plain TeX you could issue \break (or more user-friendly \hfil\break; if you use justified paragraphs this will not lead to "ugly line filling") at the point you want TeX to break.
However you should not break too many lines manually. Most times you want to do a paragraph break, because it is meant to separate different parts of the text.


text:
Q: magento - User share/restrict per website I have three websites configured with Share Customer Accounts = Global.
I need a new website that has to be restricted to a few users. Is there any way I can manage this via a single magento instalation? The closest I can think of is using a .htaccess with something like this:
<files "filename.cgi">
AuthUserFile /home/pathto/.htpasswd
AuthType Basic
AuthName "Secret Place"
require valid-user
</files>

But where would I put it so that it would be "activated" only when visiting that specific website? I'm hoping there's a better way. I've found a couple of extensions that should do the trick, but I'm not sure if the latest magento versions have this functionality.
The purpose of the new website/store is to simply allow for different prices for the same products, so if there's anything I'm missing, please tell me.
I'm using magento 1.6.


text:
Q: Firebase Authentication without email as username? Is it possible to use a string rather than email address as a username in Firebase?
I tried, but the createUser method requires it to be an email address. Is there anyway I can get around this restriction?

A: Given that Firebase Email+Password Authentication does not verify that the email address actually exists, you can just stuff any domain at the end of your string. As long as the result is a syntactically valid email address, it will work:
var name = 'puf'; // TODO: read this from the form where the user enters their username
var password = 'geheim';
var email = name + '@whateverdomain.com';
ref.createUser({ email: email, password: password}...

Note that the user won't have a way to receive password recovery emails with this approach.
Update there is an example of how to implement username+password sign-in in the functions-samples repo.


text:
Q: How to retrieve DynamicData DetailsView Viewstate when a SqlException occurs during Inserting? Using DyanamicData, I have a standard Many-to-Many table that is working perfectly fine when inserting a new unique row.  The dropdownlists for both Parent tables display as they should, and the row gets inserted correctly.
However, on one table, I have a Unique Index, which throws an exception that I can catch in the OnInserted event handler.  I can then post back a nice friendly message to the user, informing them of the problem.  The problem occurs because the DetailsView loses the viewstate and the values that the user had selected for the DropDownLists gets reset back to the page's defaults.
protected void DetailsDataSource_Inserted(object sender, LinqDataSourceStatusEventArgs e)
{
    if (e.Exception != null && !e.ExceptionHandled)
    {
        msgPanel.Text = "Error Occurred"; // or some other friendly message
        e.ExceptionHandled = true;

        // e.Result == null, so I can't rebuild the user's input from here.
        // What can be put where to get the user's input restored?
    }
}

A: I tend to wrap the error in a Validation exception in the model this results in a Validation Error and should leave your user input intact.
Steve


text:
Q: What are the types of statistical tests/analysis which I can do here? I am writing my Master Thesis on the concept of 4-day work week...this is about how employees instead of working 5 days a week...work only for 4 days a week...since the concept is relatively new..mine is an exploratory study...
In this study there are three parts -
Part 1 - I cover the advantages and disadvantages of the concept..
Part 1 has its own separate research question...
Part 2 - I discuss about the two real-world trials which were carried out on the concept...
Part 2 has its own separate research question...
Part 3 - Since the concept is new and not widely used..in this part I try to judge the employee's perception about the concept of four-day work week...that is how they view working as per a four day work week..
Part 3 again has a separate question which is " How do employees in Australia perceive the concept of 4 day work week ?"
There are no other hypotheses in my Project...only the above Research Questions...which are different for each of the 3 parts..
I have to answer the research question of Part 3 with an online survey whose questionnaire I have already prepared.. I have not started passing the survey around.. just in case I need to change anything in it.. that is make some questions mandatory or not...Although I am not sure how many qualified responses would be enough..but I plan to gather closely 130-140 responses(a qualified response is a response in which it is established that the person is currently an employee in Australia or has previously been an employee in Australia)..i will check this later...at this stage i need to be little bit clear about the analysis part...
The overall objective of my Thesis/study is to develop set of general guidelines for employers who are trying to implement this concept in order to help them understand whether if it makes sense to implement the concept of 4 day work week or not and if they want to implement it what are the factors that they need to consider..
For my Survey, I have established that there are 6-7 independent variables and there is only a single dependent variable.
To explain what I need to do and for sake of simplicity, I list only 2 Independent variables and the 1 Dependent variable as below -
Independent Variable 1 - Category under which the respondent's employer can be categorized into ?
Option 1 - Government
Option 2 - Private
Option 3 - Other
Independent variable 2 - Respondent's gender ?
Option 1 - Male
Option 2 - Female
Option 3 - Other
Dependent Variable - Willingness of the employee to work as per a Four day work week ?
Option 1 - Yes
Option 2 - No
Option 3 - Maybe
I will take the survey only once and after I have all the responses I will start analysis and developing my guidelines
Depending on the responses of the survey and the analysis I would like to see for eg. -
If there are people who have selected their employer type as "Government" and said that they are not willing to work as per a 4-day work week..
Then my guideline would include something like - Employers who are Government entities need to be vary of adopting a four-day work week as employees do not seem to like it..
Similarly if the respondents select "Government" as their employer type and for willingness to work as per four-day work week ..select "Yes".. then my guidelines would be Employers who are Government entities need to consider implementing a four-day work week as the study shows that the employees are in favour of it...
Similarly for Employer type "Other" and when they select willingness - Yes or No ..then a recommendation accordingly...
So ..
Government v/s. Yes,
Government v/s. No,
Government v/s. Other
Hence, whichever option stands out I can give out a recommendation accordingly...
Similar type of analysis for the Gender variable against the willingness variable...
Additionally similar analysis for all the other independent variables against the dependent variables of Willingness..
My professor has told me that I need to do statistical analysis..what exact type he did not specify..and I cannot ask him at this moment...i need to present him something and then maybe he gives me a feedback...However, in my case considering the stage I am currently in...my Research Objective and my Research Questions and the Survey Questionnaire will not change..so i think for Part 3 - doing analysis as above will be most appropriate and in line with my Research Question and the Research Objective -
Hence, in my case can anyone tell me what type of Statistical Analysis or Tests i need to do in order to check the variables as described above ?
If you require any additional information, please let me know.
Thanks,


text:
Q: Issue with download multiple file with names in BASH I'm trying to download multiple files in parallel using xargs. Things worked so well if I only download the file without given name. echo ${links[@]} | xargs -P 8 -n 1 wget. Is there any way that allow me to download with filename like wget -O [filename] [URL] but in parallel?
Below is my work. Thank you.
links=(
    "https://apod.nasa.gov/apod/image/1901/sombrero_spitzer_3000.jpg"
    "https://apod.nasa.gov/apod/image/1901/orionred_WISEantonucci_1824.jpg"
    "https://apod.nasa.gov/apod/image/1901/20190102UltimaThule-pr.png"
    "https://apod.nasa.gov/apod/image/1901/UT-blink_3d_a.gif"
    "https://apod.nasa.gov/apod/image/1901/Jan3yutu2CNSA.jpg"
)

names=(
    "file1.jpg"
    "file2.jpg"
    "file3.jpg"
    "file4.jpg"
    "file5.jpg"
)

echo ${links[@]} ${names[@]} | xargs -P 8 -n 1 wget

A: With GNU Parallel you can do:
parallel wget -O {2} {1} ::: "${links[@]}" :::+ "${names[@]}"

If a download fails, GNU Parallel can also retry commands with --retry 3.


text:
Q: Is $|x-y| > |x| - |y|$ if 1) $x < y$ 2) $xy < 0$ When you have a question like this:
Is $|x-y| > |x| - |y|$?
1)$ x < y$
2) $xy < 0$
Is there a way to solve this algebraically? Or do you just do scenario analysis with x and y being different combinations of positive and negative?
I'm trying to think if there's a more efficient way to solve these problems.
1) y < x
If $x=3$ and $y=2$ then $3-2 > 3-2 $--> no
If $x=3$ and $y=-2$ then $5>1 $--> yes
If $x= 0$ and $ y=-2$ then $2>-2$ --> yes
insufficient
2) $xy > 0$
If $x=3$ and $y=-2$, then $5>1$ --> yes
If $x=-2$ and $y=3$ then $5>-1$ --> yes
But how do you know something is sufficient? This may be a more philosophical math issue... but you've only tested 2 cases. How do you know for all cases that this is the case? Is there a more full proof way to figure this out?
Also, what are the best numbers to pick?

A: You're on the right track. If x and y have the same sign then |x-y| is the DIFFERENCE of the two so is GTE|x| - |y|. If they have opposite signs then |x-y| is the SUM of x and y, so is GT |x| -|y|.
Your original question should therefore be "is |x-y| greater than or equal to |x| - |y|?" Answer YES.

A: On the actual GMAT, you want to try to complete the problem as fast as possible since you only have a set amount of time to finish the section.  Usually the fastest way to do this for the data sufficiency section is to test numbers.
You are right that (1) is insufficient and (2) is sufficient, because with opposite signs the difference between the two will be bigger when the total absolute value is of both together then separately, so the answer is B.
In general when testing numbers, its good to try both positives and negatives, whole numbers and fractions, so that you get the full range.


text:
Q: How to fix Tkinter dead frezzing or crashing because of huge data? I am trying to make a program to display one single image (.png extension) at once but giving a button to the user to change the picture.
What I have done is:

*

*Reading the Image from my directory with help of Pillow module

*Appended it to a list

*With a button I increase or decrease the index of the list.
(Note I have to read 600 images approx.)
Here's the code:
import os
from tkinter import *
from PIL import ImageTk,Image
import threading,time
#Define the tkinter instance
x=0
win= Tk()
dir_path= os.path.dirname(os.path.realpath(__file__))
print(dir_path)
l1=[]
#Define the size of the tkinter frame
win.geometry("700x400")
def start():
    threading.Thread(target=bg).start()
    win.after(5000,threading.Thread(target=fg).start())
#Define the function to start the thread
def bg():
    print("bg")
    for i in range(1,604):
        a=Image.open(f"{dir_path}\\{i}.png")
        a=a.resize((500,700), Image.ANTIALIAS)
        b=ImageTk.PhotoImage(a)
        l1.append(b)
        print(b)
        print(len(l1))
def fg():
    def add():
        global x
        x+=1
        img2=l1[x]
        d.configure(image=img2)
        d.image = img2
        d.update()
    global d
    d=Label(win,image=l1[x])
    d.pack()
    Button(win,text="add",command=add).place(x=0,y=0)
label= Label(win)
label.pack(pady=20)
#Create button
b1= Button(win,text= "Start", command=start)

b1.pack(pady=20)

win.mainloop()

But the problem is that the Tkinter gets dead freeze and laggy to an extent that the GUI is not operable.
So my question is,
How to fix Tkinter dead Frezzes and if there is any way to read the images as fast as possible?

A: The freezes of Tkinter depends on reading speed of the interpreter, because:

*

*continuously reading and Showing the pictures are a huge job for Python.

*reading images using opencv or any other image processing module wont help as reading part can become faster, but showing the image in tkinter is done using python only, so rapid changes in Label will cause tkinter to crash.

Solution:

*

*Switch to a different compiler based language for example c++.

*this solution is specifically for a image slideshow,

The solution is to use selenium with python. You can specify the image location in  driver.get(image_path) and it will open the image for you, and if you want to change the image with a button, then just rename all your images with the numbers and make a button to add +1 to the index.


text:
Q: Using a thread to show a progress dialog in Android Here is a few bit of code:
public class ShowDialog extends Thread {
private static String mTitle="Please wait";
private static String mText="Loading...";
private Activity mActivity;
private ProgressDialog mDialog;

ShowDialog(Activity activity) {
    this(activity, mTitle, mText);
}
ShowDialog(Activity activity, String title) {
    this(activity, title, mText);
}
ShowDialog(Activity activity, String title, String text) {
    super();
    mText=text;
    mTitle=title;
    mActivity=activity;
    if (mDialog == null) {
        mDialog = new ProgressDialog(mActivity);
        mDialog.setTitle(mTitle);
        mDialog.setMessage(mText);
        mDialog.setIndeterminate(true);
        mDialog.setCancelable(true);
        mDialog.setOnCancelListener(
            new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface arg0) {
                    mDialog.dismiss();
                    interrupt();
                }
            });
    }
}

public void run() {
    mDialog.show();
    while(!isInterrupted())
    mDialog.dismiss();
    mDialog=null;
}

}
And in my main activity:
ShowDialog show = new ShowDialog(this, "Please wait!","Loading badly...");
    show.start();
    SystemClock.sleep(2000);
    show.interrupt();

I know I might use an async task and all the stuff but that is not what I want. Replace the SystemClock.sleep by anything that takes some time. The idea is to execute the code between start and interrupt in the UI thread and make a seperate thread handling the ProgressDialog.
What's wrong with my thread ?
Thanks a lot!

A: To wait for a Thread to complete, you should use the Thread.join() method.  But now I see you're not wanting to wait for it to complete, but you need to control when it completes.  Still, you want to avoid interrupting threads in this fashion.
In your ShowDialog class, add a dismiss() method that you can call from your main, instead of interrupt().  Also add a boolean dismiss = false instance variable.  In dismiss(), add dismiss = true, then notify();.  In run(), replace your constant while() loop (was running constantly, and very inefficient) with while(!dismiss){wait()}.  You will still need to add synchronization blocks and exception handling, but this should get you off to a good start.
Here is a generic-Java (non-android) simplified example:
public static class ShowDialog extends Thread{

    protected boolean dismiss;

    public void dismiss(){
        dismiss = true;
        synchronized(this){
            notifyAll();
        }
    }

    @Override
    public void run(){
        System.out.println("Running...");
        // Show your dialog here.
        while(!dismiss){
            synchronized(this){
                try{
                    wait();
                }catch(InterruptedException ie){
                    ie.printStackTrace();
                }
            }
        }
        System.out.println("Quitting...");
        // Dismiss your dialog here.
    }

}

public static void main(String[] args) throws Exception{
    ShowDialog sd = new ShowDialog();
    sd.start();
    Thread.sleep(2000);
    sd.dismiss();
}

You mentioned you didn't want to use AsyncTask, but I would still reconsider.  (What are your reasons against it?)


text:
Q: Getting a syntax error, ',' expected with TryParse I'm working on a method to try to get a date from a string.
First I had this code:
public static DateTime? TryGetDate(this string date)
{
    DateTime? outputDate;

    if(DateTime.TryParse(date, out outputDate))
    {
        return outputDate;
    }

    return null;
}

This worked fine but then I saw a suggestion on my Visual Studio telling me to change it to:
public static DateTime? TryGetDate(this string date)
{
    if(DateTime.TryParse(date, out var outputDate))
    {
        return outputDate;
    }

    return null;
}

But after that change, I got a

Syntax error, ',' expected

on the TryParse line of code.
Why did this happen? I got a suggestion with VS but applied that suggestion and I got a compilation error? The project Target Framework version is v4.6.2


text:
Q: NodeJS express serve static page, then throw 404 error I'm running an app with Node.js and Express. I created the skeleton of the project with Express Generator. Here is a section of the generated code:
app.use(express.static(path.join(__dirname, 'public')));

// Create routes
app.use('/', indexRouter);
app.use('/data', dataRouter);
app.use('/api', apiRouter);

// Catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// Error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log ('ERROR :', err.status);
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

When a static page is served, It continues and generates a 404 error. In the browser everything is fine, but in the Node.js logs, I can see the console.log('ERROR). Why the engine does not stop when a static page is served? How to solve it?


text:
Q: how can I update the newest react-native-reanimated version with expo? how can I update the newest react-native-reanimated version with expo ?
if I write this:
npx expo install react-native-reanimated

then I dont get the latest reanimated version

A: Run npm install react-native-reanimated for the latest or change package.json yourself and run npm install afterwards. Remember that expo has ben tested against fixed versions of reanimated, so you will get warnings from expo if you upgrade it yourself.


text:
Q: Is there a way to find/display only the posts tagged on a specific location (i.e. Bali) by IG user? The purpose would be to find content from the people you follow that were tagged to a location.
I cant seem to find the correct information on the developer page
except to creating photo containers (not a public api) or having to authenticate
https://developers.facebook.com/docs/instagram-api/reference/user/media#get-media


text:
Q: XPath finding root element tags I have the following xml doc
<root>
 <subject>This is the subject</subject>
 <email>
    <subject>Email's Subject</subject>
 </email>
</root>

How do I only select the 'subject' tag under the root element?  I do not want to get the subjects from the 'email' nodes.
Thanks!
EDIT:  Also, because the 'root' element is dynamic, how do I create the xpath without specifying the 'root' tag?  I've tried /subject,  //subject and //*/subject.  None have worked.

A: /*[name()=$name]/subject where $name = 'root'
/*/subject if you don't care about the document element name.


text:
Q: try! won't compile mismatched types Why doesn't this Rust code compile?
use std::fs;
use std::io;
use std::path::Path;

fn do_job(path: &Path) -> io::Result<()> {
    let mut files: Vec<&Path> = Vec::new();

    for entry in try!(fs::read_dir(path)) {
        entry = try!(entry);
    }
}

it's very similar to code in the docs.
compile error:
<std macros>:3:43: 3:46 error: mismatched types:
 expected `core::result::Result<std::fs::DirEntry, std::io::error::Error>`,
    found `std::fs::DirEntry`
(expected enum `core::result::Result`,
    found struct `std::fs::DirEntry`) [E0308]
<std macros>:3 $ crate:: result:: Result:: Ok ( val ) => val , $ crate:: result:: Result::
                                                         ^~~
src/main.rs:13:17: 13:28 note: in this expansion of try! (defined in <std macros>)
<std macros>:3:43: 3:46 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:12:5: 14:6 error: mismatched types:
 expected `core::result::Result<(), std::io::error::Error>`,
    found `()`
(expected enum `core::result::Result`,
    found ()) [E0308]
src/main.rs:12     for entry in try!(fs::read_dir(path)) {
src/main.rs:13         entry = try!(entry);
src/main.rs:14     }
src/main.rs:12:5: 14:6 help: run `rustc --explain E0308` to see a detailed explanation

A: It looks like you want a new binding for each directory entry in your loop:
for entry in fs::read_dir(path)? {
    let entry = entry?;
}

this new binding will shadow the one introduced in the for expression.
The type of entry introduced by the loop is Result<DirEntry> which you are trying to unwrap using ? (formerly try!). However you are attempting to assign the resulting DirEntry to a binding with type Result<DirEntry>, hence the error.
The second error indicates that the return value from your function does not match the declared type of io::Result<()>. You can simply return Ok(()):
fn do_job(path: &Path) -> io::Result<()> {
    let mut files: Vec<&Path> = Vec::new();

    for entry in fs::read_dir(path)? {
        let entry = entry?;
        //process entry
    }
    Ok(())
}


text:
Q: Unknown SMTP host: outlook.office365.com; I have written code in java to send mail. The issue I am facing is UnknownHostException. I am using SMTP Host as outlook.office.com as the email account from where i want to send the mail is corporate and accessed using outlook. Here is the code.
Properties props=new Properties();
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.host","outlook.office365.com");
        props.put("mail.smtp.port","587");
        Session session=Session.getInstance(props, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(sender, password);
            }
        });

The session object is not null as I have put a check on that. If session is getting created then what is the reason I am facing this exception?

A: change
props.put("mail.smtp.host","outlook.office365.com");

to
props.put("mail.smtp.host","smtp.office365.com");

or
props.put("mail.smtp.host", "m.outlook.com");

for more info, visit this and this site.


text:
Q: Laravel 5.2: Artisan Key Generation for Application Key not working properly I try to Setup Laravel 5.2 on CentOS 7. When I try to generate the Application Key using the console command php artisan key:generate the format of the Application Key is not as expected (longer than 32 characters including the base64 encode string and thus not working in the Configuration file.The cypher in config/app.php is AES-256-CBC.
Example Output:
[base64:MTs0+UZ0tHljmRcFP1RpZ06aYpc1N1L3rqAx1FT+yqk=]

The server should have all required Extensions installed.

A: This is a change made recently to the key generator. See this commit for more info.
Do you get an error stating that the key is invalid?

A: put this in appServiceProvider.php
use Illuminate\Support\Facades\Schema;
public function boot()
{
    Schema::defaultStringLength(191);
}

A: I dont know if you have resolved this issue.. This is how I solved the same.
In the config/app.php, remove the env() and its parenthesis from the key.
eg. 'key' => env('your_key')
should change it to..
'key' => 'your_key'
I hope this helps you and others out there.


text:
Q: how to replace Image in Lottie animation at runtime in iOS iOS: I am unable to dynamically change only a specific image in my JSON file. People recommend using BundleImageProvider but it's of no use because there is no way to provide the key for which I want to replace the image.
the android counterpart for the same is updateBitmap but can't find anything in iOS.

A: Try this:
before start new animation - .pause()
YourAnimation.animation = Animation.named(newAnimationJsonName)
after change animation - .play()


text:
Q:  in Nuxt 3 only show the page's content after refreshing I am trying to use <NuxtLink> to redirect in Nuxt 3.
However, my page won't show after the URL change.
That means, after clicking the link, the URL changes to whatever is stated in the to="", but the content doesn't show unless I refresh the page.
Wonder what did I do wrong.
Here is my Routing code
 <template>

        <NuxtLink to="/foundations">
Foundations
</NuxtLink>

   </template>

Here is my page code
<template>

Foundation page

</template>

A: I've got the same issue so I use native javascript instead.
// Simulate a mouse click:
window.location.href = "/";

// Simulate an HTTP redirect:
window.location.replace("/");


text:
Q: Constructivist Interpretation of a Function Lets suppose I have an exponential function $a^{x}$, and I desire to show that for any number $n$ in $(0, \infty)$, it is possible to find a value of $x_0$ such that $a^{x_0} = n$. The simplest proof would be to construct a function that does exactly that.
Real findLogarithm(Exponential f, PositiveReal n) {
    Real x_0 = new Real();
    /* ... */
    return x_0;
}

According to the lambda calculus, the type signature of this function would be
$\mathrm{findLogarithm} :: \mathrm{Exponential} \rightarrow (\mathrm{PositiveReal} \rightarrow \mathrm{Real})$
However, an equally valid type signature, in the language of first order logic, would be
$\forall x \forall y \exists ! z (P(z))$,
where P(z) is the desired invariant that results from constructing the function. If so, then can we interpret the function construction operator in the Lambda Calculus as a type of predicate in first-order logic? I am trying to find a motivation for why it is that, out of the 16 possible logical connectives, the lambda calculus gives the logical implication a privileged position.

A: In general, if $\forall x:X\forall y:Y\exists !z:Z P(x,y,z)$ then by the (higher-type) axiom of choice there exists a unique functional $\Phi\colon X\to (Y\to Z)$ such that $\forall x,y P(x,y,\Phi(x,y))$, and vice-versa. So your two formulations are just different ways of saying the same thing.
However, any restrictions you put on $\Phi$ (e.g. computable, primitive recursive) will correspond to a restriction on the $P$ (e.g. quantifier-free, provable in Peano arithmetic). In fact the precise correspondence between the two formulations is an incredibly deep question in proof theory.
As for your second point: The different logical connectives are largely interchangeable. For instance $A\rightarrow B\Leftrightarrow \neg A\lor B$, and so you could write down the axioms of propositional logic without referring explicitly to $\rightarrow$. What you choose depends on style and presentation to a certain extent. The $\lambda$-calculus is a theory of functionals, and so the underlying logic tends to be presented with an emphasis on $\rightarrow$.


text:
Q: A regular expression to match and exclude I've been scraping pages to compile a list to compare prices and dimensions. I've been using only widthxlength, excluding height. However some measurements come with height and sometimes decimals, such as:
5.0x10.0x8.0
10.0x10.0x9.0
10.0x15.0x9.0
10.0x20.0x9.0
I'm trying to exclude the .0's and the last dimension. To only end up with:
5x10
10x10
10x15
10x20
I've used \d+[ ][X][ ]\d+ and (\d+'x\d+') for similar problems, but I'm having trouble finding a way to crack this.

A: You can match the whole string, capturing the integer part of the width and length, and replace with the two capture groups. Match
(\d+)\.\d+x(\d+)\.\d+(?:x\d+\.\d+)?

and replace with
$1x$2

https://regex101.com/r/BOkRx6/3
If the decimal part may not exist, then put each decimal part in the pattern into an optional non-capturing group:
(\d+)(?:\.\d+)?x(\d+)(?:\.\d+)?(?:x\d+(?:\.\d+)?)?

https://regex101.com/r/BOkRx6/4


text:
Q: Running Mplayer in Docker on Raspberry Pi 4 I have a small dotnet client that runs videos using mplayer on Raspbian.
When logged in via SSH, I can run mplayer manually providing i set the DISPLAY variable to :0 and run mplayer as follows:
mplayer -vo gl video.mp4

This will display the video on the Raspberry Pi's screen when logged in remotely.
I am trying to create a docker image and deployment where I can do the same thing from a docker container.
The Dockerfile looks like this:
FROM mcr.microsoft.com/dotnet/sdk:6.0.202-bullseye-slim-arm64v8 AS build

WORKDIR /src

COPY ["presentationtv-client/PresentationTV.Client.csproj", "presentationtv-client/"]

RUN dotnet restore "presentationtv-client/PresentationTV.Client.csproj"

COPY . .

WORKDIR /src/presentationtv-client
RUN dotnet build "PresentationTV.Client.csproj" -c Release --no-restore

FROM build AS publish
WORKDIR /src/presentationtv-client
RUN dotnet publish "PresentationTV.Client.csproj" -c Release -o /app/publish --no-build

FROM mcr.microsoft.com/dotnet/aspnet:6.0.4-bullseye-slim-arm64v8 AS final
WORKDIR /

RUN \
    apt-get -y update && \
    apt-get -y upgrade && \
    apt-get -y install curl mplayer bash-completion

RUN mkdir -p /tvclient/runtime
RUN mkdir -p /tvclient/logs
RUN mkdir -p /tvclient/storage

ADD presentationtv-client/appsettings.json.linux /tvclient/appsettings.json
ADD presentationtv-client/appsettings.json.linux /tvclient/runtime/appsettings.json
ENV DISPLAY=:0

COPY --from=publish /app/publish/ /tvclient/runtime

#ENTRYPOINT ["dotnet", "/tvclient/runtime/PresentationTVClient.dll"]
ENTRYPOINT ["tail", "-f", "/dev/null"]

And my docker-compose :
version: "3.0"
services:
  tvclient:
    image: tvclient
    container_name: tvclient
    network_mode: "host"
    environment:
      - DISPLAY=:0
      - UID=0
      - GID=0
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - ./storage:/tvclient/storage
      - ./logs:/tvclient/logs
    devices:
      - /dev/vchiq:/dev/vchiq # MMAL/OMX on Raspberry Pi
    deploy:
      resources:
        limits:
          cpus: '1.0'
    restart: unless-stopped

When I exec into the container and run mplayer manually to test if it works I get the following error:
No protocol specified
vo: couldn't open the X11 display (:0)!
No protocol specified
No protocol specified
No protocol specified

My guess is I cannot interface with the X11 driver or there is no driver supported.
I am not really sure what I need to do to get it working. It needs to be with some form of acceleration else the full screen video is too slow (from my tests just running locally on the Pi).


text:
Q: How do I set recipients for UIActivityViewController when using message I'm using this code to present UIActivityViewController.
 var a = standard.value(forKey: "first_name") as? String
    let text = a! + " text to share"
    let url : NSURL = NSURL(fileURLWithPath: "https://itunes.apple.com/in/app/")

    let textToShare = [ text as String , url as URL ] as [Any]
    let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)

    activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
    activityViewController.completionWithItemsHandler = {
        (s, ok, items, error) in
        if ok == true {
            DispatchQueue.main.async {
               // code after completion
            }

        }
    }
    self.present(activityViewController, animated: true, completion: nil)

But I want that, if I select the message option in UIActivityViewController then the phone number should be pre filled with the number I provide. Is this possible with UIActivityViewController or not. If yes please provide me with a some reference or code about it


text:
Q: How to retrieve managament groups in hierarchy (managment groups /subscription / resources in each group) using java I'm building an application and I need to retrieve all management groups in a hierarchical style like the subscription IDs and that resource informations .
I looked up in the SDK for java :(https://github.com/Azure/azure-sdk-for-java)
but can't find anything related with my topic
I went through tones of documentations but still didn't find any significant class that can help

A: Refer to MSDOC to access the management group list from azure by using azure REST Api call for the list management api.
To access the above api we should have the following details:

*

*Client ID

*Client Secret

*Tenant ID

With the help of above credentials, we can generate access token to access the api's in azure.
Below is the API to generate the access token.
https://login.microsoftonline.com/<your-tenant-id>/oauth2/token

*

*Hit the api using postman: *

Use the generated token as header in the below api to access management groups:
https://management.azure.com/providers/Microsoft.Management/managementGroups?api-version=2020-05-01

I have implemented the above scenario using java and spring boot by following the code.
Output:
In my case, I have only one management groups. So, I'm getting one management group as shown below.


text:
Q: ActiveRecord::UnknownAttributeError on User.advertisements.create I have a rails application that user users and sessions. Users have many advertisements, and, while changing the user model to have many advertisements, I run into an Unknown Attribute Error.
Advertisements_controller.rb
class AdvertisementsController < ApplicationController
  before_action :require_user, only: [:new, :create]

  def index
    @advertisements = Advertisement.all
  end
  def new
    @advertisement = Advertisement.new
  end
  def create
    @advertisement = current_user.advertisements.create(advertisement_params)
    if @advertisement.save
      redirect_to '/advertisements/index'
    else
      redirect_to '/advertisements/new'
    end
  end

  private

    def advertisement_params
      params.require(:advertisement).permit(:title, :body)
    end
end

user_controller.rb
class UsersController < ApplicationController

  def new
     @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save then
      session[:user_id] = @user.id
      redirect_to '/'
    else
      redirect_to '/signup'
    end
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :email, :password)
    end
end

user.rb
class User < ActiveRecord::Base
  has_many :advertisements, dependent: :destroy

  # Rails's built-in password security
  has_secure_password
end

advertisement.rb
class Advertisement < ActiveRecord::Base
  belongs_to :user
end

When creating an advertisement I get an Unknown Attribute user_id on
    @advertisement = current_user.advertisements.create(advertisement_params)
this line. It should call current_user, which is on application_controller.rb
def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

EDIT: Now if I create and advertisement and then list it, I get
[#<Advertisement id: 1, created_at: "2016-02-27 00:50:55", updated_at: "2016-02-27 00:50:55", title: "my advert", body: "it belongs to me!", users_id: nil, user_id: 1>

Note the users_id: nil. I think, while it is filling the user_id it's not doing the belongs_to thing right. Where is the users_id: nil coming from? I'm only concerned because, when I delete a user, I want all their advertisements to be deleted as well (and not wasting space on ym database).

A: It sounds like your advertisements table has a column named users_id, and it should be user_id. I would write a migration to change the name of that column.
You can fix this by first generating a migration:
 rails g migration rename_advertisements_users_id

Then giving the migration these contents:
def change
  rename_column :advertisements, :users_id, :user_id
end

Then run the migration:
rake db:migrate && RAILS_ENV=test rake db:migrate

Next time you create a table with a foreign key, do something like this:
create_table :pages do |t|
  t.references :book  # not books
  t.text :text
  t.timestamps
end

Also, I would not fix the old migration. Just write the new one. Here is why: http://illuminatedcomputing.com/posts/2013/03/rules-for-rails-migrations/

A: This won't work in your advertisement create action:
@advertisement = current_user.advertisements.create(advertisement_params)

If an ad belongs to a user...user_id should be in the permitted params for advertisement. And then you should pass the current_user.id to Advertisement.new with the other params (one way to do it is via hidden_field in your form).
You shouldn't call .create from inside your create action.
Saying
if @advertisement.save

Will save object and it will be created. Hope this helps.


text:
Q: How to return response from Worker in .net core I have created a worker in .net core which calculates fibonacci series. But I need to be able to read this series as a response from this worker. And I am very new to this so after several hours of research I could not find the solution.
Here is my code:
 public class FibonacciCalculateWorker : BackgroundService
{
    private readonly ILogger<FibonacciCalculateWorker> _logger;

    public FibonacciCalculateWorker(ILogger<FibonacciCalculateWorker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        stoppingToken.ThrowIfCancellationRequested();

        await CreateFibonacciSeries();

    }
    public Task<string> CreateFibonacciSeries()
    {
        int a = 0, b = 1, c = 0;
        StringBuilder fiboSeries = new StringBuilder();
        fiboSeries.Append(a + "," + b);

        for (int i = 2; i < 50; i++)
        {
            c = a + b;

            fiboSeries.Append("," + c);
            a = b;
            b = c;
        }
        _logger.LogInformation(fiboSeries.ToString());
        return Task.FromResult(fiboSeries.ToString());
    }
}

And program.cs:
 public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<FibonacciCalculateWorker>();
            });

Any suggestion would be appreciated.


text:
Q: Using methods as (curried) functions in JavaScript What is the most elegant way to convert a method to a curried function, and is there support for this in libs like Underscore/Lo-dash or Ramda?
For a fixed number of arguments I'm doing this right now:
var fn2 = _.curry(function (m, a1, a2, obj) {
  return obj[m].call(obj, a1, a2);
});

which allows for code like:
var a2b = fn2('replace', 'a', 'b')
a2b('abc')
=> 'bbc'

as well as:
var nl2_ = fn2('replace', '
')
nl2_('\n', 'some
html')
=> 'some\nhtml'

A: You can easily extend your approach for methods with arbitrary arity:
function curryMethod(m, a) {
    if (a !== ~~a) a = m.length;
    return _.curry(function() {
        return m.apply(arguments[a], Array.prototype.slice.call(arguments, 0, -1));
    }, a+1);
}

> var replace = curryMethod(String.prototype.replace)
> replace("a", "b", "abc")
"bbc"
> var a2b = replace("a", "b")
> a2b("abc")
"bbc"

Since you also have asked about Ramda, I've only quickly scanned their API but found the R.invoker function which seems to be exactly what you're looking for.