text:
Q: Multiple cascade paths error entity framework Code first I am aware that this has been raised on numerous occasions but
none of the provided answers seem to help.I am aware of
the basic problem and have used fluent api to try to modify it's
behaviour but it appears this is being ignored(or i'm doing it wrong'.
Here's a example of the
code in question
public class Request
{
    [Key]
    public int RequestID { get; set; }
    public string RequestDescription { get; set; }
    public int RequestPriority { get; set; }
    public string RequestStub { get; set; }
    [ForeignKey("Requester")]
    public int RequesterID { get; set; }
    [ForeignKey("Admin")]
    public int AdminID { get; set; }
    public bool RequestAnsweredFlag { get; set; }
    public bool RequestSeenFlag { get; set; }

    public virtual User Requester {get;set;}
    public virtual User Admin { get; set; }

}
context class
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Request>()
                .HasRequired(a => a.Requester)
                .WithMany()
                .HasForeignKey(u => u.RequesterID);

        modelBuilder.Entity<Request>().HasRequired(a => a.Admin)
                       .WithMany()
                       .HasForeignKey(u => u.AdminID).WillCascadeOnDelete(false);

    }

any help would be much appreciated.

A: If I understand all correct you need to delete attributes  [ForeignKey("Requester")],  [ForeignKey("Admin")] and delete fluent api rules. And modify your code as follow
public class Request
{
    [Key]
    public int RequestID { get; set; }
    public string RequestDescription { get; set; }
    public int RequestPriority { get; set; }
    public string RequestStub { get; set; }
    public int RequesterID { get {return Requester.Id} }
    public int AdminID { get {return Admin.Id} }
    public bool RequestAnsweredFlag { get; set; }
    public bool RequestSeenFlag { get; set; }

    public virtual User Requester {get;set;}
    public virtual User Admin { get; set; }

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}

it should map all correctly by default


text:
Q: How can I restrict to 1 row edit? I'm using ng2-smart-table and currently having problems with its edit mode. It is supporting multiple rows editing, but I only want it to edit 1 row only, and the other rows are disabled until I exit edit mode of that row.
This is quite an obvious problem but I could not find answers anywhere. How can I achieve this function in my table?
Below is the settings for my table:
settings = {
    hideSubHeader: true,
    actions: {
      columnTitle: 'Edit/Delete',
      add: false,
      position: 'right'
    },
    edit: {
      confirmSave: true,
      confirmEdit: true,
      editButtonContent: ''
    },
    delete: {
      confirmDelete: true,
      deleteButtonContent: ''
    },
    columns: {
      index: {
        title: 'No',
        filter: false,
        editable: false,
        valuePrepareFunction(value, row, cell) { return cell.row.index + 1; }
      },
      categoryname: {
        title: 'Category name',
        filter: false
      },
      color: {
        title: 'Color',
        filter: false,
        type: 'custom',
        renderComponent: ColorLabelComponent,
        editor: {
          type: 'custom',
          component: ColorGetterComponent
        }
      },
      note: {
        title: 'Note',
        filter: false
      }
    }
};

redpajama_set_name: RedPajamaStackExchange


text: Q: How can i get selected image uri from sdcard in tab activity? I want to get image file from sdcard but problem is tab activity.I lost uri when i get back to tab activity if i select any image from sdcard.


text:
Q: How do I set the name of the print job when using DocumentViewer control? I've using the WPF DocumentViewer control to display an XPS Document like so:
viewer.Document = xpsDocument.GetFixedDocumentSequence();

When the print button inside the document viewer is clicked everything prints okay, however the name of the print job is System.Windows.Documents.FixedDocumentSequence, which is less than ideal.
How do I set the name of the print job?
I know using PrintDialog.PrintDocument() lets me set the name, but I can't see how to do it using the DocumentViewer control.

A: I found a solution.
Add this to the XAML
<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Print" PreviewExecuted="CommandBinding_PreviewExecuted" Executed="CommandBinding_Executed" />
</Window.CommandBindings>

And this to the code behind
private void CommandBinding_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
    PrintDialog dialog = new PrintDialog();
    if (dialog.ShowDialog() == true)
    {
        dialog.PrintDocument(Document.DocumentPaginator, "Print Job Title");
    }
}

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    //needed so that preview executed works
}

A couple of things of note. The PreviewExecuted method doesn't happen if the Exectued event isn't bound to. Don't know why.

A: I had the same issue however overriding the Print command wouldn't work in my situation so i found another work around that works equally well
internal class MyDocumentViewer : DocumentViewer
{
    public string JobTitle { get; set; }

    protected override void OnPrintCommand()
    {
        PrintDialog dialog = new PrintDialog();
        if (dialog.ShowDialog() == true)
            dialog.PrintDocument(Document.DocumentPaginator, JobTitle);
    }
}


text:
Q: Bar chart not functioning the way I would want it I was hoping if you can help me with this coding. I'm attempting to create a bar chart but it doesn't seem to be going my. I m trying to make the output below but when I run it I get [Red, Yellow, Blue](0) repeating. I feel like I'm close to solving this. If someone can push me in the right direction in what I can do it would be appreciated greatly.
import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //These arrays are not to be modified and should only use these 2 arrays.
        short[] points ={1,2,1,1,1,1,1,1,3,4,1,5};
        String[] teams ={"Red","Yellow","Blue","Blue","Blue","Red","Yellow","Red","Yellow","Red","Blue","Blue"};
        Set<String> uniqueTeams = new HashSet<String>(Arrays.asList(teams));
        Barchart(points, teams, uniqueTeams);
    }

    public static void Barchart(short[] points, String[] teams, Set<String> uniqueTeams){
        byte count=0;
        for(int index=0; index < points.length; index++){
            if(teams.equals(uniqueTeams)){
                count++;
            }
        }
        for(int index=0; index < points.length; index++){
            System.out.println(uniqueTeams + "("+ count + ")");
        }

    }
}

//Output should look like this:
//
//Red(7): *******
//
//Yellow(6): ******
//
//Blue(9): *********

