text:
Q: Get Content-Disposition parameters How do I get Content-Disposition parameters I returned from WebAPI controller using WebClient?
WebApi Controller
    [Route("api/mycontroller/GetFile/{fileId}")]
    public HttpResponseMessage GetFile(int fileId)
    {
        try
        {
                var file = GetSomeFile(fileId)

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(new MemoryStream(file));
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = file.FileOriginalName;

                /********* Parameter *************/
                response.Content.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("MyParameter", "MyValue"));

                return response;

        }
        catch(Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }

    }

Client
    void DownloadFile()
    {
        WebClient wc = new WebClient();
        wc.DownloadDataCompleted += wc_DownloadDataCompleted;
        wc.DownloadDataAsync(new Uri("api/mycontroller/GetFile/18"));
    }

    void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        WebClient wc=sender as WebClient;

        // Try to extract the filename from the Content-Disposition header
        if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
        {
           string fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", ""); //FileName ok

        /******   How do I get "MyParameter"?   **********/

        }
        var data = e.Result; //File OK
    }

I'm returning a file from WebApi controller, I'm attaching the file name in the response content headers, but also I'd like to return an aditional value.
In the client I'm able to get the filename, but how do I get the aditional parameter?

A: If you are working with .NET 4.5 or later, consider using the System.Net.Mime.ContentDisposition class:
string cpString = wc.ResponseHeaders["Content-Disposition"];
ContentDisposition contentDisposition = new ContentDisposition(cpString);
string filename = contentDisposition.FileName;
StringDictionary parameters = contentDisposition.Parameters;
// You have got parameters now

Edit:
otherwise, you need to parse Content-Disposition header according to it's specification.
Here is a simple class that performs the parsing, close to the specification:
class ContentDisposition {
    private static readonly Regex regex = new Regex(
        "^([^;]+);(?:\\s*([^=]+)=((?<q>\"?)[^\"]*\\k<q>);?)*$",
        RegexOptions.Compiled
    );

    private readonly string fileName;
    private readonly StringDictionary parameters;
    private readonly string type;

    public ContentDisposition(string s) {
        if (string.IsNullOrEmpty(s)) {
            throw new ArgumentNullException("s");
        }
        Match match = regex.Match(s);
        if (!match.Success) {
            throw new FormatException("input is not a valid content-disposition string.");
        }
        var typeGroup = match.Groups[1];
        var nameGroup = match.Groups[2];
        var valueGroup = match.Groups[3];

        int groupCount = match.Groups.Count;
        int paramCount = nameGroup.Captures.Count;

        this.type = typeGroup.Value;
        this.parameters = new StringDictionary();

        for (int i = 0; i < paramCount; i++ ) {
            string name = nameGroup.Captures[i].Value;
            string value = valueGroup.Captures[i].Value;

            if (name.Equals("filename", StringComparison.InvariantCultureIgnoreCase)) {
                this.fileName = value;
            }
            else {
                this.parameters.Add(name, value);
            }
        }
    }
    public string FileName {
        get {
            return this.fileName;
        }
    }
    public StringDictionary Parameters {
        get {
            return this.parameters;
        }
    }
    public string Type {
        get {
            return this.type;
        }
    }
}

Then you can use it in this way:
static void Main() {
    string text = "attachment; filename=\"fname.ext\"; param1=\"A\"; param2=\"A\";";

    var cp = new ContentDisposition(text);
    Console.WriteLine("FileName:" + cp.FileName);
    foreach (DictionaryEntry param in cp.Parameters) {
        Console.WriteLine("{0} = {1}", param.Key, param.Value);
    }
}
// Output:
// FileName:"fname.ext"
// param1 = "A"
// param2 = "A"

The only thing that should be considered when using this class is it does not handle parameters (or filename) without a double quotation.
Edit 2:
It can now handle file names without quotations.

A: With .NET Core 3.1 and more the most simple solution is:
using var response = await Client.SendAsync(request);
response.Content.Headers.ContentDisposition.FileName

A: You can parse out the content disposition using the following framework code:
var content = "attachment; filename=myfile.csv";
var disposition = ContentDispositionHeaderValue.Parse(content);

Then just take the pieces off of the disposition instance.
disposition.FileName
disposition.DispositionType

A: The value is there I just needed to extract it:
The Content-Disposition header is returned like this:
Content-Disposition = attachment; filename="C:\team.jpg"; MyParameter=MyValue

So I just used some string manipulation to get the values:
void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    WebClient wc=sender as WebClient;

    // Try to extract the filename from the Content-Disposition header
    if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
    {
        string[] values = wc.ResponseHeaders["Content-Disposition"].Split(';');
        string fileName = values.Single(v => v.Contains("filename"))
                                .Replace("filename=","")
                                .Replace("\"","");

        /**********  HERE IS THE PARAMETER   ********/
        string myParameter = values.Single(v => v.Contains("MyParameter"))
                                   .Replace("MyParameter=", "")
                                   .Replace("\"", "");

    }
    var data = e.Result; //File ok
}

A: As @Mehrzad Chehraz said you can use the new ContentDisposition class.
using System.Net.Mime;

// file1 is a HttpResponseMessage
FileName = new ContentDisposition(file1.Content.Headers.ContentDisposition.ToString()).FileName


text:
Q: use events after loading script I have two events which use functions from script. How to start use this functions only after loading script?
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/intl-tel-input/js/intlTelInput.js"></script>
    <script>
        var settings = {
            utilsScript: "../lib/intl-tel-input/js/utils.js",
            initialCountry: "auto",
            geoIpLookup: function (callback) {
                $.get("http://ipinfo.io", function () { }, "jsonp").always(function (resp) {
                    var countryCode = (resp && resp.country) ? resp.country : "";
                    callback(countryCode);
                });
            }
        };
        $("#phoneNumber").intlTelInput(settings);
        $("#viber").intlTelInput(settings);

        $("#phoneNumber").on('input', function (e) {
            var intlNumber = $("#phoneNumber").intlTelInput("getNumber");
            $("#viber").intlTelInput("setNumber", intlNumber);
        });
        $("#phoneNumber").on("countrychange", function (e, countryData) {
            $("#viber").intlTelInput("setCountry", countryData.iso2);
        });
</script>

in google chrome console:
Uncaught TypeError: $(...).intlTelInput is not a function

A: use $(document).ready(function(){})
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/intl-tel-input/js/intlTelInput.js"></script>
<script>
   $(document).ready(function(){
        var settings = {
            utilsScript: "../lib/intl-tel-input/js/utils.js",
            initialCountry: "auto",
            geoIpLookup: function (callback) {
                $.get("http://ipinfo.io", function () { }, "jsonp").always(function (resp) {
                    var countryCode = (resp && resp.country) ? resp.country : "";
                    callback(countryCode);
                });
            }
        };
        $("#phoneNumber").intlTelInput(settings);
        $("#viber").intlTelInput(settings);

        $("#phoneNumber").on('input', function (e) {
            var intlNumber = $("#phoneNumber").intlTelInput("getNumber");
            $("#viber").intlTelInput("setNumber", intlNumber);
        });
        $("#phoneNumber").on("countrychange", function (e, countryData) {
            $("#viber").intlTelInput("setCountry", countryData.iso2);
        });
   });
</script>