I have a idea of how to do it another way but I don't know how. If someone can answer this question below.
How would I be able to get or create a new array without having doubles of what I do in the teams array? So the array would look like String[] uniqueTeams = {"Red, "Yellow", "Blue"}; but not initialize or declare it but create a way to make the program create itself if that makes sense.

A: You're printing out uniqueTeams directly. uniqueTeams is of type Set. What you should be doing is cycling through each of the items inside the set, and printing out the stars next to them.
 The OOP Approach
If it were me, I would not have everything in separate data structures, it makes for very messy code. Why not create a Bar object, that will contain the value and the name. Then you simply need to cycle through a collection of type Bar and call the toString() method`, which you will override.
 While I'm here
I figure I might as well give you a step by step with the OOP approach. With Object Oriented Programming, we want to contain similar data in objects. For example, the name and value of a bar is a great object to make; all the data relates to the class.
class Bar
{
private int count;
private String name;
    // Some values here to store the count and the name of the bar.

public Bar(String name, int count)
{
            // Assign those values in the constructor.
    this.name = name;
    this.count = count;
}
// Override the Object toString() method, and replace it with our code:
public String toString()
{
    String stars = "";
    for(int x = 0; x < count; x++)
    {
        stars += "*";
    }
            // Create the stars string, and append it to the name and count.
    return name + ":" + count + " | " + stars;
}
}

Now to access this code is much, much simpler than your solution. First, we create an ArrayList, something like barChart to store all the values, and we parameterize it to type Bar:
  ArrayList<Bar> barChart = new ArrayList<Bar>();

Then we can add some test cases in:
  barChart.add(new Bar("Red", 10));
  barChart.add(new Bar("Blue", 20));
  barChart.add(new Bar("Green", 12));

Now, because you have overridden the toString method, you can now simply pass the objects to a System.out.println() function. Something like:
  for(Bar b : barChart) {
     System.out.println(b);
  }

Output
Red:10 | *********
  Blue:20 | ********************
  Green:12 | ************


text:
Q: Execute lambda in the context of another object It seems like proc can be executed in another object but lambda cannot.
[1] pry(main)> class A; def a; 5; end; end
[2] pry(main)> pr = proc { a + 1 } # => #<Proc:0x007f5024264668@(pry):2>
[3] pry(main)> la = -> { a + 1 }   # => #<Proc:0x007f5023fc0e48@(pry):3 (lambda)>
[4] pry(main)> A.new.instance_eval &pr
=> 6
[5] pry(main)> A.new.instance_eval &la
ArgumentError: wrong number of arguments (1 for 0)
from (pry):3:in `block in __pry__'
[6] pry(main)>

Is there any other way for lambda to be executed like proc in this example, or should I always use procs instead in the situations like that?

A: The issue here is that the receiver of instance_eval is passed to the block as an argument. Procs allow for undeclared arguments, lambdas do not.
pr = proc {|*args| p args; a + 1 }
A.new.instance_eval &pr
[#<A:0x43668596>]
 => 6

If you declare your lambda such that it receives an argument, it works just fine:
> la = ->(recv) { a + 1 }
> A.new.instance_eval &la
 => 6

You could just (and probably want to) use instance_exec instead though:
> la = -> { a + 1 }
> A.new.instance_exec &la
  => 6
> la = ->(add) { a + 1 + add }
> A.new.instance_exec 10, &la
  => 16


text:
Q: Fonts used in scrrprt TOC in a scrrprt document I'm using proportional old style numbers throughout, but I want to use monospace lining numbers for the pages in the TOC.
I can use the chapterentrypagenumber font for the top level, but sectionentrypagenumber is only available for article (because it's the top level there).
Which font is in use for the rest of the numbers?
Here's a simple test document — how do I change font for the black numbers?
\documentclass{scrreprt}
\usepackage{xcolor}
\setkomafont{chapterentrypagenumber}{\color{red}}
\setkomafont{disposition}{\color{teal}}
\begin{document}
{\color{blue}\tableofcontents}
\chapter{Chapter}
\section{Section}
\subsection{Subsection}
\end{document}

Also is there a simple debugging switch one could use for these things, to just put the name of the komafont in use into the document?
I tried
\renewcommand{\usekomafont}[2]{(#1:#2)}

But there are clearly some font changes happening that I'm not catching:

A: Use the tocstyle package from the KOMA bundle and the pagenumberhook:
\documentclass{scrreprt}
\usepackage{xcolor, tocstyle}
\setkomafont{chapterentrypagenumber}{\color{red}}
\setkomafont{disposition}{\color{teal}}
\settocstylefeature{pagenumberhook}{\sffamily{}}
\begin{document}
{\color{blue}\tableofcontents}
\chapter{Chapter}
\section{Section}
\subsection{Subsection}
\end{document}

I used \sffamily as font command, but maybe you'd like to have something else.

EDIT
It is a rainy day, I longed for something coloured and so I played around with this, just to find out which level of nonsense KOMAscript sustains:
\documentclass[x11names]{scrreprt}
\usepackage{xcolor, blindtext}
\usepackage{tocstyle}
\usetocstyle{KOMAlike}

\addtokomafont{chapterentrypagenumber}{\color{purple}}
\addtokomafont{chapter}{\color{purple}}

\addtokomafont{chapterentry}{\Large\color{purple}}
%\addtokomafont{disposition}{\color{Snow4}}
\settocstylefeature{entryhook}{\color{Wheat4!70!black}\bfseries}
 \settocstylefeature{pagenumberhook}{\rlap{\color{Wheat1}\hspace{-0.3em}\rule[-0.6ex]{0.6em}{2.5ex}\color{Wheat3}\rule[0.1ex]{0.6em}{2.5ex}}\bfseries\sffamily\color{teal}}

\begin{document}
 \tableofcontents
% \chapter{Chapter}
% \section{Section}
% \subsection{Subsection}

\blinddocument

\blinddocument

\end{document}

And you get such a cute TOC:


text:
Q: Rails User - Role relationship with predefined roles? is there any way when creating migrations to predefine the values an attribute can have?
class User < ActiveRecord::Base
    belongs_to :role
end

class Role < ActiveRecord::Base
    has_many :users
end

and my migrations:
class CreateRoles < ActiveRecord::Migration
  def change
    create_table :roles do |t|
      t.string :name # (regular, admin, etc) => how can we define these as a list?
      t.timestamps
    end
  end
end

class AddRoleToUser < ActiveRecord::Migration
  def change
    add_column :users, :role_id, :integer
  end
end

A: One approach is to use a validation like in this question and its two good answers. This validates that the value in a given column is one of a defined list of values. You could either add that validation to your User model and ditch the Role model entirely, or add it to the name field of Role. This is probably the simplest, most Rails-ish way to do it. You could define a constant on your application which contained the approved list of roles, then use whatever works best for you to maintain that list.
Another approach is to make your Role model an ActiveHash model rather than ActiveRecord. ActiveHash lets you set up models which act like ActiveRecord models, but rather than being stored in the database, they're read-only models defined by a hash in the model file. (I'm grossly oversimplifying how ActiveHash works, I expect, but it's a start.) Again, you could use an application constant to maintain the hash.
The advantage to retaining Role as a model is that it allows for Users to have multiple Roles if you ever decided to go that route.


text:
Q: Cs50 Caesar Check50 fail I am doing Caesar exercise from CS50 course, but it fail.
Here is the code:
# include <stdio.h>
# include <cs50.h>
# include <string.h>
# include <stdlib.h>
# include <ctype.h>

int main(int argc, string argv[])
{
    if (argc == 2)
    {
        string key = argv[1];
        int l = strlen(key);
        for (int i = 0; i < l; i++)
        {
            // if key[i] is an alphabet character
            if (isalpha(key[i]) != 0)
            {
                printf("Usage: ./caesar key\n");
                return 1;
            }
        }

        //change charater to number
        int k = atoi(argv[1]);

        //print Plaintext
        string plaintext  = get_string("Plaintext: ");

        int n = strlen(plaintext);

        char ciphertext[n];

        //declare plaintext in ASCII
        int nplaintext[n];

        //Change plaintext to ASCII
        for (int i = 0; i < n; i++)
        {
            nplaintext[i] = (int)plaintext[i];
        }

        //Declare ASCII for ciphertext which we name "plusplaintext"
        int plusnplaintext[n];

        for (int i = 0; i < n; i++)
        {
            //if Capital
            if ((nplaintext[i] < 91) && (nplaintext[i] > 64))
            {
                plusnplaintext[i] = 65 + ((nplaintext[i] + k) - 65) % 26 ;
            }

            //if Lowercase
            else if ((nplaintext[i] < 123) && (nplaintext[i] > 96))
            {
                plusnplaintext[i] = 97 + ((nplaintext[i] + k) - 97) % 26 ;
            }

            //if not character a -> z and A -> Z
            else
            {
                plusnplaintext[i] = nplaintext[i];
            }
        }

        for (int i = 0; i < n; i++)
        {
            ciphertext[i] = (char)plusnplaintext[i];
        }

        printf("ciphertext: %s\n", ciphertext);

    }

    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}

Here is the output from Check50:
:) caesar.c exists.

:) caesar.c compiles.

**:( encrypts "a" as "b" using 1 as key, output not valid ASCII text**

:) encrypts "barfoo" as "yxocll" using 23 as key

:) encrypts "BARFOO" as "EDUIRR" using 3 as key

:) encrypts "BaRFoo" as "FeVJss" using 4 as key

:) encrypts "barfoo" as "onesbb" using 65 as key

**:( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key, output not valid ASCII text**

:) handles lack of argv[1]

When I test the code, sometimes it gives right result, sometimes it give the wrong result with some more characters at the end...
How can I correct my code?

A: The problem is with the logic here
  //if Capital
  plusnplaintext[i] = 65 + ((nplaintext[i] + k) - 65) % 26 ;

  and

  //if Lowercase
  plusnplaintext[i] = 97 + ((nplaintext[i] + k) - 97) % 26 ;

use this logic instead
  //if Capital
  ((((nplaintext[i] - 90) + 25) + key) % 26) + 65

  //if Lowercase
  ((((nplaintext[i] - 122) + 25) + key) % 26) + 97

and it is also not necessary to assign the letters to a string, instead you can directly print it
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
// Error Checking on the command line argument
if (argc != 2)
{
    printf("Usage: ./caesar key\n");
    return 1;
}
else if (argc == 2)
{
    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if (isdigit(argv[1][i]) == 0)
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }
}

int key = atoi(argv[1]);

string plain_text = get_string("plaintext: ");

printf("ciphertext: ");
for (int i = 0; i < strlen(plain_text); i++)
{
    if (isalpha(plain_text[i]) != 0)
    {
        // printf("%c", plain_text[i] + key);
        if (isupper(plain_text[i]))
        {
            printf("%c", ((((plain_text[i] - 90) + 25) + key) % 26) + 65);
        }
        else
        {
            printf("%c", ((((plain_text[i] - 122) + 25) + key) % 26) + 97);
        }
    }
    else
    {
        printf("%c", plain_text[i]);
    }
}
printf("\n");
}

A: Instead of using the ascii value of a letter in your code, it could be helpful to keep them as characters for the sake of clarity. I took a snippet of your code and changed the values to demonstrate.
 //if Capital
        if ((nplaintext[i] <= 'Z') && (nplaintext[i] >= 'A'))
        {
            plusnplaintext[i] = 'A' + ((nplaintext[i] + k) - 'A') % 26 ;
        }

This makes it clear what those values represent, and you don't have to reference an ascii chart.  More comments would also help a user, or yourself later on, understand what the purpose is for each part of your code.
You could also create some functions outside of your main function.  For example, to check for all digits in command line input, or change the letters by the amount given in the key.  If you start working on long programs of code, it could be helpful to have functions defined that you can use as many times as you need.  It also cleans up your main for clarity.
This function below takes the character of each letter in the original text (char p), then "moves" the character by k spaces (int k, given by the user as the key in the command line).  It works when called in a for loop in main that iterates over each letter in the original given string (text[i]), with i being increased for each time the loop executes.
char rotate(char p, int k)
{
    // declare variable for the rotated letter to be stored
    char c;

    // check if it is a letter
    if (isalpha(p))
    {
        // check for lowercase letter
        if (islower(p))
        {
            // subtract ascii value from p to initialize to 0 - 25 for computations
            p -= 'a';  // if p is a, it is now initialized to 0, if b to 1, if c to 3, etc
            c = (p + k) % 26; // use Caesar's algorithm to rotate letters, 'wrapping' by using % 26
            c += 'a'; // add ascii value back to result to get the rotated letter
        }

        // the only other option is uppercase since we checked for only letters, do the same for uppercase letters as for lowercase
        else
        {
            p -= 'A';
            c = (p + k) % 26;
            c += 'A';
        }
    }

    // if it is the nul character '\0' return 0, do not print
    else if (p == '\0')
    {
        return 0;
    }

    // if not a letter or nul character, return the character as is
    else
    {
        c = p;
    }

    // print the rotated letter which is now stored in c
    printf("%c", c);

    // return the value of c
    return c;
}


text:
Q: imagemagick crop error option requires an argument -crop i want to bulk crop image so i thought i use imagemagick but when i run this command on the command line:
convert src.jpg -gravity center -crop '290×310+50+50' src_c.jpg

this's error message:
convert: option requires an argument `-crop' @ error/convert.c/ConvertImageCommand/1087.

what's the problem here.
im on ubuntu 11.04 and i'm using imagemagick 6.6.2
any help.
Thanks in advance.

A: From my experiments your x in 290×310+50+50 isn't actually an x (The letter X, rather than a multiplication symbol). Change it to an x (as in the letter) and it works for me


text:
Q: Not able to git pull in android studio 3.6 I am getting error as mentioned below:

Update failed
                    Invocation failed Unexpected Response from Server:  Unauthorized
                    java.lang.RuntimeException: Invocation failed Unexpected Response from Server:  Unauthorized
                    at org.jetbrains.git4idea.nativessh.GitNativeSshAskPassXmlRpcClient.handleInput(GitNativeSshAskPassXmlRpcClient.java:34)
                    at org.jetbrains.git4idea.nativessh.GitNativeSshAskPassApp.main(GitNativeSshAskPassApp.java:30)
                    Caused by: java.io.IOException: Unexpected Response from Server:  Unauthorized
                    at org.apache.xmlrpc.LiteXmlRpcTransport.sendRequest(LiteXmlRpcTransport.java:231)
                    at org.apache.xmlrpc.LiteXmlRpcTransport.sendXmlRpc(LiteXmlRpcTransport.java:90)
                    at org.apache.xmlrpc.XmlRpcClientWorker.execute(XmlRpcClientWorker.java:72)
                    at org.apache.xmlrpc.XmlRpcClient.execute(XmlRpcClient.java:194)
                    at org.apache.xmlrpc.XmlRpcClient.execute(XmlRpcClient.java:185)
                    at org.apache.xmlrpc.XmlRpcClient.execute(XmlRpcClient.java:178)
                    at org.jetbrains.git4idea.nativessh.GitNativeSshAskPassXmlRpcClient.handleInput(GitNat

In previous versions, I managed to fix it like this:
AndroidStudio -> Preferences -> Git -> SSH Executable and changed from Native to Built-in and it started working. See UI here: https://i.stack.imgur.com/KCvHA.png
But in android studio 3.6, I don't see above option in settings.

I have also tested the git using Test button at top right. Git is executing successfully.

A: This issue is resolved in Android Studio 3.6.1. I verified it by updating from 3.6 to 3.6.1 and git is working as expected
You can find release notes here. It says

Git version control authentication issue resolved
In the initial release of Android Studio 3.6, operations requiring
  authentication in Git version control were broken in the IDE. This bug
  has been fixed in 3.6.1. See Issue #124680708 for more information.

A: Go to -
Android Studio -> Setting-> GitHub

If you can't login using username and password try to get a Token from GitHub from here -
https://github.com/settings/tokens/new
and then generate new token if you don't have one. And finally login with Token


text:
Q: Импорт данных и производительность Появилась такая задачка: импорт в БД данных из CSV-файла. CSV представляет собой ненормализованную табличку, он прилетает из другого приложения и на его формат я повлиять никак не могу. БД нормальзована, поэтому вариант с LOAD DATA INFILE, наверное, не подойдет.
Условно, БД выглядит так:
CREATE TABLE `clients` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(30) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE `index_clients_names` (`name`)
) ENGINE = InnoDB;

CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`price` INT NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE `index_products_names` (`name`)
) ENGINE = InnoDB;

CREATE TABLE `orders` (
`id` INT NOT NULL AUTO_INCREMENT,
`client` INT NOT NULL,
`product` INT NOT NULL,
`date_time` DATETIME NOT NULL,
PRIMARY KEY (`id`),
UNIQUE `index_order_datetime` (`date_time`)
) ENGINE = InnoDB;

CSV-файл:
John Ridger;Paper;30;2018/10/7 5:23:54 AM
Василий Кормушкин;Notebook;8;2018/10/7 8:44:28 AM
Alice McCollin;Glue;5;2018/10/7 11:9:14 AM
...

Сначала мне нужно добавить недостающие поля (если таковых ранее не было в БД) в таблички clients и products, потом уже вносить данные в orders.
Соответственно, возник вопрос - как это сделать оптимально (и с т.з. производительности/нагрузки на СУБД, и с т.з. удобства кода (используется РНР7)).
В голову приходят такие варианты:

*

*На РНР распарсить CSV в массив, затем пройтись по нему построчно с кучей  INSERT'ов (вида INSERT IGNORE INTO) с клиентами и продуктами (либо с несколькими многострочными INSERT'ами). Затем еще раз пройти по массиву, SELECT'ами получить id клиентов/товаров и делать INSERT в orders.
(Мне кажется, вариант дурацкий).

*Сделать в MySQL хранимую процедуру, принимающую имя клиента, названием товара, кол-во и дату, которая будет проверять наличие нужных значений в clients/products (и получать их id), при необходимости добавлять их туда, и в конце заносить данные в orders.
(Вроде бы вариант получше, не знаю только, нет ли в MySQL каких-то ограничений, которые могут не дать это сделать. Минус в том, что вызов процедуры придется делать для каждой строчки в CSV).

*Сделать VIEW из этих 3х табличек через INNER JOIN, повесить на него триггер BEFORE INSERT и в нем выполнить необходимую подготовку данных - получение id, добавление недостающих данных в clients/products. Соответственно, из РНР просто делать INSERT в этот VIEW. Может быть даже LOAD DATA INFILE.
(Если я правильно понял документацию по MySQL, то это невозможно из-за ограничений триггеров на кол-во изменяемых таблиц.)

*Сделать хранимую процедуру, которая будет создавать временную табличку, читать в нее CSV через LOAD DATA INFILE и затем уже производить манипуляции с этой таблицей, в конце смержить ее с orders.
(Вообще не уверен, что MySQL позволит такое. Если все же такое возможно, то не знаю, как скажется на производительности/потреблении ресурсов создание/удаление временной таблицы при каждом импорте данных)

Больше ничего в голову не приходит, посему хотелось бы узнать мнение более опытных в этом деле людей.


text:
Q: Moving MySQL from localhost to remote server I've just finished writing a website which is working very well on my local server (xampp).
The following is my connection database definitions for the local server:
<?php
  $host="localhost";
  $username="root";
  $password="1234";
  $db_name="partnership";

  mysql_connect("$host", "$username", "$password")or die("cannot connect");
  mysql_select_db("$db_name")or die("cannot select DB");
?>

I've loaded my files successfully and put them on the remote server (www.mydomain.com) and I've created the relevant database 'partnership' (successfully imported all Tables from phpMySQL local server to the remote server).
I can view the website  (www.mydomain.com) but with no connection to the database (MySQL).
The error message is of course "cannot connect".
I've changed $host="localhost" to $host="www.mydomain.com" but still getting the same error message.
Any assistance on the above issue would be greatly appreciated.

A: Shouldn't you still use localhost as $host if you're trying to connect via the application? The script is on the same server as the DB.

A: Ah, this is always the most annoying part of the process.  Try this and see if it works:
$host="127.0.0.1";  // "localhost" should work, but don't count on it
$username="user"; // username you use to log into phpMyAdmin
$password="password"; // password you use to log into phpMyAdmin
$db_name="dbname"; // database you want to connect to

You'll need to have created this user/password pair and given them the appropriate permissions to access the database.  Also note that the mysql PHP functions are deprecated and should not be used.  PDO or mysqli are the preferred ones going forward.

A: If you are using cPanel, when you create the MySQL table, make sure you assign your user to it (trivial, I know, but Ive forgotten about it a few times myself.)
If your script is running from your remote server, just stick with localhost. Will work fine.
Last, my only suggestion until a better answer is said, try using
$host = 'localhost';
$user = 'username'; // Im pretty sure your username isn't root.
$pass = '1234';
$db = 'partnership';
/* Alot of hosts like to append your cPanel login to your db and username fields.
Check to see what your table is. It might actually be 'youruser_partnership'  */

$mysqli = new mysqli($host, $user , $pass, $db);
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}

If your host supports mysqli (most do). If not, when you do your die statement, still use die(mysql_error()); to get the exact error. It will more than likely be your username/password you created and assigned to your database


text:
Q: Why doesn't src inside  element load? <picture>
  <source type="image/webp" srcset="images/me.webp">

</picture>

When I use the picture element, the browser(chrome) doesn't load the image with the other resources. However, when I replace <picture> with only  element it works fine:

Why is that happening?

A: Your code will load the me.webp image if the browser supports its. If not, the jpg image will be shown (which works). Chrome 67 supports webp format, so the only issue I can figure out is that me.webp is not in the images folder.

A: AFAIK, <picture> is used when you want multiple possible images to use in a responsive design. The  at the end is the fallback. It sounds like images/me.webp isn;'t working.
Unless you are really making use of <picture>, use .


text:
Q: Class inclusion error in visual studio I am currently working in visual studio developing a text based game. I had a namespace conflict with a class.
I had a class name which was Clothing and namespace which also named Clothing. To get around this issue I renamed the namespace clothes instead of clothing and then all the drama started. My csproj file did not update the namespace references in the folders whenever i try to build i get the following error.
[Failure] Could not find file '...\src\Items\Equipment\Apparel\Clothing\Shirts\Shirt.cs'.
[Failure] Could not find file '...\src\Items\Equipment\Apparel\Clothing\ClothingEnum.cs'.
[Failure] Could not find file '...\src\Items\Equipment\Apparel\Clothing\Cloaks\Cloak.cs'.
[Failure] Could not find file '...\src\Items\Equipment\Apparel\Clothing\Boots\JackBoot.cs'.
...

If i look in these directories the files exist but are empty. The actual files are in ...\src\Items\Equipment\Apparel\ Clothes\Boots... and they are included in the csproj file. But these files are also there.
In essence what I'm asking is how do I remove these unused references/dependencies/whatever they are from the csproj file.
Manually deleting the xml references in csproj file just causes my project to fail loading.

A: I don't get why you renamed your folders after you renamed the namespaces - that is unnecessary, in my opinion.
You can remove the cs files from the solution explorer with "Exclude from project"and then add the new ones with "Add -> Existing item"


text:
Q: How many cells are in a skew diagonal of a square matrix Question:Let $M_{n}$ be a square $n \times n$ matrix. I write $S_k$ for the $k-$th skew diagonals of $M_{n}.$ If I include the top left and bottom right corners of $M_n$, namely cells $a_{11}$ and $a_{nn}$ then it is easy to verify there are $2n-1$ such skew diagonals. And so I label them
$$
S_{1}, S_{2},\ldots,S_{n-1}S_{n},S_{n+1},\ldots,S_{2n-1}
$$
I write $\text{cells}\left(S_{k}\right)$ to count the number of matrix cells along the $k-$th skew diagonal; where $1 \leq k \leq 2n-1.$ What is the formula for $\text{cells}\left(S_{k}\right)$ ?

Here is an example. In a $5 \times 5$ matrix we have $\text{cells}\left(S_{7}\right)=3.$ Surely $\text{cells}\left(S_{k}\right)=n$ whenever $k\leq n.$

A: For $1\leq i \leq 2n-1$ we have $$S_i=n-|n-i|$$ Or in others words $S_i=i$ when $1\leq i\leq n$ and $S_i=2n-i$ when $n\leq i \leq 2n-1$.


text:
Q: Screen.Fill() in Pygame isn't changing the screen I've looked through a number of code examples, but I can't determine why the window screen is not changing to blue.
import sys, pygame

pygame.init()

clock = pygame.time.Clock()

size = (1000, 440)
black = (0,0,0)
blue = (0,0,255)
white = (255,255,255)

screen = pygame.display.set_mode(size)
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(blue)
    pygame.display.update()

I expect the screen to change colors, but it's just stay at a default grey.


text:
Q: HCE payment application workflow I am doing a PoC on HCE based payment.I have gone through Android documentation and some other blogs and it seems its pretty complex to implement.
There is a sample app describing the HCE service for core communication but I beleive a real payment app has much more. e.g. I see following modules
1) user enrollment/registraion - user will get a PIN after successful registration. This PIN will be required while making payment
2) card registration - once registered cards will be stored on cloud.
3) HCE module to communicate with NFC reader at POS (point of sale)
4) token generation to perform transactions - It is one of mechanisms to prevent/minimise fraud as a token may have a lifetime, amount or no. of transactions limitation. I have not understood it fully as how the token will be generated and who all are involved in the process.
please help me to clarify this workflow.
Thanks,
iuq

A: Below is the flow I was looking for, found it here
1. Registration:
The end-user registers with their Issuing Bank for the mobile payments service, electing a card to mobilize for proximity payments, and installs the handset application
2. Card Preparation:
The Issuing Bank shares details of the elected payment card with the Remote Secure Element in readiness for tokenization
3. Handset Preparation:
The end-user activates and initializes their handset and mobile application with the Remote Secure Element
4. Payment Token Provisioning:
The Remote Secure Element provisions payment tokens to the handset mobile application ready for use in proximity payments
5. Proximity Payments:
The end-user activates a payment token within the handset mobile application and presents their handset to a POS terminal to make a payments


text:
Q: AngularJS dynamically load template and js file I want to dynamically add menu JavaScript file and html to content.html, but it can't do.
I created simple example
demo
I try move  "" to menu.html

A: Your code moves away from the whole idea of writing single page app with angular. I have updated it to give you basic idea of how you would do the routes and share templates and use controller.
Check out the plunkr
html

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="menu.css" />

js
angular.element(document).ready(function() {
    angular.bootstrap(document, ["app"]);
});

angular.module('app',['moduleContent', 'moduleMenu', 'ui.router']);

var app = angular.module('app');

app.config(function($stateProvider) {
  $stateProvider
    .state('index', {
      url: "",
      templateUrl: "first.html",
      controller: 'firstCtrl'
    })
    .state('second', {
      url: "/second",
      templateUrl: "second.html"
    })
});

app.controller('firstCtrl', ['$scope', function($scope) {
  $scope.page = "first";
}]);

//Conttent module
angular.module('moduleContent',[])
.controller('contentCtrl', contentCtrl);

function contentCtrl(shareData)
{
    shareData.currentPage = 0;
}


text:
Q: Multicast in java script I am trying to implement hybrid app using ionic and angularJS which will connect to multicast server to fetch HTML pages to connect to server. I am planning to use websockets for reliable connection.
server will send multicast packets in JSON format continuously. The client needs to join multicast group and read packet to figure out server ip address and port number from packet.
I have a couple of questions:

*

*what will be the most reliable way to create multicast socket in the client to listen for server announcement message?

*Is there any way to achieve this in hybrid approach?

I am able to receive multicast packets on nexus 9 using Java API, but i see most of the android devices don't, or don't fully, support multicast.
On IOS I don't have an issue.
As I am creating hybrid app, I am looking is there any better solution.

A: Try to utilize groups in SignalR in your server http://www.asp.net/signalr/overview/guide-to-the-api/working-with-groups
This can catalyze your client side development https://github.com/JustMaier/angular-signalr-hub


text:
Q: "Divide the divided"? Is there a political hypothesis that has the same meaning as "dividing the divided"?
I've seen it in Arabic but didn't find the English equivalent. It's used in the context of countries. It is like "divide and rule" concept.

A: The term I would use is "subdivided." In political history, an example is dividing the former India into India and Pakistan, then subdividing Pakistan into Pakistan and Bangladesh.


text:
Q: Google Maps (Reverse) Geocoding API should display only Cityname Im using the Google Maps GeolocationAPI to retrieve the Cityname of given Coordinates ( this is called reverse geolocation). Documentation is available here
i send a post request with jquery and get a JSON formatted object at my script its this array: locationName[].
for some coordinates i have success displaying the city name using:
locationName[0].address_components[0].long_name;

but for some coordinates the city name is at
locationName[0].address_components[1].long_name;

or even at
locationName[0].address_components[3].long_name;

additionally i want to display the City district (if its available for the given coordinates if not then i only want to display the cityname)
how can i determine which field in the array is the city name and how to determine if a city district is available and if so in which field it is ?

A: This question is basically about checking objects for a particular value in an array attribute and returning that object if the value is found in the array.  Here's one way you can do it -
var desiredLocationDescription;
var addressComponentArray = [];
var typeName = "locality";

for (var i = 0; i < locationName[0].address_components.length; i++){
    addressComponentArray.push(locationName[0].address_components[i])
}

for (var i = 0; i < addressComponentArray.length; i++){
    if (addressComponentArray[i].types.includes(typeName)){
        desiredLocationDescription = addressComponentArray[i];
        break;
    }
}

console.log(desiredLocationDescription.long_name)

Since the city name is stored in the object with the type: ["locality", "political"], look through the array of objects until you find the one with 'locality' in its types.


text:
Q: JPA OneToOne join issue Here is my SimpleCost Entity
@Entity
@Table(name="Simplecost")
public class SimpleCost {
@Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 private Long userId;
 private Long cost;
 @OneToOne(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
 @JoinColumn(name = "userId")
 private UserBare user;
}

UserBare:
@Entity
@Table(name="user")
public class UserBare{
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 private Long userId;
 private String fName;
 private String lName;
}

So I'm having an trouble populating SimpleCost.user attribute. I need to use SimpleCost.userId to retreive the user table data and fill the SimpleCost.user object. Here is my database structure.
Database Tables:
User
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`fName` varchar(100) DEFAULT NULL,
`lName` varchar(100) DEFAULT NULL,
`mName` varchar(100) DEFAULT NULL,
`title` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_UNIQUE` (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
 /*!40101 SET character_set_client = @saved_cs_client */;

simplecost
CREATE TABLE `simplecost` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`userId` bigint(20) DEFAULT NULL,
`liableCost` decimal(10,2) DEFAULT NULL,
`isActive` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `fk_simplecost_user1_idx` (`userId`),
CONSTRAINT `fk_simplecost_user` FOREIGN KEY (`userId`) REFERENCES `user`      (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

A: You don't need the 'userId' columns defined in your Entity (java class). The one in UserBare is obviously useless and the one in SimpleCost will be created/used because of the @JoinColumn(name = "userId") you added to the 'user' field'
Remove private Long userId; from both Entity declaration.
Other than that, you will need to define what is "having an trouble populating SimpleCost.user attribute".


text:
Q: Python lookup computer name on a domain by its IP address I`m trying to get the name of a server in our lab domain.
When trying to execute the below - it says socket.herror: [Errno 11004] host not found :
socket.gethostbyaddr("10.101.31.211")
Any ideas?


text:
Q: IOS Screen Time to get duration for app used I've been working on Flutter for quite sometime and I've no relevant experience when it comes to native side or iOS. I wanted the suggestion that is it possible for me to use screen time IOS feature in custom app where I can see how much time one has spent on app in his device, like for Android we've a package called app_usage.
Help appreciated.


text:
Q: How can I create a canvas in Swift that I can move and place some components on? I want to create an app for my iPad to design some simple electronic schematics using SwiftUI. But I don't know the best way to create the canvas - the workspace - for my app. I would like to move it vertically and horizontally. And I would also like to zoom, like in a map app.
I have no idea which framework I should use.
I thought of SpriteKit because it's a 2D framework designed for games, but I'm not sure if there is a better solution.
Which of the frameworks in Swift could handle this?

*

*SwiftUI

*UIKit

*SpriteKit?

*Something else I've never heard of?

A: Sounds to me like a SpriteKit approach would work.
Using SKCamera will allow you to scroll around and zoom in/out of an SKScene.
SKScene has a bunch of built in methods for responding to clicks/taps on specific areas of the view.


text:
Q: repeated whole vector sampling in r I have following type of data
ntrt = paste ("EL", 1:4, sep= "")
repl = 3

I want to sample from the ntrt, but 3 times (rep =3), output something like below:
nsam <- c(sample(ntrt),sample(ntrt), sample(ntrt))
repl <- rep (1:3, each = length (ntrt))
newd <- data.frame (nsam, repl)
newd
 nsam repl
1   EL3    1
2   EL1    1
3   EL4    1
4   EL2    1

5   EL2    2
6   EL4    2
7   EL1    2
8   EL3    2

9   EL1    3
10  EL3    3
11  EL4    3
12  EL2    3

Here is my trial to loop:
nsam <- rep (NULL, ntrt)
for (i in 1:rep){
         nsam[i] <- sample(ntrt)
         }

Edits: just clarification
ntrt
[1] "EL1" "EL2" "EL3" "EL4"

> sample(ntrt,4)
[1] "EL4" "EL3" "EL2" "EL1"

# is equal to:
sample(ntrt)

but what I need:
c(sample(ntrt), sample(ntrt), sample(ntrt))

[1] "EL4" "EL3" "EL1" "EL2" "EL1" "EL2" "EL3" "EL4" "EL3" "EL1" "EL2" "EL4"

which is equal to
c(sample(ntrt,4), sample(ntrt,4), sample(ntrt,4))

Thus the process is:
# for repl = 1
sample from ntrt  size = length(ntrt)

# repeat the same process again
# for repl = 2
sample from ntrt  size = length(ntrt)
# note: I only concerned with order of names within ntrt (randomization process)

# repeat the same process again
# for repl = 3
sample from ntrt  size = length(ntrt)

same process for n levels of repl

I am getting error, sorry for a simple question

A: Try using lapply:
set.seed(1) # Just so you can compare -- remove for your actual purposes
ntrt = paste ("EL", 1:4, sep= "")
repl <- rep (1:3, each = length (ntrt))
nsam = unlist(lapply(1:3, FUN=function(i) sample(ntrt)))
newd <- data.frame (nsam, repl)
# > newd
# nsam repl
# 1   EL2    1
# 2   EL4    1
# 3   EL3    1
# 4   EL1    1
# 5   EL1    2
# 6   EL3    2
# 7   EL2    2
# 8   EL4    2
# 9   EL3    3
# 10  EL1    3
# 11  EL4    3
# 12  EL2    3

Update
I noticed that @joran had already recommended replicate in a comment. Here's the replicate approach:
data.frame(nsam = as.vector(replicate(3, sample(ntrt))), repl)

A: It appears you need to learn to use the help facilities in R. The sample function should do what you appear to be asking is you just submit a second argument:
?sample      # to get the help page
nsam <- sample(ntrt, 3)
nsam
#[1] "EL2" "EL1" "EL4"

To repeat permutation 3 times:
replicate(3, sample(ntrt, length(ntrt)))


text:
Q: Posting to Facebook group with Graph API Need some help understanding the Facebook documentation.
Using the Facebook Graph API, Can you log users into your site then allow them to post to a Facebook group?
Or is it only the group admin that can post to the group. If so, does anyone know if this is something that has changed recently ?
https://developers.facebook.com/docs/graph-api/reference/v2.5/group/feed

A:
Can you log users into your site then allow them to post to a Facebook group?

A specific Facebook group yes. As long as you know the ID beforehand.
For everything else the only groups available will be those seen from user_managed_groups


text:
Q: Comparing values to an overall average I want to divide each EPSF1 value from ticker=7203 JT Equity by the average EPSF1 value over 66,000 rows  I am not sure how to combine these two queries
select Date, Ticker,EPSF1
from tblForecasts
where EPSF1 is not null
and Ticker='7203 jt equity'

select AVG(epsf1)

A: Declare a variable, store the average there, then use it in your query:
declare @avg decimal
select @avg = AVG(epsf1) from tblForecasts

select Date, Ticker,EPSF1 / @avg
from tblForecasts
where EPSF1 is not null
and Ticker='7203 jt equity'


text:
Q: vbox layout working in Firefox but not in Google Chrome after adding a layout to the container element I am trying to create a screen with Sencha Touch 2 with the following structure:

Where the red main square is a Panel,, the blue square is a container and the geen squares should be two items with HTML content in them.
Below is the code I use in the Main.js file
Ext.define('EventApp.view.Main', {
    extend : 'Ext.tab.Panel',
    id : 'mainView',
    xtype : 'main',
    requires : [ 'Ext.TitleBar', 'Ext.Video' ],
    config : {
        tabBarPosition : 'bottom',

        items : [ {
            title : 'Home',
            iconCls : 'home',

            items : [ {
                docked : 'top',
                xtype : 'titlebar',
                title : 'Welcome to Sencha Touch 2'
            }, {
                xtype : 'eventsCarrousel'
            } ],
        },

        {
            title : 'Events',
            iconCls : 'time',
            id : 'eventsButton',

            items : [ {
                docked : 'top',
                xtype : 'titlebar',
                title : 'Events'
            }, {
                xtype : 'eventList',
            } ]
        }
        ]
    }
});

and in the view named eventsCarrousel.js
Ext.define('EventApp.view.eventsCarrousel', {
    extend: 'Ext.Container',
    xtype: 'eventsCarrousel',
    config: {
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        items : [{
            flex: 1,
            html : "This is the sample top pannel." ,
            style : 'background-color: #5E99CC;'
        }, {
            flex: 1,
            html : "Second pannel.",
            style : 'background-color: #4D99CC;'
        }]
    }
});

What I get out of this code is the following output:

Here are my problems (which I have circled in red)

*

*In Google Chrome the title text of the main panel is not displaying although it does display if I use Netscape.

*The items do not seem to be arranged using the vbox layout, although I have tried this same config in Sencha Try and did produce the desired Layout.

Could someone be so kind to point me out to what I might be doing wrong?
Extended info:
I found the following entry in stackoverflow wich pointed to the need of defining a template on the containing element ( Vbox layout issue in a tab panel ) therefore I modified my code of Main.js to add a fit layout to the component containing the eventsCarrousel
  Ext.define('EventApp.view.Main', {
    extend : 'Ext.tab.Panel',
    id : 'mainView',
    xtype : 'main',
    requires : [ 'Ext.TitleBar', 'Ext.Video' ],
    config : {
        tabBarPosition : 'bottom',

        items : [ {
            title : 'Home',
            iconCls : 'home',
            layout: 'fit', // JUST ADDED THIS LINE
            items : [ {
                docked : 'top',
                xtype : 'titlebar',
                title : 'Welcome to Sencha Touch 2'
            }, {
                xtype : 'eventsCarrousel'
            } ],
        },

        {
            title : 'Events',
            iconCls : 'time',
            id : 'eventsButton',

            items : [ {
                docked : 'top',
                xtype : 'titlebar',
                title : 'Events'
            }, {
                xtype : 'eventList',
            } ]
        }
        ]
    }
});

After this change it still did not work when I tested it using Firefox desktop browser and it works,  but it does not work when using Firefox.  I thought that it was suposed to be the other way arround since Chrome is a webkit based browser.
This is the output I get in Firefox:

An this is the exact same code running in Google Chrome.

My understanding was that the recomended testing browser was Google Chrome because it was based on webkit. Is this correct? Which is the most reliable desktop browser to test sencha touch 2 development in before doing so in the mobile devices?
Thanks

A: Finally I got the answer through another question posted in StackOverflow.
Most of my problems were caused by - Chrome 29 bug. See how to fix this here: http://www.sencha.com/forum/announcement.php?f=90&a=43


text:
Q: I want to create a Text String in a Parent Object of Multiple Products sold on a specific Opportunity using a Formula Field - Help? Parent Object - Opportunity
Child Object - Opportunity Product
I have a field for each product on the Opportunity.
For example if Opportunity Products X and Y were added to the Opportunity as Opportunity Products on Opportunity fields would state :
Product X=1
PRoduct Y=1
1 indicated products was purchased.
I need to create a formula field that would look up each product's field and if the field is 1 return the name of the product and do it in a string. The issue is if multiple products were purchased the string should return all.
Example
Product X=1
Product Y=1
Product Z=0
Products W=0
New field
Products Purchased = X,Y
I tried to achieve this with IF formulas, but as soon as it evaluated to true it stops checking for other Products. I thought of using the Case formula, but as I understand it works only with retuning numbers.
this is what I have so far, but no idea how to combine it
IF ( Opportunity__r.Product_X >0,"X",
IF( Opportunity__r.Product_Y >0,"Y",
IF( Opportunity__r.Product_Z >0,"Z",
IF(Opportunity__r.Product_W>0,"W",
""))))


text:
Q: how to enter Bitbucket password on mac terminal? How do I connect to bitbucket on my mac?
I'm trying to import my existing code into bitbucket using terminal on mac, but after I do a "git push -u origin master" it asks for my bitbucket password but it doesn't let me type my password.

A: In general, when you input a password in a terminal, you don't see anything as you do it.  Many graphical environments show you an asterisk or bullet for each character, but the way terminals work is simply that they turn off the echo (that is, the display) of the characters you type.
So when you're typing your password in the terminal, it is being entered, but nothing is being displayed on the terminal, and that's normal.  Just type it in as you usually would, and then hit Enter.


text:
Q: Android's WorkManager not running when scheduled from a service My works scheduled in the WorkManager are not always being executing when the app in the background. This is how I schedule them:
    Constraints myConstraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build();

    OneTimeWorkRequest batchingWork = new OneTimeWorkRequest.Builder(BatchingJobWorker.class)
            .setConstraints(myConstraints)
            .setInitialDelay(minLatencyJobs, TimeUnit.MILLISECONDS)
            .setBackoffCriteria(BackoffPolicy.LINEAR, 10 * 1000, TimeUnit.MILLISECONDS)
            .addTag(BATCHING_JOB_WORK)
            .build();

    WorkManager.getInstance(context)
            .enqueueUniqueWork(BATCHING_JOB_WORK, ExistingWorkPolicy.APPEND, batchingWork);

I read from this other thread that the problem could be that the Android operating system could be killing / force stopping the app so that the services, schedulers, alarms, broadcast receivers, etc., are no longer working.

*

*Android. Is WorkManager running when app is closed?
However, in my case I'm scheduling the job from a background service and the delays I'm setting are small (1 min or less), so I know that the app is running at that moment. Also, I'm testing this with my testing devices, so I know no one is killing the app by swipping it from the recents menu. This is the exact procedure I'm following:

*

*An MQTT message is received in the background service

*I request a PARTIAL_WAKE_LOCK

*Some code is executed (I know this code is being called, so I suppose the MQTT and background service part is working fine).

*I schedule the work in the WorkManager.

As I said, in some cases the doWork() of the worker is not executed. These are some tests I did:

*

*When the work is scheduled in a running activity with a button click and the app is in foreground, it works as expected.

*Disabling the battery saver mode in some phones seems to help, but It doesn't fix the problem in 100% of the cases.

*Some smartphones or ROMs seem to have higher probability of executing the scheduled work.

*When the worker doesn't executes I don't see any exception in the log.

*The failure probability seems to increase with the amount of previous jobs executed in the background. In fact, when no more works are being executing, usually reinstalling the app fixes the problem.

*With the device connected to power seems to work better.

Could anyone with me a clue about what is happening here? Am I doing something wrong?
Thanking you in advance.


text:
Q: Docker Compose Always Force Build for One Service This is a section of my docker-compose file:
version: "3.2"
services:
  cachable_service:
    image: my/cachable_service:x.x
    build:
      context: .
      dockerfile: cachable_service_Dockerfile

  service_in_development:
    image: my/service_in_development:latest
    build:
      context: .
      dockerfile: Dockerfile
    depends_on:
      - cachable_service

How do I force only the image for the service_in_development to be always build from scratch so I get my latest code in there?
I've looked into the cache_from option in the docker-compose file reference, but I couldn't find any clear explanation on what exactly it does.
Clarifications:
In this question, I was asking about an option to force rebuild only specific services using an option in the docker-compose.yml file itself. But, if a commandline option let's me do this, I'd be happy with that as well for now.
Also, I'm talking about forcing a 'rebuild' of images. Not just 'recreation' of service.

A: You can use command below to rebuild all images:
docker-compose up --build --force-recreate

to force rebuild one service:
docker-compose up --build --force-recreate service-name-here

More useful parameters in documentation

Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]

Options:
    -d, --detach               Detached mode: Run containers in the background,
                               print new container names. Incompatible with
                               --abort-on-container-exit.
    --no-color                 Produce monochrome output.
    --quiet-pull               Pull without printing progress information
    --no-deps                  Don't start linked services.
    --force-recreate           Recreate containers even if their configuration
                               and image haven't changed.
    --always-recreate-deps     Recreate dependent containers.
                               Incompatible with --no-recreate.
    --no-recreate              If containers already exist, don't recreate
                               them. Incompatible with --force-recreate and -V.
    --no-build                 Don't build an image, even if it's missing.
    --no-start                 Don't start the services after creating them.
    --build                    Build images before starting containers.
    --abort-on-container-exit  Stops all containers if any container was
                               stopped. Incompatible with -d.
    -t, --timeout TIMEOUT      Use this timeout in seconds for container
                               shutdown when attached or when containers are
                               already running. (default: 10)
    -V, --renew-anon-volumes   Recreate anonymous volumes instead of retrieving
                               data from the previous containers.
    --remove-orphans           Remove containers for services not defined
                               in the Compose file.
    --exit-code-from SERVICE   Return the exit code of the selected service
                               container. Implies --abort-on-container-exit.
    --scale SERVICE=NUM        Scale SERVICE to NUM instances. Overrides the
                               `scale` setting in the Compose file if present.


text:
Q: List not displaying after adding elements to array I have a list of elements recovered from a URL like this.
 queryByDepartamentoEstado(departamento: number, estatus: EstatusRequisicion, req?: any): Observable<EntityArrayResponseType> {
    const options = createRequestOption(req);

    return this.http.get<IRequisicion[]>(`${this.resourceUrl}/departamento/${departamento}/estatus/${estatus}`, {
     params: options,
     observe: 'response'
    })
    .pipe(map((res: EntityArrayResponseType) => this.mapeaInfoDeptos(res)));

then the result is sent to this method, which is empty (for now)
  protected mapeaInfoDeptos( res: EntityArrayResponseType ): EntityArrayResponseType{

    return res;
  }

an this is the result.

now if I add this into the method mapeaInfoDeptos
  protected mapeaInfoDeptos( res: EntityArrayResponseType ): EntityArrayResponseType{

    let idsDepartamentos: number[];

    if (res.body) {
      res.body.forEach((requisicion: IRequisicion) => {
        idsDepartamentos.push( requisicion.requeridoPorId ? 0 : 1);//With this the code does not run
         requisicion.sedeId ;
      });
    }

    return res;
  }

as you can see I'm trying to add an element from the entity IRequisicion to the array idsDepartamentos, after adding this piece of code the list it is not displayed, I checked in the developer tools (chrome ) and in the console from where the app is launched but no error is displayed.
Thank you for any advice or help you can provide.


text:
Q: Laravel migration name is too long I am trying to migrate the whole Laravel application, When I write the code below I have some error.
    // Create table for associating permissions to users (Many To Many Polymorphic)
   Schema::create('permission_user', function (Blueprint $table) {
        $table->unsignedInteger('permission_id');
        $table->unsignedInteger('user_id');
        $table->string('user_type');
        $table->unsignedInteger('project_id')->nullable();.
        $table->foreign('permission_id')->references('id')->on('permissions')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('project_id')->references('id')->on('projects')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->unique(['user_id', 'permission_id', 'user_type', 'project_id']);
    });

The error:

SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'permission_user_user_id_permission_id_user_type_project_id_unique' is too long (SQL: alter table permission_user add unique  permission_user_user_id_permission_id_user_type_project_id_unique(user_id, permission_id, user_type, project_id))`

When I remove the code above, everything works well. What is wrong? I do not find anything?!

A: The laravel's way of generating a unique key is too long. You can override this by doing
$table->unique(['user_id', 'permission_id', 'user_type', 'project_id'], 'my_unique_ref');

Also, if the foreign keys are too long you can override the default name but providing a second parameter.
$table->foreign('permission_id', 'my_new_reference')->references('id')->on('permissions')
                ->onUpdate('cascade')->onDelete('cascade');


text:
Q: Create several multiplication tables instead of one at a time saved to several .txt files I want to create several multiplication tables by telling this python program how many I want to make. Then, have the program create that number of multiplication tables saved to that same number of created .txt files. I want one table per .txt file. What code do I need to add and how do I do it? Thanks for your time.
This is the program I want to add the functionality to:
def tablep():
    n=int(input("Enter a Number:"))
    start=int(input("Enter a start:"))
    end=int(input("Enter an end:"))

    file=open("*table.txt","a")

    if start<end:
        for i in range(start,end+1):
            s = str(n) + "*" + str(i) + "=  " + str(n*i)
            file.write(s)
            file.write("\n")
            print(n,"*",i,"=",n*i)

    elif start>end:
        for i in range(start,end,-1):
            s = str(n) + "*" + str(i) + "=" + str(n * i)
            file.write(s)
            file.write("\n")
            print(n, "*", i, "=", n * i)

    file.close()

w = tablep()

Example output I want in each file to have. This is just one of the files containing the multiplication table with 3:
3*0=    0
3*1=    3
3*2=    6
3*3=    9

A: From my understanding of your question, you want each txt file to be unique based on the start and end inputs, so you need to just loop over n times:

def tablep():
    n=int(input("Enter a Number:")) # number of txt files

    for x in range(0, n):
        start=int(input("Enter a start:"))
        end=int(input("Enter an end:"))
        f_path = "table_" + str(x) + ".txt" # this will numerate each table
        file = open(f_path, 'w+') # 'w+' tag will create a file if it doesn't exist
        if start<end:
            for i in range(start,end+1):
                s = str(n) + "*" + str(i) + "=  " + str(n*i)
                file.write(s)
                file.write("\n")
                print(n,"*",i,"=",n*i)

        elif start>end:
            for i in range(start,end,-1):
                s = str(n) + "*" + str(i) + "=" + str(n * i)
                file.write(s)
                file.write("\n")
                print(n, "*", i, "=", n * i)

        file.close()


text:
Q: Rewrite URL where one variable is changing I am trying to get below .htaccess rewrite working where the page=1 can have any numeric value
RewriteCond %{QUERY_STRING} ^per_page\=10&page\=1&_embed&categories\=&categories_exclude\=31,32,92$
RewriteRule ^wp\-json/wp/v2/posts$ /wp-json/wp/v2/posts?per_page=10&page=1&_embed&categories_exclude=31,32,92 [L]

So if the variable id page=6 it stays that way.
Any suggestions?

A: Capture the value of the page URL parameter in the RewriteCond regex (CondPattern) and use a corresponding %<number> backreference in the substitution string. For example:
RewriteCond %{QUERY_STRING} ^per_page=10&page=(\d+)&_embed&categories=&categories_exclude=31,32,92$
RewriteRule ^wp-json/wp/v2/posts$ /wp-json/wp/v2/posts?per_page=10&page=%1&_embed&categories_exclude=31,32,92 [L]

The regex \d is a shorthand character class for digits and is equivalent to the long-hand [0-9].
The %1 backreference contains the string captured by the first capturing subgroup, (\d+), in the preceding CondPattern (ie. the value of the page URL parameter).
Aside: No need to backslash-escape = and - in the regex as they carry no special meaning in the context they are being used here.
Reference:

*

*https://httpd.apache.org/docs/current/rewrite/intro.html

However, you might as well capture "everything" and save repetition, "simplifying" the substitution string. For example:
RewriteCond %{QUERY_STRING} ^(per_page=10&page=\d+&_embed)&categories=(&categories_exclude=31,32,92)$
RewriteRule ^wp-json/wp/v2/posts$ /$0?%1%2 [L]

Here, we capture the part of the query string before and after the &categories= URL parameter (the section to be removed). These are saved in the %1 and %2 backreferences respectively.
The $0 backreference contains the URL-path matched by the entire RewriteRule pattern.


text:
Q: What can we say about $\Phi$? Let $m$ be Lesbegue measure on $[0,1]$ and define $|f|_{p}$ with respect to $m$. Find all functions $\Phi$ on $[0,\infty)$ such that the relation
$$\Phi(\lim_{p\rightarrow 0}|f|_{p})=\int^{1}_{0}(\Phi\circ f)dm$$
Show first that $$c\Phi(x)+(1-c)\Phi(1)=\Phi(x^{c}),(x>0, 0\le c \le 1)$$

By previous conclusion we have $$\lim_{p\rightarrow 0}|f|_{p}=e^{\int \log|f|dx}$$ So we only need to find $\Phi$ such that $$
\Phi(e^{\int \log|f|dx})=\int^{1}_{0}(\Phi\circ f)dx
$$
Let $F$ be a measurable function by being $X$ on $x\in [0,c]$ and $1$ on $[c,1]$. Then the right hand side become $c\Phi(x)+(1-c)\Phi(1)$. The right hand side now become $e^{c\log[x]}=x^{c}$. So we conclude that
$$c\Phi(x)+(1-c)\Phi(1)=\Phi(x^{c}),(x>0, 0\le c \le 1)$$ as desired.
Similarly we may let $F$ be a measurable function that is $X$ on $[0,c]$ and $Y$ on $[c,1]$. Then the right hand side is $c\Phi(x)+(1-c)\Phi(y)$. The integral now become $e^{c\log[X]+(1-c)Log[Y]}=X^{c}Y^{1-c}$, and we have the more general identity
$$c\Phi(X)+(1-c)\Phi(Y)=\Phi(X^{c}Y^{1-c})$$
At this point it feels obvious that $\Phi$ can be the $\log[x]$ function or a constant times $\log[x]$ function. But $\Phi(1)\not=0$ is possible; So it is not clear to me how to construct $\Phi$ precisely.
I do not know if this is a duplicate.


text:
Q: how to output different types of data in php? This is how my table is shown.

The code for the creation and returning of the table:
i would like to test the value of the sport ID value. if it is 1, return football. if it is 2 return Tennis and if it is 3 return swimming. And if the away column is TRUE i want it to output Away, else output HOME.
$sql = "CREATE TABLE fixtureDetails
(
fixtureID INT(5) NOT NULL AUTO INCREMENT,
opponent VARCHARD(30) NOT NULL,
date DATE
away BOOLEAN,
sportID INT
refereeID INT,
PRIMARY KEY (fixtureID),
FOREIGN KEY (sportID) REFERENCES sport(sportID),
FOREIGN KEY (refereeID) REFERENCES referee(refereeID)
)";

$sql1 = "SELECT * FROM fixtureDetails";
if ($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result)>0){
        echo "
";
            echo "
";
                echo "fixtureID	";
                echo "opponent	";
                echo "date	";
                echo "away	";
                echo "sportID	";
                echo "refereeID	";
            echo"
";
        while($row = mysqli_fetch_array($result)){
            echo "
";
                echo "" . $row['fixtureID'] . "	";
                echo "" . $row['opponent'] . "	";
                echo "" . $row['date'] . "	";
                echo "" . $row['away'] . "	";
                echo "" . $row['sportID'] . "	";
                echo "" . $row['refereeID'] . "	";
            echo "
";
        }
        echo "
";
        mysqli_free_result($result);
    } else {
        echo "No records matching your query found.";
    }
} else {
    echo "ERROR: could not execute $sql1. " . mysqli_error($link);
}