A: I'm located script in Scripts section and it solve the problem.
@section Scripts {
        <script src="~/lib/intl-tel-input/js/intlTelInput.js"></script>
        <script>
            $(document).ready(function () {
                var settings = {
                    utilsScript: "../lib/intl-tel-input/js/utils.js",
                    initialCountry: "auto",
                    geoIpLookup: function (callback) {
                        $.get("http://ipinfo.io", function () { }, "jsonp").always(function (resp) {
                            var countryCode = (resp && resp.country) ? resp.country : "";
                            callback(countryCode);
                        });
                    }
                };
                $("#phoneNumber").intlTelInput(settings);
                $("#viber").intlTelInput(settings);

                $("#phoneNumber").on('input', function (e) {
                    var intlNumber = $("#phoneNumber").intlTelInput("getNumber");
                    $("#viber").intlTelInput("setNumber", intlNumber);
                });
                $("#phoneNumber").on("countrychange", function (e, countryData) {
                    $("#viber").intlTelInput("setCountry", countryData.iso2);
                });
            });
        </script>

A: Try to include "intlTelInput-jquery.min.js" from the library under jquery. It solved my problem.
<script src="//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/js/intlTelInput-jquery.min.js"></script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: tkinter value error : id must be a valid identifier returned from after or after_idle def start_quest(self):
    quest = pyautogui.locateCenterOnScreen('quest.jpg', confidence = 0.9)
    if quest:
        pyautogui.click(quest[0] - 100, quest[1])
        self.after_cancel(self.loop)
    self.loop = self.after(1000, self.start_quest)

with tkinter gui,  I am trying to click the button if the pyautogui detects it. I used self.after to make the function to work until detection. However, the code returns an error:

value error : id must be a valid identifier returned from after or after_idle

Also, because the pyautogui captures the window every seconds, the gui have buffering. How can I fix it?


text:
Q: Generate diagonal matrix from regression coefficient I am trying to generate a diagonal matrix using a linear regression coefficient. First I generated an empty matrix. Then I extract the coefficient from the regression model. Here's my code:
P = np.zeros((ncol, ncol), dtype = int)
intercep = np.zeros((1, ncol), dtype = int)

my_pls = PLSRegression(n_components = ncomp, scale=False)
model = my_pls.fit(x, y)

#extract pls coeffeicient:
coef = model.coef_
intercep = model.y_mean_ - (model.x_mean_.dot(coef))

P[(i-k):(i+k), i-k] = np.diag(coef[0:ncol])

But I got zero matrices after running the code. Can anyone please help me out with how to get the diagonal matrix from the regression coefficient?

A: Not sure why you need to declare P.
You can get diagonal matrix with zeros directly from the 1D list/vector using numpy.diag
x=[3,5,6,7]
numpy.diag(x)

Output:
array([[3, 0, 0, 0],
       [0, 5, 0, 0],
       [0, 0, 6, 0],
       [0, 0, 0, 7]])

For your case, try P=np.diag(coef)


text:
Q: Browser opens many times while Geb testing I wrote the following test for my simple Spring Boot Web application:
@SpringApplicationConfiguration(classes=[PDK])
@WebIntegrationTest
@DirtiesContext
class GebMainpageSpec extends GebSpec {

    @Autowired
    WebApplicationContext context;

    def setup() {

        System.setProperty("webdriver.chrome.driver", "chromedriver/win32/chromedriver.exe");

        browser.driver = new ChromeDriver();
        browser.baseUrl = "http://localhost:8080/";

    }

    def 'Static page present and works, check without pages'() {

        when:
            go ""

        then:
            assert title == "MyApp"

    }

    def 'Static page present and works, check WITH pages'() {
        when:
            to Mainpage

        then:
            LoginWithFormUsername.value() == "root"

    }

}

These tests are apparently work, i.e. they pass or fail depending on page data.
The problem is that it opens TWO instances of Chrome browser to operate (by number of tests).
How to prevent that? May be reuse browser? Or may be close it after each test?
UPDATE
If I add something like below
def cleanupSpec() {
    browser.driver.quit()
}

then all my tests startin to run twice, moreover, each second run they try with HtmlUnit (i.e. with "in memory" web browser, not Chrome).

A: You shouldn't instantiate the driver yourself when using GebSpec because it already handles the lifecycle of a driver instance through a browser instance it lazy initializes in it's getBrowser() method.
See the sections of The Book of Geb about how Geb interacts with WebDriver instances and about configuring the driver to be used via the config script to learn more.


text:
Q: Save with multiple checkbox i have 3 different topics in 1 lesson week. i want to add new curriculum week but use can select he would to like (for example use can select only basic or memorization).
this is my HTML part but i don't know what should now in backend side?
<ion-card-content>
                                        <ion-item-group>
                                            <ion-item>
                                                <ion-checkbox [value]="genel"
                                                              id="topicTypeGenel"></ion-checkbox>
                                                <ion-label
                                                        style="padding-left: 5px">{{'LESSONLIST.genel' | translate}}</ion-label>
                                            </ion-item>
                                            <ion-item>
                                                <ion-checkbox [value]="ezber"
                                                              id="topicTypeEzber"></ion-checkbox>
                                                <ion-label
                                                        style="padding-left: 5px">{{'LESSONLIST.ezber' | translate}}</ion-label>
                                            </ion-item>
                                            <ion-item>
                                                <ion-checkbox [value]="yuezune"></ion-checkbox>
                                                <ion-label
                                                        style="padding-left: 5px">{{'LESSONLIST.yuezuene' | translate}}</ion-label>
                                            </ion-item>
                                        </ion-item-group>
                                    </ion-card-content>


text:
Q: Error Passing java List to dart List Ok, I followed completely this example: https://flutter.io/platform-channels/
and tried to modify it like so:
List<double> points;

 try {

 //Changed This
 /*final  String  result = await platform.invokeMethod('getBatteryLevel');
 batteryLevel = 'Battery level at $result % .'; */

 //To This
 final  List<double>  result = await platform.invokeMethod('getBatteryLevel');
 points = result;
 print("Message 2");

Then In MainActivity.java, changed the getBatteryLevel function to this:
private List<Double> getBatteryLevel() {

        List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
        return list;

And Lastly changed the MethodCall to this:
List<Double> batteryLevel = getBatteryLevel();

  Log.i("errors", "Message");
  result.success(batteryLevel);

But when I run the code, the Message 1 gets printed but Message 2 does not.
I noticed that with simple types like Strings and Integer instead of List worked. I also tried to replace List with arrays in java, but still didn't work. The Problem is that I don't get any error any stacktraces, anything. What I thought is that in dart he's waiting for something that never comes as Lists of doubles in Dart and Java aren't the same. But it's just a thing I thought. Could it be the problem? How Can I solve it?

A: Try to receive the List without <double> because Dart assumes the type inside the List is dynamic and not primitive, so you have an error when you try to parse List<dynamic> into List<double>.
 final List result = await platform.invokeMethod('getBatteryLevel');

Should work.
Don't forget to include your imports in your MainActivity, looks like you are using Arrays and List classes, then import the following classes:
import java.util.Arrays;
import java.util.List;


text:
Q: Instagram recent tag So I'm working with the Instagram API and using the recent tag call. The problem is I just want photos from today. I looked through the docs and the only parameters you can pass to the api are max_tag_id and min_tag_id. What would be the best method to insure I only get pics from today and not have to save every max_id to reference in my next call?

A: If I understand your question correctly, you can provide a timestamp range according to the API Documentation.  Alternatively, you can just accept everything the API call returns and use a little logic on your end to filter the results.  Can you show us your code and what the API reply looks like, so we can provide better guidance?

A: They way I fixed this was to not supply a min or max ID. Supplying these IDs will iterate through the most recent tag's 'pagination', not supplying them will bring back the most recent tags.
http://www.instagram.com/developer/endpoints/tags/#get_tags_media_recent


text:
Q: VBA Excel - Compile Error - Expected function or variable It's probably something simple but I have been trying to work out how to fix a compile error I am getting with an excel document I have created for a while now and I have not made any progress.
Basically there is a form that has several buttons that call a public function called "writeEntry" which is stored in a module called "describePhotosExcel". The code breaks no matter where writeEntry is called from.
So far I have tried calling the function from different subs, changing the subs from private to public, adding the module name before the function and renaming the function... I'm not quite sure what else I can do. Any help would be much appreciated.
Code from the form:
Private Sub PrevPhotoBTN_Click()
   wrow = CInt(PhotoDataEntry.CurrentRow.Caption)
   test = writeEntry(wrow, Direction.Text, RoadCombo.Text, Chainage.Text, Location.Text, CommentsCombo.Text, Condition.Text)
   wrow = CInt(PhotoDataEntry.CurrentRow.Caption) - 1
   PhotoDataEntry.CurrentRow.Caption = wrow
   temp = PopulatePhotoForm()
End Sub

Code from the module "describePhotosExcel":
Public Function writeEntry(CurrentRow, Dir, RoadName, Chainage, Optional Title = "", Optional Comments = "", Optional Rating = "", Optional PhotoNumber = "") As Variant
    Application.Workbooks(PhotoDataEntry.WBK.Caption).Activate
    Worksheets("Data").Activate

    Cells(CurrentRow, 6) = Dir
    Cells(CurrentRow, 8) = RoadName
    Cells(CurrentRow, 9) = Chainage
    Cells(CurrentRow, 10) = Title
    Cells(CurrentRow, 11) = Comments
    Cells(CurrentRow, 14) = Rating
    Cells(CurrentRow, 13) = PhotoNumber
    writeEntry = 1
End Function

A: So I worked it out.
I had created a subroutine called "test" which was used to do some testing.
Therefore when it saw the word test it thought I was referring to this subroutine and not a new variable I was throwing away. Deleted that and it works well now.


text:
Q: Trouble Reading from Serial.readstring() arduino UNO The objective is to enter "on" and "off" in COM port and switch the Pin 13. No matter what I do. It won't switch on or off. Need help. I tried to see if the string I entered is "on". It prints "on" but when I check for the result it shows its different. What is wrong?
String SData;
String SData1;
 void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
delay(5000);
digitalWrite(13,LOW);
delay(1000);
 }

 void loop() {
// put your main code here, to run repeatedly:
while(Serial.available()==0)
{

}
SData=Serial.readString();
SData1="on";
if(SData==SData1)
Serial.print("Same");
else
{
Serial.print("Different");
// Serial.print(SerialData-SerialData1);
Serial.print(".");
}
if(SData=="on")
  {
  digitalWrite(13,HIGH);

  Serial.println("LED ON");
  delay(2000);
  }
Serial.println(SData);
if(SData=="off")
 {
  digitalWrite(13,LOW);
  Serial.println("LED OFF");
  delay(2000);
 }
SData="";
}


text:
Q: Virtualizing an Inline network appliance with VirtualBox (or VMWare) My device, which is a Linux based IP in-liner is transparent to the network peripherals, that is, no IP address assigned to any of its interfaces.
For the sake of the conversation, let's use ADSL connection as an example, while the device is inspecting the bi-directional traffic, the network is behaving same as if device was not there, attached to the wire (see Physical setup at the attached diagram).
I wonder if I can enclosed that "device" within a Windows machine and have it operated virtually so it still seats inline between the ADSL router and the Windows netwroking interface by using virtual NICs, (or whatever their name is in windows), and inspecting the traffic, same as if it was on a separate physical device, the drawing under "Virtual Setup" in the attached diagram show what I am trying to achieve.
Reading a bit on the VirtualBox docs, seems like binding the right side is relatively simple, perhaps I should have one network adapter set as Bridge Networking and VirtualBox will connect it to the physical NIC on the host machine, and network packets are exchanged directly, circumventing the host operating system's network stack (WinXP in my case).
However, I have no idea how to achieve the left side of my diagram, which requires adding virtual NICs to windows and configure them correctly in a way to make that pipeline possible.
I would appreciate any help.
by the way, if that is not possible with VirtualBox but with other virtualization solution (e.g. VMWare), I would accept the other as well.
components setup diagram http://img715.imageshack.us/img715/810/physicalvsvirtualsetup2.png

A: It depends on whether you want ( or more if it can ) your linix ( *nix ) inline device to "route" the packets that go through it possibly from one network to another and whether you want this "app" to essentially have no access directly out of your virtual environment ( the green box in your diagram ). If so, what might work is something like:

*

*your "app" is run inside a virtual machine ( say another windows xp instance ) with a NIC configured on a virtual internal or "private" network ( I'm positive both virtualbox and vmware server have this option ) but with the same IP subnet and as your actual network 192.168.1.0

*the left side - eth0 - of your *nix device ( which would have to be a virtual machine ) is also set up on this internal / private network

*the right side - eth1 - of your *nix device is set up on a bridged network so it has real work access into your real network

This will make it slightly easier to see if traffic / packets are infact going through your *nix device or not, as the app will not have access outside of the virtual internal/private network. NOTE when i say internal/private network I'm not talking about VPNs, just a private network that the host nor your network can reach and the virtual machines can't contact the host or your network.
Without knowing what your *nix device is doing its a little hard. if it can't route or act as a pass through device of some description then the dhcp broadcasts wont get to your dhcp server - which is what I'm guessing your doing something around given that you mentioned it in your diagram.
If your *nix device is a real device then obviously this wont work as I'm assuming its a virtual machine of some description. If this is the case let me know and I'll give some advise on how to work with that situation.
Good luck


text:
Q: How to resize a Bitmap Image and set it as the backgroound of a grid in Windows Phone 8 I tried doing this but I can't figure out how to set the height and width of the ImageBrush before setting it as the background of the grid.
BitmapImage bmp= new BitmapImage(new Uri(imagePath, UriKind.Relative));
int height = bmp.DecodePixelHeight;
int width = bmp.DecodePixelWidth;

ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = bmp;
MainGrid.Background = imgBrush    // MainGrid is the name of the Grid

A: If you simply want to set the imageBrush to fill the gird properly set the stretch property of the imageBrush to either uniform (maintains proportions but may leave empty spots) or uniform to fill (maintains proportions, does not leave empty spots, but whole picture may not fit in grid).
Otherwise there is more complex code here to set the exact pixel width and height of an imageBrush.
http://msdn.microsoft.com/en-us/library/ms742114.aspx


text:
Q: JTextArea not changing size vertically in MigLayout I have a JTextField called jta in my java program and i want it to be about 4 rows tall and I set the size when I declared the TextField and i also used jta.setSize() but I still cannot get it taller. I think it is because the MigLayout has a limit for how big a component can be in a row.
Here is a snippit of my code:
static JTextArea jta = new JTextArea(10, 42);
//declaring the JTextArea
    jta.setFont(inputfont);
    jta.setBackground(Color.LIGHT_GRAY);
    jta.setForeground(Color.WHITE);
    jta.setLineWrap(true);
    jta.setWrapStyleWord(true);
    jta.setRows(4);
//setting the jta up
panel.add(jta,"w 100%, h 100%,span,wrap");\
//adding jta to the panel

Here Is What It Looks Like

as you see it is only one line of text high, any help?
SSCCE:
import net.miginfocom.swing.MigLayout;

public class miglayout {

public static void main(String args[]) {
    MigLayout mg = new MigLayout("", "", "1");
    JFrame frame = new JFrame("jta SSCCE");
    JPanel panel = new JPanel();
    JLabel l1 = new JLabel("Row 1");
    JLabel l2 = new JLabel("Row 3");
    panel.setLayout(mg);
    frame.add(panel);
    JTextArea jta = new JTextArea(4, 40);
    panel.add(l1, "wrap");
    panel.add(jta, "wrap");
    panel.add(l2);
    frame.pack();
    frame.setVisible(true);
    }
}

As you can see if you run this code, even though I set the size of the JTextArea it is still one line, but if you comment out the panel.setLayout(mg); then it works fine.

A: Im not an expert using this layout but thanks you post a SSCCE.
if you change
MigLayout mg = new MigLayout("", "", "1");

to
MigLayout mg = new MigLayout();

I get


text:
Q: Actualizar letras mayusculas/minusculas de los campos, todos igual primera letra de cada palabra mayuscula Tengo 2 campos distintos donde uno almaceno un solo nombre ejemplo "Sean Michaels" y otro donde almaceno varios separados con una coma detrás de la coma puede ir tanto el nombre como un espacio ejemplo "Sean Michaels, Mr. Marcus, Steve Holmes"
Algunos nombres pueden tener caracteres especiales como tildes o '.
El problema que algunos tengo guardado el texto como ejemplo:
Sean Michaels
Sean michaels
sean michaels
SEAN MICHAELS
y necesitaría que todos quedaran de esta forma "Sean Michaels" (primera letra de cada palabra en mayúscula) y lo mismo en el otro campo que incluye varios separados con ,
Me gustaría si es posible desde una consulta SQL metida por el phpmyadmin que actualizara todos esos campos especificados.

A: Para este tipo de problemas, las tablas de números (o tally tables en inglés) son una gran herramienta. Ellas nos ayudan a recorrer la cadena sin necesidad de utilizar bucles explícitos y poder utilizar funciones tipo tabla en línea que no afectan el rendimiento de las consultas. En este ejemplo, creo una tabla de números al vuelo que evita la lectura al disco y la genera completamente en memoria. La limito al número de caracteres de la cadena y luego valido los caracteres comparándolos con el anterior.
DECLARE @String varchar(8000) = 'SEAN MICHAELS';

WITH
E(n) AS( --10 filas
    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS( --10x10 = 100 filas
    SELECT a.n FROM E a, E b
),
E4(n) AS( --100x100 = 10,000 filas (suficiente para varchar(8000))
    SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
    SELECT TOP(LEN(@String)) --Limitamos las filas
            ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n --Generamos los números
    FROM E4
)
SELECT ( SELECT CASE WHEN SUBSTRING( @String, n-1, 1) LIKE '[A-Za-z]' --Si el caracter anterior es una letra
            THEN LOWER( SUBSTRING( @String, n, 1)) --ponemos el caracter en minúscula
            ELSE UPPER( SUBSTRING( @String, n, 1)) END --si no, lo ponemos en mayúscula
        FROM cteTally
        FOR XML PATH(''), TYPE).value('./text()[1]', 'varchar(8000)'); --FOR XML PATH concatena el resultado y lo convertimos en texto

Esta consulta, la podemos convertir fácilmente en una función tipo tabla.
CREATE FUNCTION ConvertirTipoTitulo
(
    @String varchar(8000)
)
RETURNS TABLE  --Regresa una tabla
WITH SCHEMABINDING --Le ayuda a SQL Server a identificar que no depende de ningún objeto
AS
RETURN
WITH
E(n) AS( --10 filas
    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS( --10x10 = 100 filas
    SELECT a.n FROM E a, E b
),
E4(n) AS( --100x100 = 10,000 filas (suficiente para varchar(8000))
    SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
    SELECT TOP(LEN(@String)) --Limitamos las filas
            ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n --Generamos los números
    FROM E4
)
SELECT ( SELECT CASE WHEN SUBSTRING( @String, n-1, 1) LIKE '[A-Za-z]' --Si el caracter anterior es una letra
            THEN LOWER( SUBSTRING( @String, n, 1)) --ponemos el caracter en minúscula
            ELSE UPPER( SUBSTRING( @String, n, 1)) END --si no, lo ponemos en mayúscula
        FROM cteTally
        FOR XML PATH(''), TYPE).value('./text()[1]', 'varchar(8000)') AS Cadena; --FOR XML PATH concatena el resultado y lo convertimos en texto

Ahora, esta función solo la tenemos que llamar usando APPLY.
SELECT tt.Cadena, t.*
FROM MiTabla t
CROSS APPLY dbo.ConvertirTipoTitulo( LaColumnaAConvertir) tt;


text:
Q: Difference in output order in Debug and Run modes in Eclipse. Why is the representation of the output of the following Java program differs in Debug and in Run as Java application modes in Eclipse?
For the below Java code,
public class ThrowDemo {

    static void demoproc() {
        try {
            NullPointerException nullPointerException = new NullPointerException();
            throw nullPointerException; // or new NullPointerException();
            //System.out.println("Unreachable Code is an error in Java");
        } catch (NullPointerException e) {
            System.out.println("Caught inside demoproc.");
            throw e; // rethrow the exception
        }
    }

    static void throwing(){
        throw new NullPointerException();
    }

    public static void main(String args[]) {
        try {
            demoproc();
        } catch (NullPointerException e) {
            System.out.println("Recaught: " + e);
        }
        throwing();
    }
}

the output must be in this order of listing which I get, when I debug it as Java application.
Caught inside demoproc.
Recaught: java.lang.NullPointerException
Exception in thread "main" java.lang.NullPointerException
    at throwkeyword.ThrowDemo.throwing(ThrowDemo.java:17)
    at throwkeyword.ThrowDemo.main(ThrowDemo.java:26)

When i run it as Java application, the listing is as follows :
Caught inside demoproc.
Exception in thread "main" java.lang.NullPointerException
    at throwkeyword.ThrowDemo.throwing(ThrowDemo.java:17)
    at throwkeyword.ThrowDemo.main(ThrowDemo.java:26)
Recaught: java.lang.NullPointerException

Why it(the console) gives such a difference in Eclipse?


text:
Q: member function get() on null on woocommerce/includes/wc-notice-functions.php on line 80 I am working on a Woocommerce shipping plugin where I have a class method with the following that is triggered on a custom do_action
try {
    $client = new SoapClient( plugin_dir_path( dirname( __FILE__ ) ) . 'includes/wsdl/Test.wsdl', ['trace' => true, 'exceptions' => true ]  );
    $results = $client->__soapCall('CreateSomml', ['parameters' =>  ['Details' => $bill->__toArray() ]]);
} catch (SoapFault $e) {
    wc_add_wp_error_notices(new WP_Error('soap', $e->getMessage(), isset($client)? $client->__getLastRequest() : $bill->__toArray() ));
    // print $client->__getLastRequest();
    // throw $e;
}

which tries to connect to a web service and would catch any SoapFault and add an error notice but on running the code I run into an error

Fatal error: Call to a member function get() on null in ...../wp-content/plugins/woocommerce/includes/wc-notice-functions.php on line 80

which based on the documentation leads to
function wc_add_notice( $message, $notice_type = 'success' ) {
    if ( ! did_action( 'woocommerce_init' ) ) {
        wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
        return;
    }

    $notices = WC()->session->get( 'wc_notices', array() );

    // Backward compatibility
    if ( 'success' === $notice_type ) {
        $message = apply_filters( 'woocommerce_add_message', $message );
    }

    $notices[ $notice_type ][] = apply_filters( 'woocommerce_add_' . $notice_type, $message );

    WC()->session->set( 'wc_notices', $notices );
}

Line 80 is return
I assume it could be
WC()->session->set( 'wc_notices', $notices ); But not sure why the error.
The action is being triggered from the backend admin management. hat could be the problem?
I'm running PHP 5.6.27 with Wordpress 4.8 and Woocommerce 3.2.1
UPDATE:
been trying to find the error and all I can come up with was

Fatal error: Uncaught Error: Call to a member function get() on null in /var/www/wordpress/wp-content/plugins/woocommerce/includes/wc-notice-functions.php:80 Stack trace: #0 /var/www/wordpress/wp-content/plugins/woocommerce/includes/wc-notice-functions.php(198): wc_add_notice('Invalid User Cr...', 'error') #1 /var/www/wordpress/wp-content/plugins/wc-trinicargo-shipping/includes/class-wc-trinicargo-shipping-create-waybill.php(80): wc_add_wp_error_notices(Object(WP_Error)) #2 /var/www/wordpress/wp-includes/class-wp-hook.php(296): Wc_Trinicargo_Shipping_Create_Waybill->create() #3 /var/www/wordpress/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters('', Array) #4 /var/www/wordpress/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #5 /var/www/wordpress/wp-content/plugins/wc-trinicargo-shipping/includes/class-wc-trinicargo-shipping-create-waybill.php(68): do_action('wc_trinicargo_c...') #6 /var/www/wordpress/wp-content/plugins/wc-trinicargo-shipping/admin/partials/wc-trinicargo-shipping-init-methods.php(163): Wc_ in /var/www/wordpress/wp-content/plugins/woocommerce/includes/wc-notice-functions.php on line 80

Why is the session not starting? how do I start it?

A: So for anybody looking for a solution to this one - the issue is that the WC()->session isn't yet available here. I ran into the issue trying to add a notice inside of an 'admin_post' action. Initializing an empty session worked for me here:
WC()->session = new WC_Session_Handler();
WC()->session->init();

After those two lines I was able to successfully use wc_add_notice. Hope that helps somebody.


text:
Q: Windows Phone GetGeopositionAsync() returns wrong location I have a button which calls CurrentLocation whenever it is pressed.
private async void CurrentLocation()
{
    try
    {
        Geolocator myGeolocator = new Geolocator();
        Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(3));
        Geocoordinate myGeocoordinate = myGeoposition.Coordinate;
        GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate(myGeocoordinate);
        this.MyMap.Center = myGeoCoordinate;
    }
    catch
    { }

}

I've been testing the app on the Windows Phone emulator and everything was working fine. But today while I was pressing the button in the app running on a Lumina 640 while driving in a car, the app began showing different locations.
Anyone know what what might be wrong in my code?
EDIT:
Construcor
public MainPage()
{
    InitializeComponent();
    distanceTextBox.Visibility = Visibility.Collapsed;

    CreateStandardApplicationBar();

    pointNamePrompt = new InputPrompt()
    {
        Title = "Point",
        Message = "Name the point",
    };
    try
    {
        CurrentLocation();
        MyMap.ZoomLevel = 10;
    }
    catch { }

    LoadAppSettings();
}

Button
private void CurrentLocation_Click(object sender, EventArgs e)
{
    CurrentLocation();
}

And finally new new code which still work just for the first time when app starts:
private async void CurrentLocation()
{
    try
    {
        Geolocator myGeolocator = new Geolocator();
        Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10));

        ReverseGeocodeQuery query = new ReverseGeocodeQuery();
        query.GeoCoordinate = new System.Device.Location.GeoCoordinate(myGeoposition.Coordinate.Latitude, myGeoposition.Coordinate.Longitude);

        query.QueryCompleted += (s, e) =>
        {
            if (e.Error != null && e.Result.Count == 0)
                return;
            MessageBox.Show(e.Result[0].Information.Address.PostalCode);
        };
        query.QueryAsync();

        double lat = 0.00, lng = 0.00;
        lat = Convert.ToDouble(myGeoposition.Coordinate.Latitude);
        lng = Convert.ToDouble(myGeoposition.Coordinate.Longitude);

        this.MyMap.Center = new GeoCoordinate(lat, lng);
    }
    catch
    { }

}

A: Try below code:
private async void CurrentLocation()
{
    try
    {
        Geolocator myGeolocator = new Geolocator();
        Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(5),timeout: TimeSpan.FromSeconds(10));

        ReverseGeocodeQuery query = new ReverseGeocodeQuery();
        query.GeoCoordinate = new System.Device.Location.GeoCoordinate(myGeoposition.Coordinate.Latitude, myGeoposition.Coordinate.Longitude);

        query.QueryCompleted += (s, e) =>
        {
            if (e.Error != null && e.Result.Count == 0)
                return;
            MessageBox.Show(e.Result[0].Information.Address.PostalCode);
        };
        query.QueryAsync();

        double lat = 0.00, lng = 0.00;
        lat = Convert.ToDouble(myGeoposition.Coordinate.Latitude);
        lng = Convert.ToDouble(myGeoposition.Coordinate.Longitude);

        this.MyMap.Center = new GeoCoordinate(lat, lng);
        this.MyMap.ZoomLevel = 7;
        this.MyMap.Show();
    }
    catch
    { }

}


text:
Q: How to override FOSUserBundle's ProfileController in Symfony 3? I'm trying to override some parts of the FOSUserBundle.
I have to custom the ProfileController (especially the showAction). I looked for a solution, and found that I had to create a new ProfileController in my UserBundle, and inherits the original FOSUserBundle ProfileController.
That's what I have done.
use FOS\UserBundle\Controller\ProfileController as BaseController;

class ProfileController extends BaseController

I also know how to override twig views by creating same name files in my own UserBundle.
My problem is, that I don't know how to make Symfony using my ProfileController instead of the original.
Do I have to change routes in App/Config/routing.yml ?
Or simply create an .xml routing file in my UserBundle, and then import it in App/Config/routing.yml?
I first made the mistake of customing FOSUserBundle files but I know it wasn't the right way, that's why I'm trying to do clean changes now.

A: The ProfileController is registered as a service named fos_user.profile.controller as you can see in this configuration file.
In order to override the controller/service (for Symfony 3.4) you need to re-define this service inside your app/config/services.yml:
services:
  # [..]
  'fos_user.profile.controller':
    class: 'Your\Namespace\ProfileController'
    public: true
    arguments:
      - '@event_dispatcher'
      - '@fos_user.profile.form.factory'
      - '@fos_user.user_manager'
    calls:
      - [ 'setContainer', [ '@service_container' ]]

Now clear your cache.
Symfony will then use your ProfileController class as the service named fos_user.profile.controller.


text:
Q: Modelling Tennis Torunament with EF6 I want to generate a tennis tournament and i thought about this solution:
public class Torneo
{
    public int Id { get; set; }
    public int NrGiocatori { get; set; }
    public virtual Provincia Provincia { get; set; }
    public virtual List<Girone> Gironi { get; set; }
    public virtual List<TurnoTabellone> TurniTabellone { get; set; }
}

public class Girone
{
    public int Id { get; set; }
    public int TorneoId { get; set; }
    public string NomeGirone { get; set; }
    public virtual List<PartitaGirone> PartiteGirone { get; set; }
}

public class PartitaGirone : Partita
{
    public int Id { get; set; }
    public int GironeId { get; set; }

}

public class TurnoTabellone
{
    public int Id { get; set; }
    public int TorneoId { get; set; }
    public Turno Turno { get; set; }
    public virtual List<PartitaTabellone> PartiteTabellone { get; set; }
}

public class PartitaTabellone : Partita
{
    public int Id { get; set; }
    public int TurnoTabelloneId { get; set; }
}

public class Partita
{
    public int IdGiocatore1 { get; set; }
    public int IdGIocaotre2 { get; set; }
    public int GameGiocatore1 { get; set; }
    public int GameGiocatore2 { get; set; }
    public DateTime DataIncontro { get; set; }
    public int OraIncontro { get; set; }
}

Torneo = Tournament
Girone = Round Robin
PartitaGirone = Round Robin Match
TurnoTabellone = BoardRound, for example all Quarter of final/Semifinal/Final...
PartitaTabellone = Board Match
Partita = Match
Provincia = Province
This is the ER model:

What dumfounded me is the duplication of the matches fields in PARTITAGIRONE and PARTITATABELLONE.
On the other hand i can't use just one table for "match" because of different relationships between GIRONE and TURNOTABELLONE.
Any tip?
I also avoid to add players in the entities because i still don't know where to put them.
UPDATE 1:
And what if i use a single table for match even if i have some null foreign Keys in base of what entity i'm populating?
I fill some data to test with LinqPad:

For Girone (Round Robin) i will have TurnoTabelloneId (Round Board Id) null, viceversa if i fill TurnoTabelloneId and if i don't fill anything i will have a third case that rapresents a single match not bound with tournament.
In the first step i didn't want to leave foreign Keys blank, but, i thought about it and now it doesn't seem to me a bad idea.
The new rapresentation of the ER is:


text:
Q: How to expand LineString centerline into a rectangular polygon in PostGIS? I have a table containing LineString geometries (SRID=4326). Given that line, I also have a "left" and "right" value in miles for each row. They may not always be equal.
I want to produce a polygon from that LineString that is properly expanded on each side in miles to form a resulting rectangle.
I was trying to adapt this solution here so far without success: https://gis.stackexchange.com/questions/60655/polygon-to-fill-gap
I can generate two parallel lines with ST_OffsetCurve(), but haven't been able to create the polygon so far. Thanks a lot for any suggestions!

A: You can create a minimum bounding rectangle for your linestring geometry. The function in postgis you can use is ST_Envelope. See https://postgis.net/docs/ST_Envelope.html for some examples. If you have this rectangle, you can expand it with your given left and right values. See function ST_Expand https://postgis.net/docs/ST_Expand.html
Updated my answer (according to the screenshots):
You can do the following steps to create your desired geometry in postgis.
drop table linetest;
--create table to test
create table linetest (
    id serial not null,
    geom geometry,
    parallel_geom geometry,
    union_lines geometry,
    polygon_geom geometry
);
--insert sample linestring
insert into linetest (geom) values (
    ST_GeomfromEWKT('SRID=4326; LINESTRING(100 100, 200 200)')
);
--create parallel linestring (query your field dx or dy for the parallel value here)
update linetest set parallel_geom = (
    select ST_OffsetCurve(geom,
    -15, -- here you can parametrize your offset
    'quad_segs=4 join=round')
);
--union the 2 lines to get one geometry as a multilinestring
update linetest set union_lines = (
    select ST_Union(geom, parallel_geom)
);
--create polygon with function convex hull out of the multilinestring
update linetest set polygon_geom = (
    select ST_ConvexHull(union_lines)
);
--check your result
select ST_ASTEXT (polygon_geom) from linetest;

I visualized the situation in qgis, see image:

A: Plan is the following:

*

*go to some coordinate space where scale on X and Y is similar (they're not in EPSG:4326);

*get offset geometry to one direction via ST_OffsetCurve;

*get offset geometry to another direction by passing negative offset to ST_OffsetCurve;

*concatenate two linear geometries using ST_MakeLine(geom1, geom2);

*convert resulting linear geometry to a polygon using ST_Polygonize.

Tricky parts are:

*

*sharp-angle geometries can disappear after offsetting to the direction of sharp angle;

*ST_MakeLine may fail if your offset line has complex self-intersecting shape;

*offsetting to the miles in degrees space. I'd recommend to ST_Transform your geometry to EPSG:3857, convert miles to meters and use function similar to ST_RealOffsetCurve from lostgis extension, scaling offser meters value by cos(lat) to account for earth curvature.

A: If I got your question correctly, you probably need the answer from here Creating a polygon around a linestring with PostGIS
. The key is ST_Buffer() function which wraps your stuff with a buffer radius. Not quite a rectangle though - it makes an oval around a straight line. This function accepts points, lines, multilines, polygons and multipolygons, and returns any of them wrapped with that buffer radius.


text:
Q: Is there a way to dynamically use already created variables within a for loop? I am new to R and I would like to create new variable names and use some others previously created within a for loop.
I found online the way to create the new variables in the loop but I cant make operations with other variables that were created before. I have tried with paste functions and creating the variable wihtin the for loop. Does anybody have an idea of how I could treat this already createdd variables within the loop?
This is how it could be done manually.
ACE1_dropc = umxModify(ACE1, update = "c_r1c1", name = "AE")

ACE2_dropc = umxModify(ACE2, update = "c_r1c1", name = "AE")

ACE3_dropc = umxModify(ACE3, update = "c_r1c1", name = "AE")

By using the next loop, the variables are created but they all call the same argument ACE1 in the function umxMofidy (ACE1 is an already created variable of class S4). I want to use different variables (ACE1, ACE2, ACE3) in each iteration but when I try with paste0("ACE",i) it doesnt work.
for(i in 1:3){
  assign(paste("ACE", i, "_dropc", sep = ""), umxModify(ACE1, update = "c_r1c1", name = "AE") )
}

A: You can retrieve a variable via its name using get(), although its usually best practice to use lists or other data structure. As an example
a1 = 1
z = get(paste0("a",1))
print(z)
1

In your loop, you would change the 1 for i -> get(paste0("ACE",i))

A: I'm not sure what is umxModify but I'd definitely move to a list. In the example below I am assigning random numbers to the list l and then calculate their absolute values. Note that all the elements of the list are named and can be accessed by l[[paste0("iteration", i)]].
l <- list()

for(i in 1:3){
  l[[paste0("iteration_", i)]] <- rnorm(1)
}

lapply(l, abs)


text:
Q: loop with requests.get and avoid timeout errors I am trying to get scrape information.
I goto the introduction page to determine the number of search results. Often, the results occur over >1 page, and as such, I need to refresh and run another requests in a loop. On a few occasions an error occurs in the extra requests, or it hangs.
I am curious if there is a way to check a request, if it fails, then try again, and if it still fails, log it and go to the next one
Here is a sample script:
t=.3
urls=['https://stackoverflow.com/','https://www.google.com/'] #list of upto 200 urls
for url in urls:
    print(url)
    response = requests.get(url, timeout=t)
    t=t+10
    i=i-1

running this returns a timeout occasionally, and the processing stops. My workaround is to print the url that failed, and then rerun, updating the list manually.

I would like to find a way that if a request error occurs, the response retries 5x, and if it fails, logs and stores the failed url, then goes onto the next one, so that I can try the failed urls at a later stage
Any suggestions?

A: I haven't used Python in a while, but I'm pretty sure that this will work.
t=.3
urls=['https://stackoverflow.com/','https://www.google.com/'] #list of upto 200 urls
for url in urls:
    print(url)
    try:
       response = requests.get(url, timeout=t)
    except:
        # if the request fails: try again
        try:
           response = requests.get(url, timeout=t)
        except:
            # if the request fails again: do nothing (continue to the next url)
            pass
     t=t+10
     i=i-1


text:
Q: How to keep focus on more than one window for input devices The idea is to do something like what a keystroke catcher does, but with multiple input devices. I want a window to record input from devices even if the focus is on another window. What libraries or methodologies would allow me to accomplish this?

A: This is typically handled via a low level Hook.  There is no C# library which will handle this directly, though there is a Microsoft KB article showing How to set a Windows hook in Visual C# .NET.


text:
Q: fsck single disk from Raid 0 lvm My NAS (Seagate Blackarmor) is refusing to connect to the network after a fsck. I assume the root filesystem (stored on flash) might have been corrupted somehow after running fsck.
The setup was a Raid 0 array with 2x2TB drives.
Edit: it might have actually been mdadm with linear span.
I have a USB<->SATA/IDE dock for accessing the disk drives on my laptop, but no way of connecting two drives at the same time.
The data stored on it is not critical but it reaches ~3TB and would like to still have it or at least compare it against another backup. I can also try soldering a TTL-UART converter on the board and work from there. NAS is based on Debian Lenny, I think.
Is there any way to check the integrity on each drive or remove the fsck flag without the other drive?
Are there any other ways to do this? Like image each one drive and use LVM on another system. Don't have enough space for this though. Or maybe buy another SATA-USB adapter.
Edit
This is how I did it, just one of the possibilities
The two 3.5" SATA drives were installed in a Win7 desktop machine and booted up an Ubuntu virtual machine inside Oracle VBox.
The (raw) drives needed to be set up prior to starting the VM:
VBoxManage internalcommands createrawvmdk -filename "FILENAME" -rawdisk "\.\PhysicalDrive#"
Linux recognized the RAID and LVM setup right away ('Disks' utility) and offered to mount them. The system partition had 1GB and the entire /etc folder was missing plus other several files from /bin and /sbin. After a chkdsk some files were recovered in lost+found.
In the mean time all the files on the NAS drives were synchronized with my other backup.
I then searched for a raw image of the machine (Seagate Blackarmor) and extracted the missing files from the downloaded *.tar.gz archive.
I haven't tested booting it yet but obviously some configuration will be missing: ip address, samba shares, mdadm.conf.


text:
Q: How to relate data in MongoDB? I am storing a string in a database along with the owners of the string (one or more owners per string).
I've always worked with MySQL which is a conventional relational database. In that case, I would store the string along with a unique id in one table, and then the unique id of the string along with the owners (as multiple records) in a second table.
I could then fetch strings by owners using a SQL Join.
I am now working on a project using MongoDB, and I'm doing the same as above.
Would this be considered the wrong way when working with NoSQL databases? Should I not be thinking in terms of 'relations' when working with NoSQL?
Another way I can think of achieving the same in MongoDB is storing it like this:
{
    "string": "foobar",
    "owners": [
        "owner1",
        "owner2",
        "owner3"
    ]
}

However, in this case, I'm unsure how I would search for "all strings owned by owner1".

A:
Would this be considered the wrong way when working with NoSQL databases? Should I not be thinking in terms of 'relations' when working with NoSQL?

There are so many questions on the case of embedding and it comes down to so little.
Somethings that have not been mentioned here that need to be considered if you wish to embed:

*

*Will the document size be increasing massively? If so then the document might frequently move on disk, this is a bad thing.

*Will the related row have a many join to the collection I am working on (i.e. video cannot embed user). If this is the case you might get problems when copying redundant data over from the related row into the subdocument, especially on updating that redundant data.

*How will I need to display these results?

Displaying the results is always a key decider in whether or not to embed. If you need to paginated a high number of rows, say 1000, you will need to use the $slice operator in either normal querying or the aggregation framework. At 1000 I admit it may be quite fast but sooner or later that in-memory operation will become slower than normal querying (infact it always should be).
If you require complex sorting and displaying of the subdocuments you might wanna split these out and instead have the document structure of:
{
    "string": "foobar",
    "owners": [
        ObjectId(),
        ObjectId(),
        ObjectId()
    ]
}

I think this may actually be a more performant structure anyway for your data since the owner sounds like a user row in a users collection.
Instead of populating the subdocuments with possibly changing data of the user you can just reference their _id. This is pretty kool since you can embed the relationship but at the same time the document will only grow very little which hopefully means a low chance of constant disk movement, not only that but a smaller working set creating a more performant operation overall. Not only that but of course the _id of a owner is rarely going to change so the only operations you will need to most likely throw at this subset of data is create and delete.
Getting back to complex sorting and pagination. With this data you can of course get all owner ids with a single round trip and then in another round trip you can query for those owners rows within the users table with normal querying using an $in allowing for the complex display you require.
So this structure overall, I have found, is very performant.
Of course this structure depends on your querying, it might be better to instead house the string id on the user but in this case it doesn't since a user presumably can own many strings as such I would say it is a many->many relationship embedded on the string side.
Hopefully this helps and I haven't gone round in circles,

A: To complement dbaseman's answer:
Yes, your approach seems ok. You can easily search for "all strings owned by owner1"
db.collection.find({owners: 'author1'})

This is possible because mongodb treats arrays in a special way.

A: When dealing with embedded data I'd recommend getting to familiar with the Atomicity behaviour in mongo.
A good starting point would be here :
http://docs.mongodb.org/manual/core/data-modeling/#atomicity
In your specific case when adding/removing a user ObjectId (as recommended by Sammaye) to your "owners" array, you're going to want to use a findAndModify() operation on the string doc to ensure that when many writes to that document occur, data integrity is still maintained.
Within this operation, I'd recommend using the following operators:

*

*When adding an owner, $addToSet to prevent duplicates

*When removing an owner, $pull

Both are documented here:
http://docs.mongodb.org/manual/reference/operators/#update-operators-array

A: This looks like the correct approach; remember though, it always depends on the totality of your project, what the goals are (performance, flexibility), what queries you intend to run most heavily, if you need to run ad-hoc queries, and other factors.  In general though, using nested documents, as you wrote, is the correct alternative to using joins and foreign keys.
Keep in mind also the maximum document size (currently 16MB), which would be a concern if there are many (like, hundreds of thousands) of owners of a given string.


text:
Q: Magento 2: Disable past dates for the Datepicker built via ui-component I am trying to add a validation to the datepicker so that users won't be able to select past dates. The datepicker is built via ui-component and the code snippet is as follows:

I have checked this link where in they have said to add the javascript in the template file but in our case we don't have any template file.
My case is similar to this post but not getting where to put the javascript.
Any help would be greatly appreciated. Thanks.

A:
You can set this field in your ui-component

<field name="date">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="dataType" xsi:type="string">string</item>
                <item name="label" xsi:type="string" translate="true">Date</item>
                <item name="formElement" xsi:type="string">date</item>
                <item name="source" xsi:type="string">page</item>
                <item name="sortOrder" xsi:type="number">1</item>
                <item name="dataScope" xsi:type="string">date</item>
                <item name="options" xsi:type="array">
                    <item name="dateFormat" xsi:type="string">yyyy-MM-dd</item>
                    <item name="minDate" xsi:type="string">new Date()+ 1</item>
                </item>
            </item>
        </argument>
</field>


text:
Q: Django access to product total price through order model I want to get each product's total price in all orders which I mean how much each product sold in all orders. What Query should I write in views.py to display this matter in html?
this is my models.py:
class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField(null=True)
    description = models.CharField(max_length=200, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.name

class Order(models.Model):
    STATUS = (
        ('Pending', 'Pending'),
        ('Shipping', 'Shipping'),
        ('Delivered', 'Delivered'),
    )
    # order will remain after customer deleted
    customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=200, null=True, choices=STATUS)
    note = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.product.name

and this is my views.py:
def home(request):
    products =  Product.objects.all()
    orders =  Order.objects.all()
    total_order_prices = Order.objects.aggregate(Sum('price'))

    orders.products = Product.objects.all().aggregate(Sum('price'))
    context = {'orders':orders, 'products':products,'total_order_prices': total_order_prices  }
    return render(request, 'account/home.html', context)

A: Morez!
What I recommend is defining a foreign key to Order() in the Product(). Doing so would allow you to get related objects much more easily, as shown here.
All you would have to do is products = order.product_set.
Hope it helps!


text:
Q: Migrate to Next JS using Next Auth for existing hashed and encrypted passwords in mongo DB using JWT and Crypto I already devlep an app using MERN Stack.
But I want to migrate the app to NEXT JS.
The problem is that I have a lot of active users that logs in with MAIL and PASSWORD. And I do not know how to migrate from the current process to NEXT AUTH without causing any problem to the active users on the log in process.
Right now the process I follow to authenticate users is:

*

*I got a signout route where I extract the data from the user
 exports.signup = (req, res) => {
 //Obtain data from body
 const { name, email, password } =
     req.body;

 //Validate if mail exists
 User.findOne({ email }).exec(async (err, user) => {
     if (user) {
         //Send errror message if exists
         return res.status(400).json({
             error: "Correo electronico ya registrado!",
         });
     }

     //Gen token with JWT
     const token = jwt.sign(
         { name, email, password, colNum, specialty, cellPhone, gender, currency },
         process.env.JWT_ACCOUNT_ACTIVATION,
         { expiresIn: "59m" },
     );

     //Email Template
     //Send email to verify mail and activate account, the email contains the token in the clicleable URL
     const { subject, body, message } = mailRegister(token, email);

     //AWS Email Sender
     const responseEmailAWS = await emailSenderAWS(body, subject, email, message);

     return res.json({
         message: responseEmailAWS,
     });
 });

};
From here the user receives an email in the INBOX from the app with a clickeable link
When the user clics the URL calls an api to "Activate"the account.
exports.accountActivation = (req, res) => {
    //get the token from the req
    const { token } = req.body;

    if (token) {
        jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION, function (err, decoded) {
            if (err) {
                console.log("ERROR MSG --> JWT VERIFY IN ACCOUNT ACTIVATION ERROR", err);
                return res.status(401).json({
                    error: "Link EXPIRADO. Ingrese de nuevo",
                });
            }

            const { name, email, password } =
                jwt.decode(token);

            const user = User({
                name,
                email,
                password,
            });

            user.save((err, user) => {
                if (err) {
                    console.log("ERROR MSG --> SAVE USER IN ACCOUNT ACTIVATION ERROR", err);
                    return res.status(401).json({
                        error: "Error guardando el usuario en la base de datos. Intente de nuevo por favor!",
                    });
                }

                return res.json({
                    message: "Registro EXITOSO! por favor ingrese a su cuenta en INGRESAR!",
                });
            });
        });
    } else {
        return res.json({
            message: "Algo ocurrio!... intente de nuevo por favor!",
        });
    }
};

Now the Model of Mongo DB has some trick code to never know the password the user uses in DB
This is the model:
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const crypto = require('crypto');

const userSchema = new mongoose.Schema(
    {
        //Basic Data
        name: {
            type: String,
            trim: true,
            required: true,
            maxlength: 32,
        },
        email: {
            type: String,
            trim: true,
            required: true,
            unique: true,
        },
        hashed_password: {
            type: String,
            required: true,
        },
        salt: {
            type: String,
        },
        resetPasswordLink: {
            type: String,
            default: '',
        },

    },
    { timestamps: true }
);

// virtual field
userSchema
    .virtual('password')
    .set(function (password) {
        // create a temporarity variable called _password
        this._password = password;
        // generate salt
        this.salt = this.makeSalt();
        // encryptPassword
        this.hashed_password = this.encryptPassword(password);
    })
    .get(function () {
        return this._password;
    });

//  Methods
userSchema.methods = {
    // Method Authenticate User
    authenticate: function (plainText) {
        return this.encryptPassword(plainText) === this.hashed_password; //  Ture or False
    },
    // Method Encrypt Pass
    encryptPassword: function (password) {
        if (!password) return '';
        try {
            return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
        } catch (err) {
            return '';
        }
    },

    // Method Make Salt
    makeSalt: function () {
        return Math.round(new Date().valueOf() * Math.random()) + '';
    },
};

module.exports = mongoose.model('User', userSchema);

What makes the code above is give some functions to encrypt passwords using Crypto and make some functions to make more secure the "Forgot" password.
Somebody can help me, to migrate from MERN to NEXT JS???
I dont know if I can implament the same logic of authentication in NEXT JS or using NEXT Auth or if there are a better choice?
The objective is make "Transparent" the migration for the active users that already have a mail and password (Encrypted) saved on the DB.


text:
Q: Is there a "Hello, World" GNU-like sample project for libraries? GNU Hello is GNU's example project for best practices, coding standards, internationalization, configuration automation, etc.
Is there a similar project that targets libraries? I realize GNU Hello can be used in that way, but would I be missing some library-specific practices?
I've also searched for good tutorials on this topic, and the Program Library HOWTO seems to be the most appropriate one out there. Do you have any other suggestions?

A: There is a project called libabc: shared library skeleton created by Lennart Poettering:

To make things easy we have put together an example skeleton library we dubbed libabc, whose README file includes all our points in terse form.

http://0pointer.de/blog/projects/libabc.html

A: The following are some guidelines that I regularly bring up. I'm not entirely sure how helpful they'll be:
http://en.wikipedia.org/wiki/Indent_style
http://www.python.org/dev/peps/pep-0007/
Otherwise, I just try to match what I see. Looking at the above style guides should give you a good indication of what consistencies to look for and attempt to match in your code.
Edit:
I should clarify, the above guides are not specific to GNU, but might help you find consistencies such as naming schemes or tab/spacing guides.

A: I read through the GNU manual and found a short example that I think would get you to a good start:
Straight from the manual:
/* hello.c -- print a greeting message and exit.

    Copyright (C) 1992, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
    2005, 2006, 2007 Free Software Foundation, Inc.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3, or (at your option)
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */

 #include <config.h>
 #include "system.h"

 /* String containing name the program is called with.  */
 const char *program_name;

 static const struct option longopts[] =
 {
   { "greeting", required_argument, NULL, 'g' },
   { "help", no_argument, NULL, 'h' },
   { "next-generation", no_argument, NULL, 'n' },
   { "traditional", no_argument, NULL, 't' },
   { "version", no_argument, NULL, 'v' },
   { NULL, 0, NULL, 0 }
 };

 static void print_help (void);
 static void print_version (void);

 int
 main (int argc, char *argv[])
 {
   int optc;
   int t = 0, n = 0, lose = 0;
   const char *greeting = NULL;

   program_name = argv[0];

   /* Set locale via LC_ALL.  */
   setlocale (LC_ALL, "");

 #if ENABLE_NLS
   /* Set the text message domain.  */
   bindtextdomain (PACKAGE, LOCALEDIR);
   textdomain (PACKAGE);
 #endif

   /* Even exiting has subtleties.  The /dev/full device on GNU/Linux
      can be used for testing whether writes are checked properly.  For
      instance, hello >/dev/full should exit unsuccessfully.  On exit,
      if any writes failed, change the exit status.  This is
      implemented in the Gnulib module "closeout".  */
   atexit (close_stdout);

   while ((optc = getopt_long (argc, argv, "g:hntv", longopts, NULL)) != -1)
     switch (optc)
       {
       /* One goal here is having --help and --version exit immediately,
          per GNU coding standards.  */
       case 'v':
         print_version ();
         exit (EXIT_SUCCESS);
         break;
       case 'g':
         greeting = optarg;
         break;
       case 'h':
         print_help ();
         exit (EXIT_SUCCESS);
         break;
       case 'n':
         n = 1;
         break;
       case 't':
         t = 1;
         break;
       default:
         lose = 1;
         break;
       }

   if (lose || optind < argc)
     {
       /* Print error message and exit.  */
       if (optind < argc)
         fprintf (stderr, _("%s: extra operand: %s\n"),
         program_name, argv[optind]);
       fprintf (stderr, _("Try `%s --help' for more information.\n"),
                program_name);
       exit (EXIT_FAILURE);
     }

   /* Print greeting message and exit. */
   if (t)
     printf (_("hello, world\n"));

   else if (n)
     /* TRANSLATORS: Use box drawing characters or other fancy stuff
        if your encoding (e.g., UTF-8) allows it.  If done so add the
        following note, please:

        [Note: For best viewing results use a UTF-8 locale, please.]
     */
    printf (_("\
 +---------------+\n\
 | Hello, world! |\n\
 +---------------+\n\
 "));

   else
     {
       if (!greeting)
         greeting = _("Hello, world!");
       puts (greeting);
     }

   exit (EXIT_SUCCESS);
 }

 /* Print help info.  This long message is split into
    several pieces to help translators be able to align different
    blocks and identify the various pieces.  */

 static void
 print_help (void)
 {
   /* TRANSLATORS: --help output 1 (synopsis)
      no-wrap */
         printf (_("\
 Usage: %s [OPTION]...\n"), program_name);

   /* TRANSLATORS: --help output 2 (brief description)
      no-wrap */
   fputs (_("\
 Print a friendly, customizable greeting.\n"), stdout);

   puts ("");
   /* TRANSLATORS: --help output 3: options 1/2
      no-wrap */
   fputs (_("\
   -h, --help          display this help and exit\n\
   -v, --version       display version information and exit\n"), stdout);

   puts ("");
   /* TRANSLATORS: --help output 4: options 2/2
      no-wrap */
   fputs (_("\
   -t, --traditional       use traditional greeting format\n\
   -n, --next-generation   use next-generation greeting format\n\
   -g, --greeting=TEXT     use TEXT as the greeting message\n"), stdout);

   printf ("\n");
   /* TRANSLATORS: --help output 5 (end)
      TRANSLATORS: the placeholder indicates the bug-reporting address
      for this application.  Please add _another line_ with the
      address for translation bugs.
      no-wrap */
   printf (_("\
 Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
 }

 /* Print version and copyright information.  */

 static void
 print_version (void)
 {
   printf ("hello (GNU %s) %s\n", PACKAGE, VERSION);
   /* xgettext: no-wrap */
   puts ("");

   /* It is important to separate the year from the rest of the message,
      as done here, to avoid having to retranslate the message when a new
      year comes around.  */
   printf (_("\
 Copyright (C) %s Free Software Foundation, Inc.\n\
 License GPLv3+: GNU GPL version 3 or later\
 <http://gnu.org/licenses/gpl.html>\n\
 This is free software: you are free to change and redistribute it.\n\
 There is NO WARRANTY, to the extent permitted by law.\n"),
               "2007");
 }


text:
Q: Create UTF8 String from UTF Codes in Javascript I have the byte representation of UTF8, e.g.
195, 156 for "Ü" (capital U Umlaut)

I need to create a string for display in JavaScript out of these numbers - everything I tried failed.
No methode I found recognizes "195" as a UTF leading byte but gave mit "Ã".
So how do I get a string to display from my stream of UTF8 bytes?

A: You're working with decimal representations of the single byte components of the characters. For the example given, you have 195, 156. First, you have to converting to base 16's C3, 9C. From there you can use javascript's decodeURIComponent function.
console.log(decodeURIComponent(`%${(195).toString(16)}%${(156).toString(16)}`));

If you're doing this with a lot of characters, you probably want to find a library that implements string encoding / decoding. For example, node's Buffer objects do this internally.


text:
Q: Lagrange multiplier method on Banach spaces (in Dirac notation) I want to prove Cauchy–Schwarz' inequality, in Dirac notation, $\left<\psi\middle|\psi\right> \left<\phi\middle|\phi\right> \geq \left|\left<\psi\middle|\phi\right>\right|^2$, using the Lagrange multiplier method, minimizing $\left|\left<\psi\middle|\phi\right>\right|^2$ subject to the constraint $\left<\phi\middle|\phi\right> - c = 0$, where $c$ is a constant.
I'm completely new to Lagrange multipliers, and the Fréchet derivative etc., and have tried to consult https://en.wikipedia.org/wiki/Lagrange_multipliers_on_Banach_spaces, but am still quite confused, conceptually.
This is my sketchy thinking thus far (trying to follow the Wikipedia exposition, adapted to my problem):
We have a Banach space $B_\phi$. We then have $f = \left|\left<\psi\middle|\phi\right>\right|^2 : B_\phi \to \mathbf C$, which we want to minimize. The constraint is given by $g = \left<\phi\middle|\phi\right> - c : B_\phi \to \mathbf C$, which is set to zero. The Wikipedia article goes on to suppose that "$u_0$" (would "$ \left|\phi_0\right>$" be a logical label in my case?) is a constrained extremum of $f$, i.e. an extremum of $f$ on $g^{-1}(0) = \big\{\left|\phi\right> \in B_\phi$ $|$ $g(\left|\phi\right>) = 0 \in \mathbf C \big\} \subseteq B_\phi$. The problem is then formulated as $$Df(u_0) = \lambda \circ Dg(u_0)$$ where $\lambda$ is the Lagrange multiplier, and D the Fréchet derivative. Is it a complete misconception if I write this as (given $f$ and $g$ above, and my assumption that $u_0 = \left|\phi_0\right>$) $$D \left|\left<\psi|\phi_0\right>\right|^2 = \lambda \circ D\big(\left<\phi_0|\phi_0\right> -c\big)$$?
My main questions at the moment are:

*

*What are the conceptual errors above? (I guess there are plenty)

*How do I evaluate the Fréchet derivative, e.g. $D \left|\left<\psi|\phi_0\right>\right|^2$?

Thanks in advance!


text:
Q: Replicating Simulation Study of Gary King in R In this article, the authors describes the following simulation study of Propensity Score Matching,

For each of two covariates, we randomly and independently draw 100 control units from a Uniform(0,5) and 100 treated units from Uniform(2,6). This leaves the overlapping [1, 5] x [1, 5] square as a completely randomized experiment and observations falling outside adding imbalance. We generate the outcome as $Y = 2T_i + X_{i1} + X_{i2} + \varepsilon$, where $\varepsilon \sim N(0,1)$

However, there is no clear description of how T is defined here. $X_{i,k} ~ \forall ~k$ is, as far as the paper goes, a vector of length 100, while T is also a (naturally) vector.

My first interpretation of this, was of the following,
# First Attempt

dgp <- function(n = 100)
{

  # Generate Covariates
  x1 <- runif(n, min = 0, max = 5)
  x2 <- runif(n, min = 1, max = 6)

  # Generate data with treatment indicators
  # and outcomes

  tibble(
    x1 = x1,
    x2 = x2
  ) %>% mutate(
    treatment = as.numeric(x1 >1 | x2 > 1),
    y         = 2*treatment + x1 + x2 + rnorm(n, 0, 1)
  )
}

However, this attempt assigns some of the obs in the untreated runif(n, 0,5) to the treatment group, which is not what the authors intends.
My second attempt, includes cbind(x1 = runif(100, 0,5), treatment = 0) for each covariate - however, then the length of the treatment-variable exceeds that of the covariates, and therefore breaks down.
How do I interpret the simulation study mentioned in the paper, and replicate it in R?
Edit: Quoted exactly from the article after @whuber's comment.

A: I attempted to replicate this study two ways using the data-generating process described in the text and what I hoped to demonstrate was an equivalent data-generating process. My replication is here.
Here is a snippet of the code I used to generate the data, where A is the treatment:
n <- 200
A <- rep(0:1, each = n/2)
X1 <- ifelse(A==1, runif(n, 1, 6), runif(n, 0, 5))
X2 <- ifelse(A==1, runif(n, 1, 6), runif(n, 0, 5))

Y <- 2*A + X1 + X2 + rnorm(n)

Note that in the paper, they generate the treatment groups first, and then assign covariate values to the assigned units. That is, treatment doesn't depend on the covariates. Instead, the treatment is randomized and the covariates are actually mediators.
A colleague thought this undermined their entire paper, and I disagreed, which is why I set out to formulate an equivalent data-generating process where the treatment was created based on the covariates but the treatment and covariates had the same joint distribution as in the original formulation. Here is code to do that:
G1 = sample(LETTERS[1:5], n, replace = TRUE,
            prob = c(5/50, 4/50, 32/50, 4/50, 5/50))
X1 = runif(n,
           sapply(G1, switch, A = 1, B = 0, C = 1, D = 5, E = 0),
           sapply(G1, switch, A = 6, B = 1, C = 5, D = 6, E = 5))
X2 = runif(n,
           sapply(G1, switch, A = 5, B = 1, C = 1, D = 1, E = 0),
           sapply(G1, switch, A = 6, B = 5, C = 5, D = 5, E = 1))

#P is propensity score.
P = 1*(X1 > 1)*(X2 > 1) - .5*(X1 > 1)*(X1 < 5)*(X2 > 1)*(X2 < 5)

A <- rep(0, n)
A[P == 1] <- 1
A[P == .5] <- sample(c(rep(1, n/2 - sum(P==1)),
                       rep(0, n/2 - sum(P==0))),
                     sum(P == .5), replace = FALSE)

Basically, you create an exogenous auxiliary grouping variable G1, then generate X1 and X2 based on G1. The propensity score is defined in an unusual way; values can be either 0, .5, or 1. Normally, treatment would be generated using rbinom() for those with propensity scores other than 0 or 1, but to ensure the number of treated and control units is equal, we use sample() instead. This ensures both the propensity score is accurate and the group sizes are balanced. Those with a propensity score of .5 correspond to the "completely randomized experiment" and those with a propensity score of 0 or 1 correspond to those "adding imbalance".
You can verify that the joint distributions of the variables are the same regardless of the method, indicating that the messages of the paper apply regardless of which data-generating process is used as long as the joint distribution of the variables is the same. This is because the paper makes a statistical argument, not a causal one, and the statistics are agnostic to the causal assumptions one would typically invoke (i.e., about whether the treatment causes the covariates or the covariates cause the treatment).
This has to do with the statistical estimand, which for matching is $E[E[Y|X,A=1]] - E[E[Y|X,A=0]]$. Whether this corresponds to a causal estimand is another question. Under a confounding data-generating process (the second one I describe), the causal estimand is the de-confounded average treatment effect $E[Y^1] - E[Y^0]$. Under the mediation data-generating process (the one in the paper), the causal estimand is the direct effect of treatment not through the covariates. The authors don't clarify this because it is tangential to their argument, but for those investigating deeply, it is worth knowing what is actually going on.


text:
Q: Multiple data types within one vector of pointers using templates I have two classes seen below,
template <typename T> class node   {
public:
    int NodeID;//ID used to identify node when inserting/deleting/searching
    T data;//generic data encapsulated in each node.
    std::vector<node*> children;//child nodes, list of ptrs
    std::vector<node*> parents;//parent nodes list of ptrs
};

template<typename T> class DAG {//Class for the graph

    std::vector<node<T>*> Nodes;//Vector of node ptrs, this is how we define a DAG;
}

I was wondering whether its possible using templates to have the vector of nodes contain nodes of multiple types? Something like this.
std::vector<node*> Nodes = {node<int>*,node<string>*, ...}

A: I suggest that you use polymorphism and create a non-template base class:
struct nodebase {
    nodebase(int id) : NodeID{id} {}
    virtual ~nodebase() = default; // to be able to delete via base class pointer

    virtual void print(std::ostream& os) const {
        os << NodeID;
    }

    int NodeID;  // ID used to identify node when inserting/deleting/searching

    std::vector<std::unique_ptr<nodebase>> children; // child nodes, list of ptrs
    std::vector<nodebase*> parents;  // parent nodes list of ptrs
};

// to be able to print all nodes, calls the overridden `print` method:
std::ostream& operator<<(std::ostream& os, const nodebase& nb) {
    nb.print(os);
    return os;
}

With that base class, your node<T> could look like this:
template <typename T>
class node : public nodebase {
public:
    // constructor taking `id` + the arguments needed for `T`:
    template<class... Args>
    node(int id, Args&&... args) : nodebase{id}, data{std::forward<Args>(args)...} {}

    void print(std::ostream& os) const override {
        nodebase::print(os);
        os << ',' << data;
    }

    T data;  // generic data encapsulated in each node.
};

And you could use it like so:
int main() {
    std::vector<std::unique_ptr<nodebase>> Nodes;

    Nodes.emplace_back(std::make_unique<node<int>>(1, 12356));
    Nodes.emplace_back(std::make_unique<node<std::string>>(2, "Hello world"));

    for(auto& ptr : Nodes) {
        std::cout << *ptr << '\n';
    }
}

Output:
1,12356
2,Hello world


text:
Q: ggplot2 insert geom H-Line in specific Facets I am trying to show the limestone treatment amount of Ca on treatment sites (2,000 kg/ha) and I would like to remove the line from the Untreated site facet.
The code I have been using is:
soillimebudget %>%
  mutate(`Stand Age` = factor(`Stand Age`, levels = c("NL", "14", "19", "23", "28", "32", "33", "37"))) %>%
  mutate(`Treatment` = factor(`Treatment`, levels = c("Pre-Treatment Conditions", "Limestone, Stable", "Limestone, Eroded"))) %>%  mutate(Treatment = recode(Treatment, "Pre-Treatment Conditions" = "Untreated")) %>%
  mutate(Pool = factor(Pool, levels = c("ABG", "LFH", "Mineral Soil"))) %>%
  mutate(Pool = recode(Pool, "ABG" = "AGB")) %>%
 group_by(Treatment, `Stand Age`, Pool) %>%
  ggplot(aes(x = Mg, y = `Stand Age`, fill = `Pool`, position = "stack")) +
  labs(title = "Mg Budget") +
  labs(x = "Stand Age", y = "Mg (kg/ha)") +
  geom_bar(aes(`Stand Age`, `Mg`, fill = Pool),
           position = "stack", stat = "identity") +
#scale_fill_grey(start = 0.3, end = 0.7) +
  theme_bw() +
geom_hline(linetype = "dashed", yintercept = 1000) +
  theme(legend.position =  "top") +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.border = element_rect(colour = "Black", fill = NA)) +
  theme(text = element_text(size = 30)) +
  facet_grid(~`Treatment`, scales = "free_x", space = "free_x")

Currently my figure is how I would like, barring removing the one H line from the Facet.
Thanks

A: Layers are facetted by the facetting variable in the data. To make geom_hline() appear in a subset of the facets, you'd need two things:

*

*(dummy) data that includes the facetting variables you need.

*A mapping created with aes(), otherwise the data -and thus facetting variables- are ignored.

Example with a standard dataset below:
library(ggplot2)

ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_hline(
    data = data.frame(Species = c("setosa", "virginica"), y = 6),
    aes(yintercept = y)
  ) +
  geom_point() +
  facet_grid(~ Species)

Created on 2021-06-22 by the reprex package (v1.0.0)


text:
Q: capybara check input type (fill_in vs check vs select) I've got method that fills forms for me with capybara.
After getting some default params from FactoryGirl i'm looping tis way:
form_attributes.each do |field, value|
    if value == false
      value == true ? check("#{model}_#{field}") : uncheck("#{model}_#{field}")
    elsif try(:select,value, from: "#{model}_#{field}")
      select value, from: "#{model}_#{field}"
    elsif try(:fill_in, "#{model}_#{field}", with: value)
      fill_in "#{model}_#{field}", with: value
    else
      raise Capybara::ElementNotFound
    end
end

Unfortunately try(:select,value, from: "#{model}_#{field}") will raise error Capybara::ElementNotFound: Unable to find select box ...
How to tell capybara to  check when element is checkbot and select when element is <select>?
Here is some sample of form_attributes:
{:attitude=>"happy",
 :feedback_date=>2014-08-19 15:35:14 +0200,
 :feedback_action=>"Refund",
 :feedback_details=>"....",
 :approved=>"true"}

A: Assuming that #{model}_#{field} is always the same property (ie id, name or label), you could:

*

*Find the element

*Inspect the element to determine its type

*Call the appropriate method to input the field

The following codes assumes that #{model}_#{field} is the id of an element:
form_attributes.each do |field, value|
  e = find("##{model}_#{field}")
  if e.tag_name == 'select'
    e.select(value)
  elsif e.tag_name == 'input' && e['type'] == 'checkbox'
    # Assumes that value is true or false (not a String)
    e.set(value)
  else
    # Assumes e is a text field
    e.set(value)
  end
end

In this code, we check the element's tag_name and type attribute if required. As there are many ways that an input tag could be a text field, it is assumed that anything that is not a select list or checkbox must be a text field. You would need to expand the if-else statement if you also want to handle radio buttons, etc.

A: I would suggest that you use the has_selector? method in the elsif. It returns a boolean indicating whether or not it's visible within the page. Here's a link the documentation to the page.
TL;DR:
page.has_selector?('p#foo')
page.has_selector?('li', :text => 'Horse', :visible => true)


text:
Q: What's the way you transfer data object from client to server for persisting datas using GWT? If you use JPA or another kind of persistence, you probably have a way to save a record that is sent to client via ajax.
EDIT : the interface is done with GWT, so all ajax call are classic java method (converted to javascript equivalent)
Let's take the class Person which is an entity in database.
Person has four fields : name, birthday, id, email
When you load a person from server via ajax, you generally send to client a Person object.
In your Person editor, you display the name, the birthday and the email. When the Person object is edited you may want to display the id.
There are two cases :

*

*save person : only email can be changed but you can display id

*create person : email, name and birthday can be changed

When you send the just edited datas to server, what's the way you proceed ?
I see several approaches :

*

*send a Person object. In this case you must take care of data you persist and not only make the person object you received from client to persist mode because a hacker can send data you may not want to be changed (and you can't trust on interface to disabled these changes). In this case, there is several approaches too :

*

*use two functions (save and create), create a new Person object on server (or load the persisted instance via the id if you are in the save method) and copy all fields you want from the client Person object to the persisted one

*use one function (saveOrCreate) and check if id exists. It is equivalent to the above approach by merging the two functions in one with a big "if"

*send datas to the server (email, birthday, name, id (in case of edit)). When you do that, create a new Person object (or load the persisted one) and copy datas to this persisted instance.

To summary you have one of the following method signature (just for edit case):

*

*Person savePerson(Person person);

*Person savePerson(String id, String email);
I see pros and cons for each approach. For example the first allow quick change on the Person model without modifying all savePerson calls. But it is less readable than the second approach to know what is really saved.
I don't know what is the best one and if you know another way to do that. So, how do you do ?

A: It is always nice to use domain objects for data transfer. In GWT you have to define your interfaces and mark your Rpc BeanProxies. As part of the project evolution, you find a need to add additional fields to an object. If you go with interfaces that use data attributes rather than objects, you will be constantly changing them and the method signature becomes clumsy and unreadable.
However, certain people ask for a separation of persistance domain entities from business domain. In such cases, property copying (apache commons-bean utils) can be used.


text:
Q: Yii2 execution time (total time for serving the current request) What is the equivalent of method
Yii::getLogger()->getExecutionTime()

in Yii2, that present the total time for serving the current request?

A: You should simply use :
Yii::getLogger()->getElapsedTime();

Read more : http://www.yiiframework.com/doc-2.0/yii-log-logger.html#getElapsedTime()-detail


text:
Q: Some properties of the content of a polynomial

*

*Let $F \in \mathbb{Q}[x]$. Then exists $a,b \in \mathbb{Z}$, with
$gcd(a,b)=1$, and a primitive polynomial $f \in \mathbb{Z}[x]$ that $F
= \dfrac{a}{b}f$,

*Let $f,g \in \mathbb{Z}[x]$. Show using Gauss's lemma that:
$$cont(fg)=cont(f)cont(g)$$

My idea for 1 was took $a=gcd(a_0,...a_n)$ and $b=lcm(b_0,...,b_n)$, then picking $f = \dfrac{b}{a}F$, but I'm not sure of it.
For 2, I though doing $f = cont(f).f^*$ and $g=cont(g).g^*$, with $f^*$ and $g^*$ being primitive polynomials. Then we would have $f^*g^*$ primitive by Gauss's lemma, and then:
$$cont(fg) = cont(cont(f)cont(g)f^*g^*) = cont(f)cont(g)cont(f^*g^*) = cont(f)cont(g).$$
because by definition $cont(f^*g^*)=1$.
OBS: $cont(f)$ is the content of the polynomial $f$.


text:
Q: Best practice around GraphQL nesting depth
*

*Is there an optimum maximum depth to nesting?

We are often presented with the option to try to represent complex heirarchical data models with the nesting they demonstrate in real life. In my work this is genetics and modelling protein / transcript / homology relationships where it is possible to have very deep nesting up to maybe 7/8 levels. We use dataloader to make nested batching more efficient and resolver level caching with directives. Is it good practice to model a schema on a real life data model or should you focus on making your resolvers reasonable to query and keep nesting to a maximum ideal depth of say 4 levels?

*When designing a schema is it better to create a different parent resolver for a type or use arguments that to direct a conditional response?

If I have two sets of for example 'cars' let's say I have cars produced by Volvo and cars produced by tesla and the underlying data while having similarities is originally pulled from different apis with different characteristics. Is it best practice to have a tesla_cars and volvo_cars resolver or one cars resolver which uses for example a manufacturer argument to act differently on the data it returns and homogenise the response especially where there may then be a sub resolver that expects certain fields which may not be similar in the original data.
Or is it better to say that these two things are both cars but the shape of the data we have for them is significantly different so its better to create seperate resolvers with totally or notably different fields?

*Should my resolvers and graphQL apis try to model the data they describe or should I allow duplication in order to create efficient application focused queries and responses?

We often find ourselves wondering do we have a seperate API for application x and y that maybe use underlying data and possibly even multiple sources (different databases or even API calls) inside resolvers very differently or should we try to make a resolver work with any application even if that means using type like arguments to allow custom filtering and conditional behaviour?

A: *

*Is there an optimum maximum depth to nesting?

In general I'd say: don't restrict your schema. Your resolvers / data fetchers will only get called when the client requests the corresponding fields.
Look at it from this point of view: If your client needs the data from 8 levels of the hierarchy to work, then he will ask for it no matter what. With a restricted schema the client will execute multiple requests. With an unrestricted schema he can get all he needs in a single request. Though the amount processing on your server side and amount of data will still be the same, just split across multiple network requests.
The unrestricted schema has several benefits:

*

*The client can decide if he wants all the data at once or use multiple requests

*The server may be able to optimize the data fetching process (i.e. don't fetch duplicate data) when he knows everything the client wants to receive

The restricted schema on the other hand has only downsides.

*When designing a schema is it better to create a different parent resolver for a type or use arguments that to direct a conditional response

That's a matter of taste and what you want to achieve. But if you expect your application to grow and incorporate more car manufacturers, your API may become messy, if there are lot's of abc_cars and xyz_cars queries.
Another thing to keep in mind: Even if the shape of data is different, all cars have something in common: They are some kind of type Car. And all of them have for example a construction year. If you now want to be able to query "all cars sorted by construction year" you will need a single query endpoint.
You can have a single cars query endpoint in your api an then use interfaces to query different kinds of cars. Just like GraphQL Relay's node endpoint works: Single endpoint that can query all types that implement the Node interface.
On the other hand, if you've got a very specialized application, where your type is not extensible (like for example white and black chess pieces), then I think it's totally valid to have a white_pieces and black_pieces endpoint in your API.
Another thing to keep in mind: With a single endpoint some queries become extremely hard (or even impossible), like "sort white_pieces by value ascending, and black_pieces by value descending". This is much easier if there are separate endpoints for each color.
But even this is solvable if you have a single endpoint for all pieces, and simply call it twice.

*Should my resolvers and graphQL apis try to model the data they describe or should I allow duplication in order to create efficient application focused queries and responses?

That's question of use case and scalability. If you have exactly two types of clients that use the API in different ways, just build two seperate APIs. But if you expect your application to grow, get more different clients, then of course it will become an unmaintainable mess to have 20 APIs.
In this case have a look at schema directives. You can for example decorate your types and fields to make them behave differently for each client or even show/hide parts of your API depending on the client.

Summary:

*

*Build your API with your clients in mind.

*Keep things object oriented, make use of interfaces for similar types.

*Don't provide endpoints you clients don't need, you can still extend your schema later if necessary.

*Think of your data a huge graph ;) that's what GraphQL is all about.


text:
Q: nginx-ingress-controller forever on "Scheduled for sync" I have an ingress for my application:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapi-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
  ingressClassName: nginx
  rules:
  - host: mysite.com
    http:
      paths:
      - path: "/posts"
        pathType: Prefix
        backend:
          service:
            name: myservice
            port:
              number: 80

When I run kubectl describe ing myapi-ingress, I can see that the ingress is stuck in sync state:
Events:
  Type    Reason  Age                From                      Message
  ----    ------  ----               ----                      -------
  Normal  Sync    26m (x2 over 27m)  nginx-ingress-controller  Scheduled for sync

PS. Before this happens, I tried to install another ingress for internal usage under another namespace and ingressclassname.
I'm getting 404 when I try to hit this endpoint. Nothing in the logs.
What is the problem?

A: The problem was the host name set on the Ingress