A: You don't show the structure of the Sport table, so I'm assuming there is a column in that table named Name.  You can change this part to reflect your actual table.
I wouldn't use PHP to retrieve those values if they're already in the database (as hinted by the following in your CREATE statement):
FOREIGN KEY (sportID) REFERENCES sport(sportID),

Instead of the SELECT * FROM fixtureDetails; query you're using, I would use the following query instead:
Select  F.FixtureId,
        F.Opponent,
        F.Date,
        Case When F.Away = 1 Then 'Away' Else 'Home' End As Away,
        S.Name As Sport,    -- Change S.Name to the actual column in Sport.
        F.RefereeId
From    FixtureDetails  F
Join    Sport           S   On  S.SportId = F.SportId

A: Please check it:
echo "" . (isset($row['away']) && $row['away']) ? 'AWAY' : 'HOME' . "	";

A: echo "" . $row['fixtureID'] . "	";
echo "" . $row['opponent'] . "	";
echo "" . $row['date'] . "	";
if($row['away'])
  echo "Away	";
else
  echo "Home	";

switch($row['sportID']){
   case 1: echo "Football	";
       break;
   case 2: echo "Tennis	";
       break;
   case 3: echo "Swimming	";
       break;
   default: echo "Error!";
 }
echo "" . $row['refereeID'] . "	";


text:
Q: Run Commands without Spaces I won't bore you with the details but I need to pass a command to a file without spaces, with each space it considers the next text to be a variable which is not the case. I need to be able to create a command with another character other than space or use hex characters to overcome this. Unfortunately I am completely locked to using this method as this file exists on 1000s of devices and I would need to change the file manually on each device, if I can workaround it's limitations then this would be the best solution for me.
Does anyone have any ideas if this is possible?
edit
Hi guys for some more info, lets say I have the file test.sh, it has a function called echo_var, if I use the command for example
test.sh echo_var helloworld

The function will simply echo helloworld
If I say use the command
test.sh echo_var hello world

Only hello gets echoed as it considers "hello world" as two strings and only acknowledges the first one, the function takes each separated string as a variable and only uses the first variable ie hello. I need to make hello world one variable
The command I want to run is to restart a service ie
test.sh echo_var hello&&service apache2 restart

So both hello will be echoed and the service restarted. But after the space after service, the command is cut.
Here is the file (test.sh) I have to interact with, again this is on 1000s of devices and I need to work with it:
case "$1" in
    echo_var)
        echo "$2"
        ;;

A: Use double quote around your string
Below one should work fine
test.sh echo_var "hello world"

A: #!/bin/sh
echo_var="hello world"
echo  $echo_var

Are you looking for something like this?
#!/bin/sh
echo_var="Apache Server Restarted"
echo  $echo_var >> /var/log/ApacheRestart.log
service apache2 restart

So something like this might help you out.

A: The solution for me was the following:
./test.sh echo_var test1;what="service restart apache2";$what

This means the spaces are never caught by the script


text:
Q: Why does the STL overload their constructors with/without allocator argument? in std::vector, why does the stl overload the constructors like that:
vector( const vector& other );
vector( const vector& other, Allocator& a );

Why not just do this?
vector( const vector& other, Allocator& a = Allocator() );

Edit:
Since rvalues can't bind to a non const lvalue, then this can be done instead:
vector( const vector& other, const Allocator& a = Allocator() );

A: The allocator parameter allows the copy to use a specified allocator. The standard provides both constructors because they have fundamentally different properties.
The version with no allocator parameter will make a copy using the same allocator as other. Whereas the version with a specified allocator will make a copy using that allocator. Your suggestion of providing a default allocator makes distinguishing between these two versions impossible.
Here's what the documentation says:
vector(const vector& other) :

Copy constructor. Constructs the container with the copy of the contents of other.

The allocator is obtained as if by calling std::allocator_traits<allocator_type>::select_on_container_copy_construction( other.get_allocator())

vector(const vector& other, const Allocator& alloc) :

Constructs the container with the copy of the contents of other, using alloc as the allocator.

The template parameter Allocator is only deduced from the first argument while used in class template argument deduction.

A:
Why not just do this?
vector( const vector& other, Allocator& a = Allocator() );

Because a non const lvalue ref cannot be bound to a temporary so Allocator& a = Allocator() won't work.

Edit

Since rvalues can't bind to a non const lvalue, then this can be done instead:
vector( const vector& other, const Allocator& a = Allocator() );

Even if you were to use a const lvalue ref then that would make vector(vec) to be ambiguous as the compiler wouldn't know which one of the above two constructors to use.


text:
Q: Creating a Quick links box with border I am having serious issues with making a quick links box. Please see my website http://www.orkoa.com/index4.html, you will notice I have played around with a few things and I am stuck. I was hoping you could help.
1) I am trying to add quick links and trying reduce the height of the top-sidebar and make the text perfectly center and align. I am having a very difficult time to achieve this.
2) In addition, I have added a gallery from w3c tutorials page, and added this within the "mainContent class". Its working, but is this the correct way to go about this? If you do it independently, the gallery just sits at the bottom outside the "bottomcontent" class.
Any advice?

A: To center align the h3 text in the to side bar, add this to your existing css
.top-sidebar h3 {
  text-align: center;
}

if you wish to cneter align all text in the side bar add this instead
.top-sidebar {
  text-align: center;
}

A: Instead of using aside tag, you should make a div container and make it float: right
then you can place all the other sidebars inside that container, using more divs
you can then easily adjust their heights as all of them would be independent divs, although I'll suggest to avoid handling heights if you want to make it responsive. Better will be to use bootstrap.
As for making text center, you can use text-align: center. Whichever portion of the div needs to be in center, you can add this to the CSS of that portion.
Also, currently all the aside tags are having float: left, they should be float: right


text:
Q: "The second half of the second decade of the third millennium"
"The second half of the second decade of the third millennium"

I have difficulty understanding the phrase above. Can anyone help me out?

A: It means the time period from 2015 until 2020. Sometimes, pictures are "worth a thousand words":

A: I think a good way to look at this is to read it backward. Like how you read numbers by going from the largest to the smallest, you would understand this sentence by looking at the end - where the object of the sentence is - and working back from there.
So you have the third millennium. Ignoring other ways of counting years, that means 2001-3000. So we have 2xxx. Then it says the second decade. That would be 201x. Then it's just the second half, so just the second half of the 2010s.
I hope that makes sense! It's possible I made a silly math error but the breakdown should at least be sound.


text:
Q: Invalid configuration of route 'auth'. One of the following must be provided: component, redirectTo, children or loadChildren I'm trying to set up routing to a component in my app directory. For some reason, I keep this error Invalid configuration of route 'auth'. One of the following must be provided: component, redirectTo, children or loadChildren. I think AuthComponent is showing up as undefined, but I can't get why. I'm not an expert in angular, so I could just be making a syntax error. Any help is greatly appreciated!!
Here is my app-routing.module.ts:
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { AuthComponent } from './auth/auth.component'

const routes: Routes = [
 {
   path: 'auth',
   component: AuthComponent
 },
];

const config: ExtraOptions = {
 useHash: false,
};

@NgModule({
 imports: [RouterModule.forRoot(routes, config)],
 exports: [RouterModule],
})
export class AppRoutingModule {}

and here is my auth.component.ts:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { NbAuthSocialLink } from '@nebular/auth';
import { NbAuthService } from '@nebular/auth';

export declare class AuthComponent {

   protected service: NbAuthService;
    protected options: {};
    protected cd: ChangeDetectorRef;
    protected router: Router;
    redirectDelay: number;
    showMessages: any;
    strategy: string;
    errors: string[];
    messages: string[];
    user: any;
    submitted: boolean;
    socialLinks: NbAuthSocialLink[];
    rememberMe: boolean;
    constructor(service: NbAuthService, options: {}, cd: ChangeDetectorRef, router: Router);
    login(): void;
    getConfigValue(key: string): any;
}

A: Angular uses annotations to define components, that appears to be what you are missing.
@Component({
  selector: 'app-my-auth',
  templateUrl: './my-auth.component.html',
  styleUrls: ['./my-auth.component.scss'],
  providers: [myServiceService]
 })

The easiest way to create these annotations is to let the angular cli work for you, just run the command ng g c Auth, which is short for ng generate component Auth, and it will create a class named 'AuthComponent' and register it in your module.
Once that is done you can move your component code into it and use reference it in your routing module.
These components need to be defined in a module for use as well. For simple project you can put them in app-module, but otherwise the general best practice is to lazy load modules and separate components into them, with separate modules being made for components that get shared across your site.


text:
Q: What are ways to deal with circular covariates (e.g. with a GAM)? I'm building a model in which several of my covariates live on a "circle", in the sense that they take values in the interval [0,1), and 0=1.  I'm wondering about techniques for dealing with this situation.  One idea is to represent a circular variable theta as a pair of variables ( sin(theta), cos(theta) ).  Any thoughts on this approach or better approaches?
I'm specifically using the mgcv package GAMs.  Is there a way to tell the model that certain additive pieces should have the same values at the endpoints?  Another package?
Thanks!

A: There are two ways of dealing with circular variables, one hacky method would be to manually duplicate your data set on either side of the boundary conditions but the more elegant solution I think would be to use the built-in spline basis functions with periodic boundary conditions !
For example:
bs="cc" specifies a cyclic cubic regression splines (see cyclic.cubic.spline). i.e. a penalized cubic regression splines whose ends match, up to second derivative.
Splines on the sphere
bs="sos". These are two dimensional splines on a sphere. Arguments are latitude and longitude, and they are the analogue of thin plate splines for the sphere. Useful for data sampled over a large portion of the globe, when isotropy is appropriate. See Spherical.Spline for details.
bs="cp" gives a cyclic version of a P-spline

A: You might want to look into Gill and Hangartner (2010). Circular Data in Political Science and How to Handle It. They talk about various models for circular/clock/seasonal data, and Jeff Gill provides R code for the paper which you can look into for inspiration. There should be a presentation version of this material which would weave the methodology and R code together.


text:
Q: point.in.poly (spatialEco) returns non-intersecting points I just updated the spatialEco package for R, and now the point.in.poly function behaves differently from previous behavior. Previously, it returned only points that intersected at least one of the polygons in the polygon layer. Now, it returns all points, including those that do not intersect with any polygons (the polygon fields are NA for the non-intesecting points). It seems that an extra step is now necessary to retain only the intersecting points, which doesn't seem desirable to me. It is not too burdensome to add the extra step, but it does break old code that uses point.in.poly. Is there a way to retain only the intersecting points in the output from the point.in.poly function?
Below is some example code that illustrates what I mean.
library(rgeos)
library(sp)
library(spatialEco)
library(raster)

coords <- matrix(c(0,0,0,10,10,10,10,0,0,0),5,2,byrow=TRUE)
SA <- SpatialPolygonsDataFrame(SpatialPolygons(list(Polygons(list(Polygon(coords)),1))),data.frame(pol=1))

pts <- spsample(SA,50,"regular")
pts <- SpatialPointsDataFrame(pts,data.frame(ptid=1:length(pts)))
smallSA <- gBuffer(SA,width= - 1,byid=TRUE)
grd <- raster(extent(smallSA),resolution=2)
grd <- as(grd,"SpatialPolygons")
grd <- SpatialPolygonsDataFrame(grd,data.frame(pol=1:length(grd)))
plot(SA)
plot(grd,add=TRUE)
plot(pts,add=TRUE,col="blue",pch=20)
pts2 <- point.in.poly(pts,smallSA) # includes non-intersecting points!
plot(pts2,add=TRUE,col="red",pch=20)
length(pts)
length(pts2)

# remove non-intersecting points
pts3 <- pts2[-which(is.na(pts2$pol)==TRUE),]
length(pts3)
plot(pts3,add=TRUE,col="blue",pch=20)

A: You can use st_intersection() from sf, which retains the data from both data sets and keeps only those points actually intersecting your polygon geometry. The sole drawback here is that your Spatial* objects must be made available as sf objects, which can be handled through st_as_sf(). The resulting object can be transformed back to Spatial*  using as() as shown below. See also this related answer.
library(sf)

tmp = st_intersection(st_as_sf(pts), st_as_sf(smallSA))
pts4 = as(tmp, "Spatial")

plot(SA)
plot(grd, add = TRUE)
plot(pts4, col = "blue", pch = 20, add = TRUE)

identical(pts3, pts4)
# TRUE


text:
Q: Add the difference of two pandas column values to a new row if the difference is greater than a column value in Pandas '''
This is a sample of data I have
'''
PERIOD GROUP USER_COUNT REGION
50    A     55            AX
25    A     20            AX
30    B     33            BY
40    C     10            CZ

Expected Output
PERIOD GROUP USER_COUNT REGION
50    A        50         AX
50    A         5         AX
25    A        20         AX
30    B        30         BY
30    B        3          BY
40    C        10         CZ

A: Use:
#get difference of columns
s = df['USER_COUNT'].sub(df['PERIOD'])
#mask for positive subtract values
m = s > 0

#subtract of original data ony matched rows of column VAL2
df1 = df.assign(USER_COUNT = lambda x: x['USER_COUNT'].sub(s[m], fill_value=0))
#overwrite matched rows
df2 = df[m].assign(USER_COUNT = s[m])

#join together and sorting by only stable sorting - mergesort
df3 = (pd.concat([df1, df2])
         .sort_index(kind='mergesort')
         .reset_index(drop=True)
         .astype(df.dtypes))
print (df3)
   PERIOD GROUP  USER_COUNT REGION
0      50     A          50     AX
1      50     A           5     AX
2      25     A          20     AX
3      30     B          30     BY
4      30     B           3     BY
5      40     C          10     CZ


text:
Q: Weird text in android studio I just installed android studio in my windows. But here is what I get:

How to fix my android studio?

A: This solved to me:
(Unrecognized characters in the Android Studio Setup Wizard).
Just removed Bizagi Studio and everything work fine now.

A: It seems you have choosen a different language set package to download (or it was the option you took at install time - if this feature is available). The weird characters are displayed probably because your system seems not to know how to handle this different language set (can be chinese, japanese, arabic, cirilic etc). Try installing A.S. again, to see if you have language options, or try downloading the correct A.S. for your language.

A: Change the windows fonts using WinAeroTweaker. working 100%


text:
Q: Binding separate list into one listbox I want to bind my listbox with separate list data that I get from json web service, so it looks like this:
public List<Phone> phone { get; set; }
public List<Fax> fax { get; set; }
public List<Email> email { get; set; }
public List<Website> website { get; set; }

and I want to bind all that list into one single listbox, so my listbox will have phone,fax,email and website in one item... how to do that?
edit: example of the format that i have in mind

phone: +04532534534
fax : +5234523453
email : user@user.com
website : www.user.com

edit: my approach so far is getting putting separated list into separated property into my mainviewmodel
RootObjectDetail result = JsonConvert.DeserializeObject<RootObjectDetail>(e.Result);
if (result.contacts.email != null)
    hereRestEmail = new ObservableCollection<Email>(result.contacts.email);
if (result.contacts.phone != null)
    hereRestPhone = new ObservableCollection<Phone>(result.contacts.phone);
if (result.media.reviews.items != null)
    hereRestReview = new ObservableCollection<ItemReview>(result.media.reviews.items);
if (result.media.images.items != null)
    hereRestImage = new ObservableCollection<ItemImage>(result.media.images.items);

but i just don't know how to bind it into my listbox datacontex since i only can bind one of thos property
 <telerikPrimitives:RadDataBoundListBox
   x:Name="ContactListBox"
   ItemsSource="{Binding hereRestPhone}">
    <telerikPrimitives:RadDataBoundListBox.ItemTemplate>
       <DataTemplate>

          <TextBlock Text="{Binding LocalizedResources.phone,
                      Mode=OneWay, Source={StaticResource LocalizedStrings}}"
                       Style="{StaticResource PhoneTextLargeStyle}"/>
          <TextBlock Grid.Column="1" Text="{Binding value}"
                       Style="{StaticResource PhoneTextLargeStyle}" />

       </DataTemplate>
     </telerikPrimitives:RadDataBoundListBox.ItemTemplate>

it only can show phone only, i still don't know how to bind fax,email and website into this listbox

A: Without knowing what your classes look like internally, I can only guess:
 var allValues =
     phone.Select(x => new { Type = "phone", Value = x.PhoneNumber })
          .Concat(fax.Select(x => new { Type = "fax", Value = x.FaxNumber }))
          .Concat(email.Select(x => new { Type = "email", Value = x.EmailAddr }))
          .Concat(website.Select(x => new { Type = "website", Value = x.URL }))
          .ToList();

You'll end up with a list (of anonymous types) with a "Type" and "Value".
I haven't tested this, but you should be able setup a template in your XAML, bind to "Type" and "Value", and get them to display like you've indicated above.


text:
Q: Dynamic switching of fragments My Activity contains two buttons (Next and Back) and a fragment. When the Activity starts, it gets an array of resources.
Such as {"Fish", "Bird", "Animal"};
Or this {"Fish", "Bird", "Animal", "Bird", "Bird"}; etc.
Depending on the contents of the array, the Next button should switch the fragments accordingly:
So: Fragment_Fish.java >Fragment_Bird.java>Fragment_Animal.java.
So: Fragment_Fish.java >Fragment_Bird.java>Fragment_Animal.java. >Fragment_Bird.java>Fragment_Bird.java>
How is it easier to implement in Java, please tell me?

A: I don't understand your problem clearly, I think you want to switch between fragments.
If you want to switch between multiple fragments, you can use navigation components for this.
You can explore about navigation components.
Resources :- Integrate the Navigation component

A: *

*You need to make an array of the fragments like this:

Fragment[] fragments = new Fragment[]]{new Fragment_Fish(), and other fragments separated with commas};

*Make a int variable in the class something like this:

int counter = 0;

*Increase the counter on button click and update the fragment. Like this:

buttonNext.setOnClickListener(v -> {
   counter ++;
   if(!counter >= fragments.size()){
      //all the fragments are opened do what you need
      return;
   }
   final FragmentTransaction ft = getFragmentManager().beginTransaction();
   ft.replace(R.id.details, fragments[counter]);
   ft.commit();
   //came to another fragment
});


text:
Q: "add employee" form without page redirect Im sending form data from employee.php to a new_employee.php, new_employee.php inserts the data to my database.
After submitting the form it redirects the user to new_employee.php and let them know if it where successful or not.
What I want is that it clears the form and let the user know if it was successful or not on employee.php rather than redirecting the user.
NOTE! I know that this isnt sql injection protected or anything but i simplified it when i posted it here.
And im also aware that i should use mysqli.
employee.php

    <form id="add-emp" method="POST" action="add_employee.php">
            <input type="text" id="name" name="name" placeholder="Full Name" />
            <input type="text" id="email" name="email" placeholder="Email" />

            <input type="submit" value="Register Employee" class="button"  onClick="fun();"/>
    </form>

And this is my new_employee.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
     mysql_connect("localhost", "****", "****");
     mysql_select_db("****");

$stmt = "INSERT INTO employee (name, email) VALUES ('$name', '$email')";
$result = mysql_query($stmt);
     if($result){
     echo("success!");
     }else{
     echo("failed!");
     }

?>

A: There are a few things going wrong here. You have a }) to many in your code and defined var form but using $form:
$('#add-emp').submit(function(event) {
        event.preventDefault();
        var form = $(this),
                value1 = form.find( 'input[name="name"]' ).val(),
                value2 = form.find( 'input[name="email"]' ).val(),
                url = form.attr( 'action' );

        var posting = $.post( url, { name: value1, email: value2 }, function(data) { alert(data)} );
 });

And with the callback function in $.post you can see what happens and get your message (failed or success) back.
https://api.jquery.com/jQuery.post/

A: You almost there, all that is left is to grab the string of you echo in php file, and add it to the dom.
success: function(data){
  var div = document.getElementById('#messageDiv');
  div.innerHTML(data);
}


text:
Q: Redirecting stdin - C So I'm meant to accept a text file by doing the following command:
$ sort < list.txt

I understand that the list text file is being inputted to my sort program, but how do I actually use the information inside my program? How do I read it?
My code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {

    char c;

    while (c != EOF){
        c = getchar();
        printf("%c ",c);
    }

   return (0);
}

Example:
$ ./sort.c < input.txt

./sort.c: line 3: $'\r': command not found

./sort.c: line 4: syntax error near unexpected token `('

'/sort.c: line 4: `int main(int argc, char** argv) {

A: When you use the '<' symbol on the command line as you have written in your post, the OS reads the file for you and gives the contents to your program via stdin. So, all you need to do is to read from stdin.
Here is a very simple code snippet to demonstrate -
#include <stdio.h>

int main() {
    char line[256];
    FILE *fp = stdin;
    while(fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);
    }
}