text:
Q: In Ionic2 Leaflet marker is not accept Draggable feature? In this code {draggable:'true'}feature is not accepted and makes error:
import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';

import * as Leaflet from 'leaflet';

@Component({
  selector: 'page-street',
  templateUrl: 'street.html'
})
export class StreetPage {
 private latLng: any;
  private marker: any;
  private map: any;
  constructor(public navCtrl: NavController) {

  }
  ngOnInit(): void {
    this.drawMap();
  }
  drawMap(): void {
    let map = Leaflet.map('map');
    Leaflet.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      maxZoom: 15
    }).addTo(map);

    map.locate({ setView: true});
    function onLocationFound(e) {
      var radius = e.accuracy / 3;
      Leaflet.marker(e.latlng, {draggable:'true'}).addTo(map);
      Leaflet.circle(e.latlng, radius).addTo(map);
    }
    map.on('locationfound', onLocationFound);
    //alert on location error
    function onLocationError(e) {
      alert(e.message);
    }
    map.on('locationerror', onLocationError);
  }
}

any Idea to solve it?
Update:
error for {draggable:'true'} :

Typescript Error
   Argument of type '{ draggable: string; }' is not
  assignable to parameter of type 'MarkerOptions'. Types of property
  'draggable' are incompatible. Type 'string' is not assignable to type
  'boolean

error for {draggable: true} :

Typescript Error Argument of type '{ draggable: true; }' is not assignable to parameter of type 'MarkerOptions'. Property 'options' is
  missing in type '{ draggable: true

A: first use
{draggable:true}

here, true is a boolean instead of your 'true' which is a string.
TypeScript sees your code as an object with a string property which can not be assigned to a variable which is an object with a boolean property named 'draggable'
The type that is expected also needs an 'options' property. you should be able to figure out what you should put in options by looking at the definition of MarkerOptions.
You have probably downloaded some Typings (.d.ts) for 'leaflet' that is putting some definition for MarkerOptions that is too limiting.
let's say you have used this to get this typings

npm install @types/leaflet

Option1: Find the declarations made for MarkerOptions and either change it to fit your purpose or change your parameters to match that definition.
Option2: Find the declaration for the 'marker' function in the declaration file you have downloaded and change the second parameter's type from 'MarkerOption' to 'any'
eventually your index.d.ts should look like this
   export interface MarkerOptions extends InteractiveLayerOptions {
        icon?: Icon;
        clickable?: boolean;
        draggable?: boolean;
        keyboard?: boolean;
        title?: string;
        alt?: string;
        zIndexOffset?: number;
        opacity?: number;
        riseOnHover?: boolean;
        riseOffset?: number;

        options?: DivIconOptions;
    }

    export class Marker extends Layer {
        constructor(latlng: LatLngExpression, options?: MarkerOptions);
        getLatLng(): LatLng;
        setLatLng(latlng: LatLngExpression): this;
        setZIndexOffset(offset: number): this;
        setIcon(icon: Icon): this;
        setOpacity(opacity: number): this;
        getElement(): HTMLElement;

        // Properties
        options: MarkerOptions;
        dragging: Handler;
    }


text:
Q: How to add to a nested collection in oData If I had a collection /Events(123)/Registrants, and I wanted to add a Person to that collection, how would I do something like that.
I tried POSTing a Person to that url, but I get an error.

A: Stupid me for not reading the oData specification.
POST /OData/OData.svc/Events(123)/$links/Registrants HTTP/1.1
Host: services.odata.org
DataServiceVersion: 1.0
MaxDataServiceVersion: 2.0
Content-Length: 159
Content-Type: application/xml
<uri xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
http://services.odata.org/OData/OData.svc/Person(10)
</uri>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing Serial Ports with an Application Runs in Flatpak I recently updated my IDE to Monodevelop 6 using Flatpak, on Ubuntu 16.04 LTS, from an older version 5.
I have an application that interacts with serial ports which is basically a USB/RS232 adapter connecting a device to my computer.
I have no issue accessing USB port (/dev/ttyUSB0) when I debug the application in Monodevelop5. However, the device directory (/dev/) that I have access to, using Monodevelop6 is completely different than the one I have access to in Linux, and there is no ttyUSB0 in that folder.
I believe this is because Flatpak runs the application in sandbox. So, if that is the reason, how can I access to a serial port then?
Thanks.

A: Most likely that's because Flatpak is blocking access to the serial device.
Unfortunately at the moment I don't think there is a way to give access specifically to the serial devices, so you'd need to give access to all:
$ flatpak run --device=all com.xamarin.MonoDevelop

What this does is essentially mount the host's /dev inside the sandbox, so the app has full access to it.
It's a pretty big hole in the sandbox, but sometimes it's needed until all the permission handling stuff gets implemented.


text:
Q: Removing some slide numbers in Beamer class Berkeley? Using exactlay the code provided here: Slide number in beamer Berkeley header?
I inserted slide numbers. However, I do not want them for some slides (mostly back-up slides): Could you please help me?
What I tried but did not work:
 \documentclass{beamer}
 \usepackage[english]{babel}
 \usepackage[ansinew]{inputenc}
 \usepackage[T1]{fontenc}
 \usepackage{amsmath,amsfonts,amssymb}
 \usepackage{mathptmx}
 \usepackage{booktabs}
 \usepackage{dcolumn}
 \usepackage{tikz}
 \usetikzlibrary{spy}

 \usetheme{Berkeley}
 \makeatletter
 \setbeamertemplate{frametitle}{%
    \nointerlineskip%
    \vskip-\beamer@headheight%
    \vbox to \beamer@headheight{%
        \vfil
        \leftskip=-\beamer@leftmargin%
        \advance\leftskip by0.3cm%
        \rightskip=-\beamer@rightmargin%
        \advance\rightskip by0.3cm plus1fil%
        {\usebeamercolor[fg]{frametitle}
            \usebeamerfont{frametitle}\insertframetitle\hfill\insertframenumber\par}% added number
        {\usebeamercolor[fg]{framesubtitle}
            \usebeamerfont{framesubtitle}\insertframesubtitle\par}%
        \vbox{}%
        \vskip-1em%
        \vfil
    }%
 }
 \makeatother
 \usefonttheme{professionalfonts}
 \setbeamertemplate{bibliography item}[triangle]

 \begin{document}

\begin{frame}{Numbered slide}

I am a slide that wants a number.

\end{frame}

\begin{frame}[noframenumbering]{No Number}
Here should be no number.
\end{frame}

\end{document}

A: You've redefined frametitle to include the frame number, but you haven't made that conditional on the noframenumbering option. To change this, you can redefine frametitle to omit the frame number for \ifbeamer@noframenumbering. Try the following in your example.
 \makeatletter
 \setbeamertemplate{frametitle}{%
    \nointerlineskip%
    \vskip-\beamer@headheight%
    \vbox to \beamer@headheight{%
        \vfil
        \leftskip=-\beamer@leftmargin%
        \advance\leftskip by0.3cm%
        \rightskip=-\beamer@rightmargin%
        \advance\rightskip by0.3cm plus1fil%
        {\usebeamercolor[fg]{frametitle}
            \usebeamerfont{frametitle}
            \ifbeamer@noframenumbering%
            \insertframetitle\par% added number
            \else
            \insertframetitle\hfill\insertframenumber\par% added number
            \fi}
        {\usebeamercolor[fg]{framesubtitle}
            \usebeamerfont{framesubtitle}\insertframesubtitle\par}%
        \vbox{}%
        \vskip-1em%
        \vfil
    }%
 }
 \makeatother


text:
Q: How to add special characters in lucene search ? c# I am using Standard analyzer from lucene in my search engine to search for german words this is my code:
private IList<Document> GetFromLucene(string terme, string FieldName)
    {
        TopDocs hits;
        CustomAnalyzer standardAnalyzer = new CustomAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
        List<Document> matches = new List<Document>();
        IndexSearcher indexSearcher = new IndexSearcher(FSDirectory.Open(new System.IO.DirectoryInfo(MainDoc + DocIndex)), true);

        if (terme.Contains(" "))
        {
            BooleanQuery finalQuery = new BooleanQuery();
            string[] terms = terme.Split(' ');

            #region AND
            QueryParser queryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, FieldName, standardAnalyzer)
            {
                DefaultOperator = QueryParser.Operator.AND
            };
            #endregion

            #region Contains
            Query querys = queryParser.Parse("" + terme + "*");
            finalQuery.Add(querys, Occur.MUST);
            #endregion

            hits = indexSearcher.Search(finalQuery, int.MaxValue);
        }
        else
        {
            WildcardQuery query;
            query = new WildcardQuery(new Term(FieldName, "*" + terme + "*"));
            hits = indexSearcher.Search(query, int.MaxValue);
        }

        matches = hits.ScoreDocs.Select(scoreDoc => indexSearcher.Doc(scoreDoc.Doc)).ToList();

        return matches;
    }

it doesn't appear to find words containing "ü" and "ä".
How can i achieve this ?

A: Lucene uses the so-called analyzer classes to examine indexed terms from text and generate a token stream. To implement an accent-insensitive search, you replace the default analyzer used by Lucene with one that replaces accented characters with the corresponding unaccented ones. Sitefinity CMS has an example: https://www.progress.com/documentation/sitefinity-cms/for-developers-search-with-accented-characters

A: The default analyzer skips the special characters
use the exact match query which will consider the special characters that you use.
https://lucenenet.apache.org/docs/3.0.3/d5/d58/class_lucene_1_1_net_1_1_search_1_1_phrase_query.html


text:
Q: Website menu displays funny in all IE before IE 8 I am new to CSS and have coded my first site with CSS. I will admit to not fully understanding CSS yet but would like to learn. I have heard about special XHTML & CSS coding being needed for older IE browsers but really don't know what CSS code is causing the trouble.
The website is here. The problem is with the top and bottom navigation menus on all pages except Blog and Moodle (I haven't updated those yet). Can someone help me with what needs to be isolated for IE?
Thanks so much!

A: You need to do three things.

*

*use a strict doctype at the top of your page. at the moment you have transitional. a strict doctype ensures that IE conforms to CSS standards the best it can.

*Add the following bit of CSS for your top navigation list items
#topnavcontainer ul li { display:inline; }

*Add the following bit of CSS for your bottom navigation list items
#bottomnavcontainer ul li { display:inline; }

A: Another solution (that should work regardless of doctype);
#topnavcontainer li {
    display:inline-block;
    zoom: 1;
    *display: inline;
}

The short explanation is that inline-block allow you to style the list-items as if they were block level elements (ie, give them width, height, etc) while still laying them out inline. An advantage over float: left is that you can apply text-align to #topnavcontainer to align your navigation left/center/right. You can also set vertical alignment although that seems to be a bit finicky at times.
The other two lines, zoom and *display are a trick to make this work in older versions of IE. It's a long explanation but if you want to know more about it, search Google for "hasLayout" and "css star hack".


text:
Q: Redirecionar uma página com javascript ao abrir uma nova guia Preciso fazer o redirecionamento de uma página com javascript após submeter um formulário, o problema é que esse formulário abre em nova guia e após abrir essa nova guia eu preciso redirecionar a guia original para um novo endereço.
Usando o código abaixo eu não consigo fazer isso:
$("#gerarBoletoForm").on('submit', function(){
    window.location.replace('https://www.site.com.br/');
});

Nem mesmo se eu usar location.href ou location.assign.
Existe alguma forma de fazer isso?

A: O objeto window.opener te dá acesso à aba "mãe". Com window.opener.location.href você vai poder controlar a url dela.

A: Com base nas informações que vocês me passaram eu fui capaz de solucionar o problema.
Primeiramente setei o target do meu formulário numa nova janela criada por mim (e não o _target do form) após isso abri essa nova janela e atribui ela a uma variável e então submeto o formulário.
Após isso consigo usar o opener.location.href sem problemas. Abaixo deixo o código da solução:
$("#gerarBoletoForm").on('click', function(){
    document.gerarBoletoForm.target = "novaJanela";
    var boletoWindow = window.open("","novaJanela","toolbar=0");
    document.gerarBoletoForm.submit();

    boletoWindow.opener.location.href = "https://www.site.com.br/";
});

Dessa foi possível redirecionar a "janela mãe" sem problemas. Obrigado pela ajuda de todos!
PS: não sei se é a melhor solução mas foi possível resolver dessa forma.


text:
Q: Delphi - problem with consuming SOAP with x509 certificate authentication We should use a SOAP web service that is written in c# with Delphi 10.4.2 OR 11.0
related WSDL file successfully imported and the Delphi related code is generated no problem.
the problem is we should use x509 certificate as authentication method but webservice is on HTTP not HTTPS
first we install certificate on local machine and use certificate in HTTPRIO.HTTPWebNode.ClientCertificate by its serial number and call a method with no success. server just close the connection with 0 length reply.
after that we receive a simple working code in c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GeneralUtilityService.GeneralUtilityServiceSR;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Security;

namespace GeneralUtilityServiceProject
{
    class Program
    {
        static void Main(string[] args)
        {
            GeneralUtilityService client = new GeneralUtilityService();

            client.ClientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2("d:/test/test.cer");
            client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2("d:/test/test.p12", "123456", X509KeyStorageFlags.PersistKeySet);
            client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

            var result = client.getLastStatusOfEmployees("username","password");
            var nn = result[0].lastStatusCheck;
            Console.WriteLine(nn);
            Console.ReadKey();
        }
    }
}

but i don't know its equivalent in Delphi to handle certificate like this
any helps would be appreciated
best regards


text:
Q: jqGrid MultiSelect Problem I use that when I construct my jqgrid:
multiselect: true

So I have a check all column. However when I click check all checkbox( the checkbox at header) it selects all checkboxes but the checkboxes are not clicked at each row. Here is a demo: http://www.trirand.com/blog/jqgrid/jqgrid.html and when I click the top checkbox all the checkboes become clicked.
What should I do additionally?
PS: I just want that: http://jsfiddle.net/YWVA8/24/ when a user clicks a row that row's checkbox should be clicked, when user clicks click all all the rows should be selected and their checkboxes clicked. Do I use any other paramater that I should not use with multiselect: true?

A: I solved the problem. My id column element was like:
User 0
User 1
...

I changed it to:
User_0
User_1
...

because it was not recognizing it as a proper id with whitespace.


text:
Q: getResources.getString(R.string.hello_world) not working when i changed my language to french I have 3 string files for 3 different languages(English en, French fr, Spanish sp). When i change the language from en to sp everything works fine. If I change it to fr it says Resource id not found. The resource is available in 3 string files. How can i achieve to get fr language?

Process: com.bhaskar.project, PID: 19377
     android.content.res.Resources$NotFoundException: String resource ID #0x7f0f0059

A: Try below code.
for language change i made one function you have to pass language code and context.
language="en"
set language as per your requirement(English en, French fr, Spanish sp)
context pass your activity/fragment  context
public static boolean setLangRecreate(String language, Context context) {
    try {
        Configuration config = context.getResources().getConfiguration();
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        config.locale = locale;
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
        // recreate();
        ((Activity) context).finish();
        ((Activity) context).overridePendingTransition(0, 0);
        ((Activity) context).startActivity(((Activity) context).getIntent());
        ((Activity) context).overridePendingTransition(0, 0);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}


text:
Q: Exception handling in StreamingResponseBody I'm trying to catch an exception thrown in my implementation of StreamingResponseBody, I can see the exception being thrown inside the class however the thrown exception isn't visible to the method body or my Controller Advice. So none of my handling seems to work, just interested to know which is the correct way to handle exceptions in this case.
@GetMapping(path = "/test", produces = "application/json")
public StreamingResponseBody test(@RequestParam(value = "var1") final String test)
        throws IOException{

    return new StreamingResponseBody() {

        @Override
        public void writeTo(final OutputStream outputStream) throws IOException{
            try {
                  // Some operations..
            } catch (final SomeCustomException e) {
                throw new IOException(e);
            }
        }
    };
}

I would expect my ControllerAdvice to return an ResponseEntity with a Http Status of 500.

A: The best way I discovered to handle errors/exceptions in the web environment is to create your custom exception with the disabled stack trace, and handle it with @ControllerAdvice.
import lombok.Getter;
import org.springframework.http.HttpStatus;

public class MyException extends RuntimeException {

    @Getter private HttpStatus httpStatus;

    public MyException(String message) {
        this(message, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public MyException(String message, HttpStatus status) {
        super(message, null, false, false);
        this.httpStatus = status;
    }
}

And then handle it in @ControllerAdvice like this:
@ExceptionHandler(MyException.class)
public ResponseEntity handleMyException(MyException exception) {
    return ResponseEntity.status(exception.getHttpStatus()).body(
            ErrorDTO.builder()
                    .message(exception.getMessage())
                    .description(exception.getHttpStatus().getReasonPhrase())
                    .build());
}

where ErrorDTO is just a simple DTO with two fields:
@Value
@Builder
public class ErrorDTO {

    private final String message;
    private final String description;

}


text:
Q: mysql error connecting to the server did not ask for password during the installation process I wanted to learn MySQL, so I decided to download it from https://dev.mysql.com/downloads/installer/. However, during the installation it did not ask me for any password, now I cannot connect to the server as it needs a password. I have tried reinstalling it but it still does not ask for the password. Can somebody tell what the problem is?

A: It happens to me several times, if you want to solve this download the full package installer. The second installer from the link you posted. I think that will save you from unnecessary headache.
I hope I'm able to help?

A: Open your terminal and run the below cmd after this one gets into the MySQL server.
sudo mysql --defaults-file=/etc/mysql/debian.cnf

To change the password of any user you can use the below query
ALTER USER '{USER_NAME}'@'localhost' IDENTIFIED WITH mysql_native_password BY '{YOUR NEW PASSWORD}';


text:
Q: transform an array of objects into an array containing arrays of objects I have an array of objects like this:
[{...}, {...}, {...}, {...}, {...}]

An object looks like this:
{
  id: ...
  name: ...
  association: {
    id: ...
  }
}

I'd like to collect objects with the same association id and get a array like this:
[ [ { ... association { id: 1} }, { ... association { id: 1} } ], [ { ... association { id: 2 } } ] ]

How can I do this?

A: Sounds like you're looking for a function that will return an array of objects that contain an association id that is provided
const data = [{...},{...},{...}]
const getByAssociationID = (source, id) => source.filter(obj => obj.association.id === id)
console.log(getByAssociationID(data, id))

A: This should group the data as you describe
function groupByAssociation(data) {
    return data.reduce((list, value) => {
        let added = false;

        list.forEach(group => {
            if(group[0].association.id === value.association.id) {
                group.push(value);
                added = true;
            }
        });

        if(!added) {
            list.push([ value ]);
        }

        return list;
    }, []);
}

A: Use forEach to build and object with keys as association.id and values are accumulated.

const data = [
  {
    id: 1,
    name: "blah",
    association: {
      id: "a1"
    }
  },
  {
    id: 2,
    name: "foo",
    association: {
      id: "a2"
    }
  },
  {
    id: 3,
    name: "test",
    association: {
      id: "a2"
    }
  }
];

const process = data => {
  const obj = {};
  data.forEach(item => {
    const aId = item.association.id;
    const newItem = obj[aId] || [];
    newItem.push(item);
    obj[aId] = newItem;
  });
  return Object.values(obj);
};

console.log(process(data));


text:
Q: Simple calculator problem So I am trying to create a calculator program in arduino using this codes.
void loop()
{
    char keypressed = myKeypad.getKey();
    if (keypressed != NO_KEY)
    {
        //Serial.print(keypressed - 48);
        Serial.print(keypressed);

        if(keypressed > 47 && keypressed < 58)
        {
              if(!mySwitch)
              {
                  num1 = (num1*10) + (keypressed - 48);
              }else{
                  num2 = (num2*10) + (keypressed - 48);
              }
         }

         if(keypressed == 61)
         {
             answer = num1 + num2;
             Serial.println(answer);
             num1 = 0;
             num2 = 0;
             mySwitch = false;
         }else if (keypressed == 43)
         {
             mySwitch = true;
         }
    }
}

This code is for adding the numbers. I do a nested loop
if(keypressed == 61)
{
    if(keypressed == 43){
        answer = num1 + num2;
        Serial.println(answer);
        num1 = 0;
        num2 = 0;
        mySwitch = false;
    }else if (keypressed == 43){
        mySwitch = true;
    }

    if(keypressed == 45){
        answer = num1 - num2;
        Serial.println(answer);
        num1 = 0;
        num2 = 0;
        mySwitch = false;
    }else if (keypressed == 45){
        mySwitch = true;
    }
}

it will only accepts the value and not compute it after pressing the "="sign
btw "61", "43", "45" is the ASCII value of "=", "+", "-"

A: Assuming I understood what you are trying to do (subtraction  when '-' is pressed and addition when '+' is pressed), use the following:
#include <Keypad.h>

const byte numRows = 4; //number of rows on the keypad
const byte numCols = 4; //number of columns on the keypad

//keymap defines the key pressed according to the row and columns just as appears on        the keypad
char keymap[numRows][numCols] =
{
    {'1', '2', '3', '+'},
    {'4', '5', '6', '-'},
    {'7', '8', '9', 'C'},
    {' ', '0', '=', 'D'}
};

//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = {11, 10, 9, 8}; //Rows 0 to 3
byte colPins[numCols] = {7, 6, 5, 4}; //Columns 0 to 3

//initializes an instance of the Keypad class
Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

long num1, num2, answer;
boolean mySwitch = false;
boolean do_subtraction_flag = false;  // when true we will apply subtraction

void setup()
{
    Serial.begin(9600);
    num1 = 0;
    num2 = 0;
}

//If key is pressed, this key is stored in 'keypressed' variable
//If key is not equal to 'NO_KEY', then this key is printed out
//if count=17, then count is reset back to 0 (this means no key is pressed during the   whole keypad scan process

void loop()
{
    char keypressed = myKeypad.getKey();

    if(keypressed != NO_KEY)
    {

        //Serial.print(keypressed - 48);
        Serial.print(keypressed);

        if(keypressed > 47 && keypressed < 58)  // is between '0' and '9'
        {
            if(!mySwitch)
            {
                num1 = (num1 * 10) + (keypressed - 48);
            }
            else
            {
                num2 = (num2 * 10) + (keypressed - 48);
            }
        }

        if(keypressed == '=')
        {
            if(do_subtraction_flag)  // we want to subtract the numbers
            {
                answer = num1 - num2;
            }
            else  // we want to add the numbers
            {
                answer = num1 + num2;
            }

            Serial.println(answer);
            num1 = 0;
            num2 = 0;
            mySwitch = false;
            do_subtraction_flag = false;
        }
        else if(keypressed == '+')
        {
            mySwitch = true;
        }
        else if(keypressed == '-')
        {
            mySwitch = true;
            do_subtraction_flag = true;
        }
    }
}

I have added a flag Boolean variable named do_subtraction_flag
The flag is set depending on the button used, false for addition and true for subtraction.
Its value is used when '=' is pressed to conditionally execute the code that either subtracts num2 from num1 or adds them.
Note that I have replaced keypressed == 61 with keypressed == '='
and keypressed == 43 with keypressed == '+'
It is much easier to read the code this way.


text:
Q: Is it possible to do type conversion (from boolean to yes_no) in pure JPA? There is an annotation in Hibernate that can persist boolean types as 'Y'/'N' in the database.
https://stackoverflow.com/questions/1154833/configure-hibernate-using-jpa-to-store-y-n-for-type-boole
an-instead-of-0-1
However if I don't want to bind to Hibernate is there a way to do it in pure JPA without using getters/setters?

A: Pure JPA without Hibernate is achieved by using some kind of conversion
private boolean enabled;

@Transient
public boolean isEnabled() {
    return this.enabled;
}
public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

@Column(name="ENABLED")
public String getEnabledAsString(){
    return enabled ? "Y" : "N";
}

public void setEnabledAsString(String enabled){
    this.enabled = "Y".equalsIgnoreCase(enabled);
}

Nothing else

A: This is pure JPA without using getters/setters, so it answers the question:
@Entity
public class Person {

    @Convert(converter=BooleanToStringConverter.class)
    private Boolean isAlive;
    ...
}

And then:
@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {

    @Override
    public String convertToDatabaseColumn(Boolean value) {
        return (value == null || !value) ? "N" : "Y";
        }

    @Override
    public Boolean convertToEntityAttribute(String value) {
        return "Y".equals(value);
        }
    }

Please note this solution is JPA 2.1, and was not available when the question was first asked: The JPA 2.1 specification was released 22 April 2013.

A: You can use like this
@Entity
public class Employee {
@Convert(converter=BooleanTFConverter.class)
private Boolean isActive;
}

@Converter
public class BooleanYNConverter implements AttributeConverter<Boolean, String>{
@Override
public String convertToDatabaseColumn(Boolean value) {
    if (value) {
        return "Y";
    } else {
        return "N";
    }
}
@Override
public Boolean convertToEntityAttribute(String value) {
    return "Y".equals(value);
}

}

A: Similar to the above (@Arthur Ronald F D Garcia), but you can also use JPA field access and leave the ivar in the type of the database with transient accessors - marking them @Transient. This ensures JPA acces the entity by field access but leaves the accessors available for appropriately typed usage.
Using the above example:
@Column(name="isconstrained")
private int isConstrained;

@Transient
public boolean getIsConstrained() {
    return (isConstrained == 1);
}

@Transient
public void setIsConstrained(boolean isConstrained) {
    this.isConstrained = (isConstrained? 1 : 0);
}


text:
Q: The primitive type double of a does not have a field Sorry for this basic question, I have tried to check other answers on SO but they haven't been convincing. My code is plain and simple but I do not understand why do I have compiling errors.
Can someone explain this in layman terms? It would be very helpful.
public class gravityCalculator

public static void main(String[] args) {
    // TODO Auto-generated method stub
    double g= -9.81;
    double u= 0.0;
    double t= 10.0;
    double x_i =0;
    double s;
    double a=0;
    if(a<=0){
        a=g;
    }
    //System.out.println(a);
    s= 0.5+a.t^2+u.t+x_i;
}
}

Error Trace
 Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The primitive type double of a does not have a field t
    The primitive type double of u does not have a field t

Edit: This question can also be useful to know about the difference between Datatype and an Object.
Solution : s= 0.5*a*t * t+u*t+x_i;

A: The multiplication symbol in Java is *, not .. Also, Java does not have an exponentiation operator (and ^ means something different than what you want). Correct syntax for what you're trying to do:
s = 0.5 + a*t*t + u*t + x_i;

Here I just multiplied t*t to get t2. In general, exponentiation can be calculated with the Math.pow() method.
EDIT: Assuming that you want to calculate position at a given time t for a given start position x_i, velocity v and acceleration a, you not only need to correct the syntax as above, but you also need to correct the formula:
s = 0.5*a*t*t + u*t + x_i;

(The 0.5 needs to be a coefficient of at2, not an added term.)

A: In your expression s= 0.5+a.t^2+u.t+x_i; there is a part u.t that confused the compiler.
It supposed that u had a public property (field) with name t, but it did not. So you get the error.
u has primitive type double. It is not an object, so it does not have any properties.
Rewrite your expression like that: s = 0.5 + a*t*t + u*t + x_i;

A: The problem is in this part t^2 in java to make a power use Math.pow(), to get t^2 use Math.pow(t,2), also, to multiply in java you have to use * operator instead of . that means object property or attribute, so your complete sentence must be:
Also, to make a correct calculation you must think in operations order, mutiply and divide goes first, so you have to be carefull with parenthesis to get correct result!
s= (0.5+a)*Math.pow(t,2)+u*(t+x_i);

A: It's the line  s= 0.5 + a.t
what were you trying to achieve there? perhaps multiplication? in that case it's asterisk:
0.5 + a * t

A: s= 0.5+a.t^2+u.t+x_i;
You are writing . instead of * for multiplication. . is used to denote methods of fields of the object and primitive objects have no methods or attributes.
Edit: ^ is used as XOR. To square, you have to multiply t*t or use java.lang.Math.pow (I would not recommend using this one as it is way slower.).


text:
Q: How to share a directory using C++ so everyone can access I'm trying to make a program so that when it run, it will create a new folder on C://. I also want to add a feature where the folder can have a shared permission to everyone. So, everyone can access and read/write
I've tried using netshareadd but I always got a compiler warning, how do I get rid of it?
This is creating new directory code :
#include <direct.h>
    int main()
    {
          mkdir("c:/scan");
          return 0;
    }

This is the netshareadd code :
    #ifndef UNICODE
    #define UNICODE
    #endif
    #include <windows.h>
    #include <stdio.h>
    #include <lm.h>
    #pragma comment(lib, "Netapi32.lib")

    void wmain( int argc, TCHAR *argv[ ])
    {
       NET_API_STATUS res;
       SHARE_INFO_2 p;
       DWORD parm_err = 0;

       if(argc<2)
          printf("Usage: NetShareAdd server\n");
       else
       {
          //
          // Fill in the SHARE_INFO_2 structure.
          //
          p.shi2_netname = TEXT("TESTSHARE");
          p.shi2_type = STYPE_DISKTREE; // disk drive
          p.shi2_remark = TEXT("TESTSHARE to test NetShareAdd");
          p.shi2_permissions = 0;
          p.shi2_max_uses = 4;
          p.shi2_current_uses = 0;
          p.shi2_path = TEXT("C:\\scan");
          p.shi2_passwd = NULL; // no password
          //
          // Call the NetShareAdd function,
          //  specifying level 2.
          //
          res=NetShareAdd(argv[1], 2, (LPBYTE) &p, &parm_err);
          //
          // If the call succeeds, inform the user.
          //
          if(res==0)
             printf("Share created.\n");

          // Otherwise, print an error,
          //  and identify the parameter in error.
          //
          else
             printf("Error: %u\tparmerr=%u\n", res, parm_err);
       }
       return;
    }

22    22  D:\kerja\NETSHARE.cpp   [Warning] deprecated conversion from
  string constant to 'LPWSTR {aka wchar_t*}' [-Wwrite-strings]

This is the warning that I always got when compiling the netshareadd code

A: NetShareAdd requires a non const parameter. Some Windows APIs modify the passed buffer (or are way old) so you need a wchar_t*, not a const wchar_t* which is what a L"string" produces.
Solution, copy the const wchar_t* into a vector and pass the vector's data() member to the function (don't forget the null terminator).


text:
Q: django many to many uml confusing In my project i have a many to many relation. as django can handle a many to many relationship, i did like that:
class Groups (models.Model):
        name=models.CharField(max_length=50)
        groups_to_users=models.ManyToManyField(User,related_name='handler')

I have to make umls diagrams, so unless i'm wrong django create the relation table between the both. for the database i did explicitely apear this one.
but in the class diagram how can i handle that ? can class have many to many in uml ?
I guess no, so humm ????   :)

A: What django does is an implementation detail. This is valid UML:


text:
Q: How to send MQTT "message" event back to REST body? I'm currently having problems figuring out how to capture my MQTT message event back to my REST API body which is written in NodeJS. My current setup is App -> NodeJS REST API -> MQTT broker inside RPi 3.
This is my MQTTHandler.js class where I have put all my reusable MQTT functions
const mqtt = require('mqtt')

class MQTTHandler {
  constructor (host) {
    this.client = null
    this.host = host
  }

  connect () {
    this.client = mqtt.connect(this.host)

    this.client.on('error', function (err) {
      console.log(err)
      this.client.end()
    })

    this.client.on('connect', function () {
      console.log('MQTT client connected...')
    })

    // I need this to send message back to app.js
    this.client.on('message', function (topic, message) {
      if (!message.toString()) message = 'null'

      console.log(JSON.parse(message.toString()))
    })

    this.client.on('close', function () {
      console.log('MQTT client disconnected...')
    })
  }

  subscribeTopic (topic) {
    this.client.subscribe(topic)
  }

  unsubscribeTopic (topic) {
    this.client.unsubscribe(topic)
  }

  sendMessage (topic, message) {
    this.client.publish(topic, message)
  }
}

module.exports = MQTTHandler

And below is a short snippet of my app.js
const MQTTHandler = require('./mqtt.handler')
...

var mqttClient = new MQTTHandler('mqtt://127.0.0.1')
mqttClient.connect()

app.get('/hello', function (req, res) {
  mqttClient.subscribeTopic('topic')
  mqttClient.sendMessage('topic', 'hello world')

  // I need to return the MQTT message event here
  // res.json(<mqtt message here>)

  res.end()
})

I have already tried using NodeJS' event emitter but it doesn't seem to work. Any help or suggestions would be much appreciated, thank you!

A: You are trying to mix a synchronous protocol (HTTP) with and asynchronous protocol (MQTT). These 2 paradigm don't easily mix.
When you publish an MQTT message you have no idea how many clients may be subscribed to that topic, it could be zero, it could be many. There is also no guarantee that any of them will send a reply so you need to include a timeout. (You also need to include a request id in the payload so you can coordinate any response with the request as you can't say anything about what order responses may come in.)
Your example code is only using 1 topic, this is very bad as you will end up needing to filter out request messages from response messages. Better to use 2 different topics (MQTT v5 even has a msg header to specify the topic the response should be sent on).
Having said all that it is possible to build something that will work (I will use request and reply topics.
var inflightRequests = {};

// interval to clear out requests waiting for a response
// after 3 seconds
var timer = setInterval(function() {
  var now = new Date.now();
  var keys = Object.keys(inflightRequests);
  for (var key in keys) {
    var waiting = inflightRequests[keys[key]];
    var diff = now = waiting.timestamp;
    // 3 second timeout
    if (diff > 3000) {
      waiting.resp.status(408).send({});
      delete(inflightRequests[keys[key]]);
    }
  }
},500);

// on message handler to reply to the HTTP request
client.on('message', function(topic, msg){
  if (topic.equals('reply')) {
    var payload = JSON.parse(msg);
    var waiting = inflightRequest[payload.requestId];
    if (waiting) {
      waiting.res.send(payload.body);
      delete(inflightRequests[payload.requestId]);
    } else {
      // response arrived too late
    }
  }
});

// HTTP route handler.
app.get('/hello', function(req, res) {
  //using timestamp as request Id as don't have anything better in this example.
  var reqId = Date.now();
  var waiting = {
    timeStamp: reqId,
    res: res
  }
  inflightRequests[reqId] = waiting;
  var message = {
    requestId: reqId,
    payload: 'hello world'
  }
  client.publish('request',JSON.stringify(message));
});


text:
Q: translate dynamic text in angular 2 l10n i try to translate a dynamic text by this line
{{'{{var}}'| translate:lang }}

while {{var}} is text that can change in the component.ts
and in my json file i have several options for the dynamic value of "var".
but its dont work.
Is there a way to do it?


text:
Q: After change value with jquery I cant select this value I have problem with this code: Where I am changing value of eache option and after I want to show or hide div depending on value.
But after changing value of options I cant select in jQuery that value.
$("#form1 > select > option:not(:first), #form7 > select > option:not(:first)").each(function() {
$(this).attr('value',$(this).text());
});

$('#frmdocumentsForm-r1').on('change',function(){
    if($(this).val()=='AAA'){
        $('#form2own').show();
    } else {
        $('#form2own').hide();
    }
});
$('#frmdocumentsForm-r7').on('change',function(){
    if($(this).val()=='BBB'){
        $('#form8own').show();
    } else {
        $('#form8own').hide();
    }
});

A: trim your text to remove the spaces from it, and then try as
$("#form1 > select > option:not(:first), #form7 > select > option:not(:first)").each(function() {
     $(this).val($.trim($(this).text()));
});

A: Try this
$("#form1 > select > option:not(:first), #form7 > select > option:not(:first)").each(function() {
   var textValue = $(this).text().trim();
   $(this).val(textValue);
});


text:
Q: $y_n^*\to y^*$ strongly in $Y^*$ and $y_n\to y$ weakly in $Y$ implies $y_n^*(y_n) \to y^*(y)$ given a sequence $y^*_k \in Y^*$ with $\|y^*_k-y^* \| \to 0$.
($y_k \to y$ weakly convergent in $(Y,\| \|_Y)$)
show that $\lim_{n \to \infty} y_n^*(y_n) = y^*(y)$.
My idea:
$|y_n^*(y_n) - y^*(y)| \le |y^*_n(y_n)-y^*_n(y)| +|y^*_n(y)-y^*(y)| \le \| y^*_n \| \|y_n-y\|+|y^*_n(y)-y^*(y)|$
I'm a bit confused here, what can I assume is $y_n$ bounded? $ \|y_n-y\| \to 0$? what about $|y^*_n(y)-y^*(y)|$?
I'm very thankful for tips.
Greetings.

A: Since $y_n\to y$ weakly, we deduce that $M:=\sup_{n\in\mathbb{N}}\|y_n\|<\infty$ (use the uniform boundedness principle and the canonical isometry from $Y$ into $Y^{**}$ to see this).
Then, for every $k\in\mathbb{N}$, we have
\begin{align*}
|y_n^*(y_n)-y^*(y)|
&\le |y_n^*(y_n)-y_k^*(y_n)|+|y_k^*(y_n)-y^*(y_n)|+|y^*(y_n)-y^*(y)| \\
&\le \|y_n^*-y_k^*\|\|y_n\|+\|y_k^*-y^*\|\|y_n\|+|y^*(y_n)-y^*(y)| \\
&\le M(\|y_n^*-y_k^*\|+\|y_k^*-y^*\|)+|y^*(y_n)-y^*(y)|.
\end{align*}
Now use the facts that $y_n^*\to y^*$ and $y^*(y_n)\to y^*(y)$ to conclude.

A: $$
|y_n^*(y_n) - y^*(y)|\le|(y_n^*- y^*)(y_n)| + |y^*(y_n-y)|\le\|y_n^*-y^*\|\|y_n\| + |y^*(y_n-y)|.
$$
If $Y$ is a Banach space, $(y_n)$ - as a weakly convergent sequence - is bounded. So, both terms tend to zero.


text:
Q: Story with time-traveling vampires Lately I've been trying to remember a book I read a while ago, about a group of time-traveling vampires and (possibly) including the one and only Count Dracula himself.
The book was written in English by an American author probably in the 80s, but I read it around the mid-90s. It was a paperback with around 200+ pages or so and if I remember correctly, the version that I had, had a red cover.
The story is that vampires really do exist in our society and they really fear the sign of the cross and daylight. However, due to the modern surveillance and policing methods of our society, feeding unobserved is becoming more and more difficult, thus being led to extinction as they are also hunted by the Van Helsing family (descendants of the famous vampire hunter of the original Bram Stoker story).
Some time in the near future only a handful of them are left and are led by the Count himself. At the same time, a scientist makes a time-machine and becomes an instant celebrity in the news. In a desperate attempt, the Count and his team attempt a series of heists: First they steal a few nuclear bombs from a nearby base and then the time-machine itself, with the goal to travel back to the Stone Age when humans are not a threat and explode the bombs to make a nuclear winter, thus walking the Earth unmolested and enslaving the humans of the time, so as to keep them as cattle.
However, at the very last minute they are stopped by our hero (a Van Helsing of course), albeit, with him and his love interest being stuck in the stone Age with the last few of the vampires, thus starting the cycle once again. Finally, one of the bombs exploded and the mushroom cloud and the bright flash cause the vampires' fear of light and the cross.
I tried to provide as many details as possible, but my google-fu is giving me lots of irrelevant results due to the terms time-travel, Dracula, vampires etc, and I may be confusing some of the details with other stories, so my apologies. Any help is appreciated!

A: Could it Brian Aldiss's Dracula Unbound? That does feature vampires travelling through time, as well as Bram Stoker, Dracula, and a nuclear bomb going off in prehistoric times.

In the barren dust of the far future, the sun leaks energy in a darkening sky and the only remaining humans are imprisoned by spectral bloodthirsty beings. Back in the brilliant Utah sunlight of 1999, two ancient graves yield evidence that a species of human coexisted with the dinosaurs. Linking these scenarios is impetuous inventor, Joe Bodenland, who has just created a time machine that manipulates time to disperse of hazardous waste.

However, it looks like the vampires set off the nuclear weapon in 2599 and it's the heroes who bring one to the past, killing off the pterosaurs that will evolve into vampires.
Search terms of book vampires dracula "time machine". Took me a few other searches with the book title to get details about the bombs, though.


text:
Q: Diferencias entre file_get_contents() y curl Estoy haciedo un script para obtener contenido desde una url y he encontrado  aqui, aqui y aqui que se puede hacer con curl y con file_gets_contents(), pero no tengo del todo claro dos cosas:

*

*¿Qué diferencias hay entre las dos?

*¿Cuál es la mas apropiada para obtener html desde una url para luego analizar el html?

El código que he usado es este:
file_get_contents
$html = file_get_contents($urlFlujo, false, $context);

curl
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);

Realizan la misma función que es obtener un html a partir de una url, pero no tengo claro que funcionen de la misma forma o sirvan exactamente para lo mismo.
Pido solo datos empíricos y demostrables de qué forma es la más apropiada (menor tiempo de ejecución, menor consumo de recursos, etc.) para mi caso.

A: En pocas palabras:
file_get_contents()
Es un simple destornillador. Ideal para simples solicitudes GET donde el encabezado, método de solicitud HTTP, tiempo de espera, cookies, redirecciones y otras cosas más complejas no importan.
También se pueden usar para peticiones POST, pero habría que crear un contexto para ello (Ver esta contribución en el Manual de PHP).
Es menos seguro que cURL y por eso viene desactivado por defecto en muchos entornos PHP.
cURL
Es mucho más potente y para usos más avanzados.
cURL  es probablemente la librería de HTTP más ampliamente utilizada en el mundo de la programación. Originalmente fue codificado utilizando lenguaje C, y luego fue portado a muchos otros lenguajes.
cURL puede manejar manipulaciones HTTP complicadas de manera elegante, como solicitudes HTTP asíncronas, informes de progreso, etc.
El único problema de cURL es que requiere algún tiempo, varias horas al menos, para familiarizarse con sus funciones y estilo de codificación.
Pero al ser una librería tan usada, la documentación y ejemplos de código en la red son abundantes.
Como ejemplo, sólo basta con ver la amplia documentación para cURL en el Manual de PHP (enlace de más arriba).

¿Cuál es más rápido?
Todas las pruebas que he leído hasta ahora indican que cURL es más rápido.
El siguiente gráfico es el producto de una prueba entre diferentes métodos, publicada por Philip Norton en Quickest Way To Download A Web Page With PHP

Ver también:

*

*PHP cURL vs file_get_contents en Stackoverflow en inglés.

*Comparison of the HTTP libs in PHP: file_get_contents vs. cURL vs. PECL_HTTP

A: Realmente sirven para lo mismo, sólo que file_gets_contents va de serie en PHP, y curl es un módulo que hay que instalar y activar en la configuración de PHP.
curl tiene muchas más opciones, más sencillas de utilizar y hay muchos más ejemplos en internet.
Con file_get_contents tienes funciones parecidas a curl, pero tienes que montarte un contexto, con streams y otras cosas que complican bastante, por lo menos al principio.
De todas formas la principal y más importante diferencia es que la función file, la cual es utilizada por file_get_contents, puede estar bloqueada en algunos servidors web compartidos de algunos hostings, ya que ciertos usos de la misma pueden ser un problema de seguridad. En caso de estar bloqueada tendrás que utilizar curl por obligación.


text:
Q: Passando método com parâmetro É possivel eu utilizar uma função do componente pai que atualiza o estado desse mesmo componente em OUTRO componente? (esta função possui um parâmetro que seria o novo valor a ser atualizado)
Esta é a função que quero utilizar no componente filho

function atualizarCadastros(novoCadastro){
setCadastros(cadastrosAtuais => {
return[...cadastrosAtuais, novoCadastro]
})
}

Componente pai:

import './App.css';
import React, {useState} from 'react';
import {Table, Jumbotron, Button} from 'react-bootstrap'
import Formulario from './Formulario'
import renderCadastros from './renderCadastros'

function App() {

  const [Cadastros, setCadastros] = useState([{
    "id": 1,
    "nome": "Francisca Julia da Costa",
    "cpf": "457.696.936-65",
    "rg": "47.360.897-2",
    "data_nasc": "23/03/1944",
    "sexo": "Feminino"
  },
  {
    "id": 2,
    "nome": "Noah Felipe Silva",
    "cpf": "956.531.431-70",
    "rg": "40.974.782-8",
    "data_nasc": "11/07/1964",
    "sexo": "Masculino"
  },
  {
    "id": 3,
    "nome": "Alícia Rosângela Melo",
    "cpf": "066.291.353-18",
    "rg": "36.214.141-1",
    "data_nasc": "18/02/1978",
    "sexo": "Feminino"
  }])

  function atualizarCadastros(novoCadastro){
    setCadastros(cadastrosAtuais => {
      return[...cadastrosAtuais, novoCadastro]
    })
  }

  return (

  <Jumbotron style={{background: 'transparent'}}>

    <Formulario/>

          id
          Nome
          CPF
          RG
          Nascimento
          Sexo

        {Cadastros.map(renderCadastros)}

  </Jumbotron>

  );
}

export default App;

Componente filho em questão:

import './App.css';
import React, {useRef} from 'react';
import {Button, Form, Col} from 'react-bootstrap'

function Formulario (){

  return(

    <Form>
    <Form.Row>
      <Col>
        <Form.Label>Identificação</Form.Label>
        <Form.Control placeholder="Id" />
      </Col>
      <Col>
        <Form.Label>Nome Completo</Form.Label>
        <Form.Control placeholder="João Silva" />
      </Col>
      <Col>
        <Form.Label>CPF</Form.Label>
        <Form.Control placeholder="000.000.000-00" />
      </Col>
      <Col>
        <Form.Label>RG</Form.Label>
        <Form.Control placeholder="0.000.000" />
      </Col>
      <Col>
        <Form.Label>Data de Nascimento</Form.Label>
        <Form.Control placeholder="DD/MM/AAAA" />
      </Col>
      <Col>
        <Form.Label>Sexo</Form.Label>
        <Form.Control placeholder="Masculino/Feminino" />
      </Col>
    </Form.Row>
    </Form>

      <Button style={{margin: '10px'}} variant="primary">Cadastrar</Button>

  )
}

export default Formulario

E segue o outro componente que compõe a aplicação apenas para completar o código:

import './App.css';
import React from 'react';
import {Button} from 'react-bootstrap'

function renderCadastros(cadastro, index){
    return(

        {cadastro.id}
        {cadastro.nome}
        {cadastro.cpf}
        {cadastro.rg}
        {cadastro.data_nasc}
        {cadastro.sexo}
        <Button variant="danger">Excluir</Button>

)
  }

  export default renderCadastros

A: No componente você pode passar a função como um atributo HTML:
<Formulario atualizarCadastro={atualizarCadastro} />

No componente filho, você acessa a função por meio das propriedades de argumento:
function Formulario({ atualizarCadastro }) { ... }


text:
Q: 2D Cellular Automata Glitch I'd like to make it so that my code generates a cave system in a game. I'm having trouble with the code; it seems that it makes meshes in the parts inbetween the caves and I don't want a mesh, I want an open area. Here is my code:
package CATest;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CATest extends JPanel{
    static CATest w;
    static Random rand=new Random();
    JFrame jf=new JFrame();
    boolean tileMap[][];
    public static void main(String argsp[]){
        w=new CATest();
        w.jf.add(w);
        w.jf.setSize(100,400);
        w.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.jf.setVisible(true);
        w.tileMap=new boolean[100][400];
        for(int x=0;x<w.tileMap.length;x++)
            for(int y=0;y<w.tileMap[0].length;y++)
                if(rand.nextFloat()<0.7)
                    w.tileMap[x][y]=true;
        for(int step=0;step<7;step++){
            boolean newMap[][]=new boolean[100][400];
            for(int x=0;x<w.tileMap.length;x++)
                for(int y=0;y<w.tileMap[0].length;y++){
                    int count=0;
                    if(x-1>=0&&y-1>=0&&x+1<w.tileMap.length&&y+1<w.tileMap[0].length){
                        if(w.tileMap[x-1][y])
                            count++;
                        if(w.tileMap[x+1][y])
                            count++;
                        if(w.tileMap[x][y-1])
                            count++;
                        if(w.tileMap[x][y+1])
                            count++;
                        newMap[x][y]=count<=3;
                    }
                }
            w.tileMap=newMap;
        }
        w.repaint();
    }
    @Override
    public void paintComponent(Graphics g){
        for(int x=0;x<tileMap.length;x++)
            for(int y=0;y<tileMap[0].length;y++){
                if(tileMap[x][y])
                    g.setColor(Color.black);
                else g.setColor(Color.white);
                g.drawRect(x,y,1,1);
            }
    }
}

Here's a picture of what happens:cellular automata
As you can see, there is a mesh where there should be a cave. Please, help.

A: I omitted the fact that the center tile needed to be accounted for. So instead of
if(w.tileMap[x-1][y])
    count++;
if(w.tileMap[x+1][y])
    count++;
if(w.tileMap[x][y-1])
    count++;
if(w.tileMap[x][y+1])
    count++;

it should be
if(w.tileMap[x][y])
    count++;
if(w.tileMap[x-1][y])
    count++;
if(w.tileMap[x+1][y])
    count++;
if(w.tileMap[x][y-1])
    count++;
if(w.tileMap[x][y+1])
    count++;


text:
Q: How to add a className to single .map item? I want to add className to a .map item, but only for the one which is clicked.
Tried useState ( {state ? "class" : ""} ) but it added class for all items inside my loop.
I also tried useRef but I learned that useRef does not cause re-render so result didn't update on screen.
example code:
    {posts.map((post)=> {
      return (
        <div className=`PLACE FOR CLASS` key={post.id}>
        {post.title}
        <button onClick={()=> onclick event to add class}>add</button>

      )
    })}

So what is the way to add class only for item which is clicked in this case? ( I think I need to use Key but don't know how )

A: If you don't want to add this information to the main state (posts) you can create a separate list of selected ids, it'll be something like this (assuming you're using function components)
const [selectedPosts, setSelectedPosts]=useState([]);
...
{posts.map((post)=> {
  return (

    {post.title}
    <button onClick={()=> {setSelectedPosts(s => [...s, post.id])}}>add</button>

  )
})}


text:
Q: Point iTunes to restored content after PC crash After my PC died I have started to restore my data from backup.  I have backed up the entire iTunes folder and successfully restored it.  I do not put my content in the standard location...I do not put it on the Windows drive for example.  Now that I have reinstalled iTunes, how do I tell it to use the content I restored?  Right now it just shows all my music as existing on the cloud.
I'm on Windows 7 64-bit and I have the latest version of iTunes.  I do not have iTunes match.
Thanks!

A: You can change the default location for the main mp3 file storage for iTunes, but not [easily] the location of the database files.
It is far simpler in the long term to leave the database in its default location -
C:\Users\[your name]\Music\iTunes
This is also a folder you should recover from your old machine & transfer to the new one, otherwise you will have all the music but none of the playlists, play counts etc etc. & will have to re-import all your existing tunes.
You can, however, easily change the main 'content' storage location.
Go to Edit menu > preferences > Advanced
The first section is 'iTunes Media Folder Location' with a file path beneath [presumably currently set to the default location mentioned above] & a Change… button to the right. This will allow you to redirect to your non-standard location.

If you still have the original database successfully recovered from your old machine, then to save a lot of additional effort, make sure you put your content folder in "the same place" as it used to be on the old machine, i.e., if it was in D:\iTunes remote folder then put it in the same place again, otherwise it will lose the connection to your existing tunes & again have to be rebuilt.


text:
Q: Differences between /clr and /clr:netcore + net6.0 I have a managed C++ project in Visual Studio 2022 (v143) where I've used the following in the settings (Configuration Properties > Advanced):
**Attempt #1:**
Common Language Runtime Support: .NET Core RUntime Support (/clr:netcore)
.NET Core Target Framework: net6.0

**Attempt #2:**
Common Language Runtime Support: Common Language Runtime Support (/clr)
.NET Core Target Framework:

Each of these attempts worked when used by a C#-.NET 6.0 project. Is there a difference between these two configurations? Is one preferrable to the other? Thanks in advance!


text:
Q: How do I find the sphere center from 3 points and radius? I have three 3D points p1, p2 and p3 and the sphere radius. How do I find the sphere center from 3 points and radius?
I expect two 3D points as solution because there are 2 spheres that meet the requirements.
Thanks.

A: *

*Find the plane P containing all three points. In that plane these
points determine a triangle.

*Find the circle around this triangle. Let C denote the center of
this circle.

*Find the line perpendicular to P and crossing it at C.

*On this line, find those 2 points with the desired distance from the
circle.
I have ignored degenerate cases.

A: There are a number of ways to formalize this. Here's one of them (basically the same as Ali suggested, but with more math): you want to find points
(a) equidistant from p1, p2, p3, with
(b) the distance being exactly R.
First off, find a center of the circumscribed circle as per http://en.wikipedia.org/wiki/Circumscribed_circle (see the part about "the circumcircle of a triangle embedded in d dimensions"):
p0 = cross(
    dot(p21, p21) * p31 - dot(p31, p31) * p21,
    n
) / 2 / dot(n, n) + p1,

with p21=p2-p1, p31=p3-p1, n=cross(p21,p31).
The points from item (a) lie on a line that passes through this point, and is orthogonal to the plane containing p1, p2, p3, so its equation is
p(t) = p0 + n * t

Substitute this into
dist(p1, p)^2 = dot(p - p1, p - p1) = R^2

to get the quadratic equation
dot(n, n) * t^2 - 2*dot(n, p0-p1) * t + dot(p0-p1, p0-p1) = R^2

Actually, n and (p0-p1) are orthogonal, so the second addend on the left is 0, and
t1 = sqrt((R^2 - dot(p0-p1, p0-p1))/ dot(n, n)),
t2 = -sqrt((R^2 - dot(p0-p1, p0-p1))/ dot(n, n))

(note how p1 in p0 cancels out). Substitute these into p(t) to get the answer.


text:
Q: call from method in class to @class.method using python I am trying to make a class, that will be eventually turned into a library. To do this, I am trying to do something like what discord.py made, and the idea comes from it.
The code that discord makes is:
@bot.event
async def on_ready():
   print('discord bot is ready')

Where the '@bot' is just an object that I created before by doing
bot = discord()

And the '.event' is a preprogramed and ready to use method.
on_ready() is a function that is called already.
I want to have a way to create this from my own class, and from there mannage the entire code using async functions.
How to do it in my own code?

A: You need to implement a class whose public methods are decorators. For example, this class implements a scheduler that exposes scheduling through a decorator:
class Scheduler:
    def __init__(self):
        self._torun = []

    def every_second(self, fn):
        self._torun.append(fn)

    async def _main(self):
        while True:
            for fn in self._torun:
                asyncio.create_task(fn())
            await asyncio.sleep(1)

    def run(self):
        asyncio.run(self._main())

You'd use it like this:
sched = Scheduler()

@sched.every_second
async def hello():
    print('hello')

@sched.every_second
async def world():
    print('world')

sched.run()

The class mimics discord in that it has a run method that calls asyncio.run for you. I would prefer to expose an async main instead, so the user can call asyncio.run(bot.main()) and have control over which event loop is used. But the example follows discord's convention, to make the API more familiar to users of discord.py.


text:
Q: Prevent hotlinking but allow specified images? I'm preventing hotlinking with this in htaccess:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain\.com [NC]
RewriteRule \.(gif|jpe?g|png)$ - [F,NC,L]

However, I'd like to allow certain specified images to be hotlink-able, how do I do this?
I can't find anything about it online.
Thanks,
Colin

A: RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain\.com [NC]
RewriteCond %{REQUEST_URI}  !^images/allow-hotlink/.+\.(gif|jpe?g|png)$
RewriteRule \.(gif|jpe?g|png)$ - [F,NC,L]

A: you can add another rewrite condition like so:
RewriteCond %{REQUEST_URI}  !^whitelisted-directory/.*

but its more efficient and easier just to add one write rule that does nothing above and declare it at last like so:
RewriteRule ^(whitlistet-directory1|whitelisted-directory2) - [L]


text:
Q: Add some new sorting options to the flag queue We already have a sort order for the moderator queue that sorts flags by a certain "Order of Importance."
However, I don't work the queue from top to bottom.  Frequently, I will dispatch the "Not an answer" flags first, because they are by far the easiest to process (I can do about twelve per minute; it takes me about 5 seconds to decide on each one).  In the past, these used to cluster together, making them easy to handle at once.
Then I will do the spam flags (if I can find them).  Then I will do the off-topic ones (If I have any time left).  Because I am not constantly changing gears mentally, I believe I get more done by working this way.
Please give me a new sort option that sorts "Not an Answer" to the top. Give me one that sorts "Off Topic" to the top. Give me one that sorts spam or offensive flags to the top. That way I can prioritize my work, and I'm not constantly context-switching (i.e. I can focus on one type of flag at a time).
Note that this is probably only a problem on SO (and maybe SU) due to the sheer number of flags.
The flag weight can still be used to prioritize the flags within each sorting.


text:
Q: ¿Como soluciono este error del cors en ionic3?
Necesito solucionar ese error que aparece en consola de la app.

A: 1.- Puedes agregar un proxy en el archivo ionic.config.json de tu app Ionic para realizar pruebas.
En la documentación te dice como: service-proxies.
2.- Tu servidor debe permitir peticiones javascript desde otros servidores para poder obtener información del servidor original. Mas información en Wikipedia: CORS, Mozilla CORS.
Esas son las 2 posibles soluciones a las restricciones que tienes para poder realizar tus peticiones.

A: Otra opción seria en tu script de php agregar:
header("Access-Control-Allow-Origin: *");

O si estas usando el framework slim según la documentación:
$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
            ->withHeader('Access-Control-Allow-Origin', 'http://mysite')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});

Link a la documentación de slim


text:
Q: tcl set list of arrays produce duplicates I'm producing a TCL procedure that will return a list of arrays of devices under a switch.  The definition is an XML file that is read.  The resulting lists of XML entries are parsed using a recursive procedure and the device attributes are placed in an array.
Each array is then placed in a list and reflected back to the caller.  My problem is that when I print out the list of devices, the last device added to the list is printed out each time.  The contents of the list is all duplicates.
Note:  I'm using the excellent proc, 'xml2list' that was found here.  I'm sorry, I forgot who submitted this.
The following code illustrates the problem:
source C:/src/tcl/xml2list.tcl

# Read and parse XML file
set fh [open C:/data/tcl/testfile.xml r]
set myxml [read $fh]
set mylist [xml2list $myxml]

array set mydevice {}

proc devicesByName { name thelist list_to_fill} {
        global mydevice
        global set found_sw 0

        upvar $list_to_fill device_arr
        foreach switch [lindex $thelist 2] {

            set atts [lindex $switch 1]
            if { [lindex $switch 0] == "Switch" } {
                if { $name == [lindex $atts 3] } {
                    set found_sw 1
                    puts "==== Found Switch: $name ===="
                } else {
                    set found_sw 0
                }
            } elseif { $found_sw == 1 && [string length [lindex $atts 3]] > 0 } {

                set mydevice(hdr) [lindex $switch 0]
                set mydevice(port) [lindex $atts 1]
                set mydevice(name) [lindex $atts 3]
                set mydevice(type) [lindex $atts 5]
                puts "Device Found: $mydevice(name)"
                set text [lindex $switch 2]
                set mydevice(ip) [lindex [lindex $text 0] 1]

                lappend device_arr mydevice
            }
            devicesByName $name $switch device_arr
         }
    }

    #--- Call proc here

    # set a local array var and send to the proc
    set device_arr {}
    devicesByName "Switch1" $mylist device_arr

    # read out the contents of the list of arrays
    for {set i 0} {$i<[llength $device_arr]} {incr i} {
        upvar #0 [lindex $device_arr $i] temp
        if {[array exists temp]} {
            puts "\[$i\] Device: $temp(name)-$temp(ip)"
        }
    }

The XML file is here:
<Topology>
    <Switch ports="48" name="Switch1" ip="10.1.1.3">
        <Device port="1" name="RHEL53-Complete1" type="host">10.1.1.10</Device>
        <Device port="2" name="Windows-Complete1" type="host">10.1.2.11</Device>
   <Device port="3" name="Solaris-Complete1" type="host">10.1.2.12</Device>
    </Switch>
    <Switch ports="36" name="Switch2" ip="10.1.1.4">
        <Device port="1" name="Windows-Complete2" type="host">10.1.3.10</Device>
    </Switch>
    <Router ports="24" name="Router1" ip="10.1.1.2">
        <Device port="1" name="Switch1" type="switch">10.1.1.3</Device>
        <Device port="2" name="Switch2" type="switch">10.1.1.4</Device>
    </Router>
</Topology>

If my code blocks look bad, please excuse that.  I followed the directions as I read them, but it didn't look correct.  I could not fix it, so just posted anyway.
Thanks in advance...

A: Arrays in tcl are not values. Therefore they don't behave like regular variables. They are in fact something special like filehandles or sockets.
You cannot assign an array to a list like that. Doing:
lappend device_arr mydevice

simply appends the string "mydevice" to the list device_arr. That string happens to be the name of a global variable so that string may be used later to access that global variable.
To build up a key-value data structure what you want is a dict. You can think of a dict as a special list that has even numbers of elements in the format: {key value key value}. In fact, this data structure works even on very old versions of tcl before the introduction of dicts because the foreach loop in tcl can be used to process key-value pairs.
So what you want is to create a new $mydevice dict each loop and use [dict set] to assign the values.
Alternatively you can keep most of your code and change your lappend to:
lappend device_arr [array get mydevice]

This works because [array get] returns a key-value list which can be treated as a dict. You can later access the data using the dict command.

A: Array variables can't be used as values. To put the contents of one into a list element, send it to a proc, write it to a file etc, convert it to list form (key, value, key, value...) with array get.
lappend device_arr [array get mydevice]

To use it later, write the list back to an array with array set.
foreach device_l $device_arr {
  #array unset device
  array set device $device_l
  puts "$device(name)-$device(ip)"
}

Note that array set doesn't erase the old keys in the destination array, so if you use it in a loop and the key names aren't always the same, you need to clear the array every iteration.

A: You can store this information in two ways using arrays . First is as a multi-dimensional array, in this case a three dimensional array and the second is a one dimensional array storing a list that can be converted easily to an array later for accessing data at a later time.
For the 3d array the key would be Switch Name,device_port,dataname you would change your erroneous temporary myDevice and lappend code to
  # attr is a list of { attributename1 value1  ... attributenameN valueN}
  array set temp $attr
  set port $temp(port)
  set text [lindex $switch 2]
  set ip [lindex [lindex $text 0] 1]
  # name already set to "Switch1" etc
  foreach f [array names temp ] {
      set device_arr($name,$port,$f) $temp($f)
  }
  set device_arr($name,$port,ip) $ip
  array unset temp

this code results in the following ( when parray device_arr
parray device_arr

device_arr(Switch1,1,name) "Switch1"
device_arr(Switch1,1,port)  1
device_arr(Switch1,1,type) "RedHat .."
device_arr(Switch1,1,ip) 10..
device_arr(Switch1,2,name) "Switch1"
device_arr(Switch1,2,port)  1
device_arr(Switch1,2,type) "RedHat .."
device_arr(Switch1,2,ip) 10..
...
device_arr(Switch2,1,name) "Switch1"
device_arr(Switch2,1,port)  1
device_arr(Switch2,1,type) "Windows Complete"
device_arr(Switch2,1,ip) 10..
....

to find ip of Switch1 port2 you would:
puts "the ip of Switch1 port 2 is $device_arr(Switch1,2,ip)"

Note lots of data duplication but you can access all data directly without having to go to an intermediate step to get to the data  as in the next scheme
  # attr is a list of { attributename1 value1  ... attributenameN valueN}
  set data $attr
  array set temp $attr
  set text [lindex $switch 2]
  set ip [lindex [lindex $text 0] 1]
  lappend data ip $ip
   set key "$name,$temp(port)"
  # name already set to "Switch1" etc
  set device_arr($name,$port) $data
  array unset temp

doing a parray device_arr gives:
device_arr(Switch1,1) {  port "1" name "RHEL53-Complete1" type "host" ip 10.1.1.10 }
device_arr(Switch1,2) {  port "2" name "Windows-Complete1" type "host" ip 10.1.2.11}
....

to find the ip of swtich1 port 2 you would
  array set temp $device_array(Switch1,2)
   puts "ip of device 2 is $temp(ip)"


text:
Q: Suitable payment method for sell Credits in iOS, Android and Web I am developing a system it has web application, iOS application and Android application. There user can buy credits through web, iOS device or Android device. Credit purchased are stored in Database and can be used from any of Applications mentioned above. My Question is in mobile Apps should I use In App Purchase and In App billing or should use third party Payment Gateway. I contacted Google and Apple. I didn't get direct answer. I was asked to look at the web.

A: Please, don't use 3rd party for purchasing credits that are used within the app. My app just got rejected for that reason. I used Swipe instead of IAP


text:
Q: How to disable firefox rendering for a program? how can i disable the Firefox rendering? i would like to download and display pure html only for a program i have in java which use selenium api

A: You have to change your Reponse Headers
In C# I'd do
Response.ContentType = "text/plain"

If you want the user to see the html code.
or
Response.ContentType ="application/octet-stream"

If you want the user to download the html code.
EDIT : In java it seams that it's the "contentType" attribute of your @page directive on the top of your .jsp files that'll change the response's header.

A: You can replace all angle brackets in returned content with '<' or '>'. This will render them as text representations of html tags instead of the browser parsing them.


text:
Q: Drupal 6 + Lighttpd = Very Slow on registering & no email I have VPS account with 256MB RAM.
But when Im trying registering, it takes very long time, and no email sent
Is this because I have too small resource?

A: 256MB RAM is more than enough to run Drupal6. I run it in a 64MB VPS with MySQL as well. Have you optimised your service resources? You want to tweak lighttpd and fastcgi to be lightweight. There are lots of examples on the Internet.
It is more likely that there is something wrong with your mail back-end. Did you setup an MTA to send your mail? Alternatively, you may want to use something like sSMTP to proxy your mail over to a real mail server. PHP on its own will use sendmail by default. However, if your back-end MTA is not configured correctly, things can go missing.


text:
Q: Java multithreads - Identify the error in the code So this code was given in an exam and the question was what's wrong with it. It's meant to create new objects of type SomeClass but only if they were not created earlier.
class Foo {
    private SomeClass x = null;
    public synchronized SomeClass getX() {
        if (x == null)
            x = new SomeClass();
        return x;
    }
}

My guess is that x and getX should be declared static since otherwise there may be multiple copies of x. Is that correct? if so is that the only problem in the code?

A: You are trying to build a singleton factory method:
public class Foo {
    private static SomeClass x = null;
    public static synchronized SomeClass getSomeClass() {
        if (x == null)
            x = new SomeClass();
        return x;
    }
}

Note that if you really need this, you should also make SomeClass an inner class of Foo, and make the constructor of SomeClass private.


text:
Q: Need Help Solving this Indefinite Integral I was viewing past questions of the MIT Integration Bee and came across the problem:
$$ \int \frac{x^2+1}{x^4-x^2+1}\,dx$$
According to MIT, first semester calculus should be sufficient enough to solve this problem.
I have tried many conventional methods, unsuccessfully, and would appreciate any and all help.
Edit: Changed LaTeX formatting

A: $$F=\frac{x^2+1}{x^4-x^2+1}=\frac{1+\dfrac1{x^2}}{x^2-1+\frac1{x^2}}$$
Observe that $\displaystyle\int\left(1+\dfrac1{x^2}\right)=x-\frac1x$
So,$\displaystyle F=\frac{1+\dfrac1{x^2}}{\left(x-\frac1x\right)^2+2-1}$

A: Maybe not as elegant but more intuitive, there's always partial fractions.
$$\int\frac{x^2+1}{x^4-x^2+1}dx=\int\frac{x^2+1}{x^4+2x^2+1-3x^2}dx=\int\frac{x^2+1}{(x^2+1+x\sqrt3)(x^2+1-x\sqrt3)}dx=$$
$$\frac12\int\frac{dx}{(x+\frac{\sqrt3}2)^2+\frac14}+\frac12\int\frac{dx}{(x-\frac{\sqrt3}2)^2+\frac14}=$$
$$\int\frac{2dx}{(2x+\sqrt3)^2+1}+\int\frac{2dx}{(2x-\sqrt3)^2+1}=$$
$$\tan^{-1}(2x+\sqrt3)+\tan^{-1}(2x-\sqrt3)$$


text:
Q: Proof of $\frac{1-r^2}{1-2r \cos \theta + r^2}=1+2\sum_{k=1}^{\infty} r^k \cos k\theta$ for $0 < r < 1$ How to prove the following: For $0 < r < 1,$
$$\frac{1-r^2}{1-2r \cos \theta + r^2}=1+2\sum_{k=1}^{\infty} r^k \cos k\theta.$$
I started with writing the left hand side as
$$\frac{1-r^2}{1-2r \cos \theta + r^2}=\textrm{Re} \left( \frac{1+r e^{i \theta}}{1 - r e^{i \theta}} \right),$$
but wasn't successful. Any help is much appreciated.

A: Using polar coordinates you have that $z=r\cos\theta+ ri\sin \theta $ and so by De Moivre's formula $z^k=r^k\cos(k\theta)+ r^ki\sin (k\theta).$ In turn,
$$\sum_{k=1}^\infty r^k\cos(k\theta)+ r^ki\sin (k\theta)=\sum_{k=1}^\infty z^k=\frac{z}{1-z}$$
Now you just have to find the real part of $\frac{z}{1-z}$.

A: The approach in the OP is a good one.  Proceeding we can write
$$\begin{align}
\frac{1+re^{i\theta}}{1-re^{i\theta}}&=(1+re^{i\theta})\sum_{k=0}^\infty r^ke^{ik\theta}\\\\
&=\sum_{k=0}(r^ke^{ik\theta}+r^{k+1}e^{i(k+1)\theta})\\\\
&=1+2\sum_{k=1}^\infty r^ke^{ik\theta}
\end{align}$$
which after taking the real part yields
$$\text{Re}\left(\frac{1+re^{i\theta}}{1-re^{i\theta}}\right)=1+2\sum_{k=1}^\infty r^k\cos(k\theta)$$
as was to be shown!


text:
Q: R: How to combine grouping and colour aesteric in ggplot line plot I am trying to create a line plot with 2 types of measurements, but my data is missing some x values. In Line break when no data in ggplot2 I have found how to create plot that will make a break when there is now data, but id does not allow to plot 2 lines (one for each Type).
1) When I try
ggplot(Data, aes(x = x, y = y,  group = grp)) + geom_line()

it makes only one line, but with break when there is no data

2) When I try
ggplot(Data, aes(x = x, y = y,  col = Type)) +
  geom_line()

it makes 2 lines, but with break when there is no data

3) When I try
ggplot(Data, aes(x = x, y = y,  col = Type, group = grp)) +
  geom_line()

it makes unreadyble chart

4) of course I could combine the Type and grp to make new variable, but then the legend is not nice, and I get 4 groups (and colours) insted of 2.
5) also I could make something like that, but it dose not produce a legend, and in my real dataset i have way to many Types to do that
ggplot() +
      geom_line(data = Data[Data$Type == "A",], aes(x = x, y = y, group = grp), col = "red") +
      geom_line(data = Data[Data$Type == "B",], aes(x = x, y = y, group = grp), col = "blue")

Data sample:
Data <- data.frame(x = c(1:100, 201:300), y = rep(c(1, 2), 100), Type = rep(c("A", "B"), 100), grp = rep(c(1, 2), each = 100))

A: One way is to use interaction() to specify a grouping of multiple columns:
library(ggplot2)

Data <- data.frame(x = c(1:100, 201:300), y = rep(c(1, 2), 100), Type = rep(c("A", "B"), 100), grp = rep(c(1, 2), each = 100))

ggplot(Data, aes(x = x, y = y, col = Type, group = interaction(grp,Type))) +
  geom_line()


text:
Q: Sending multiple JSON request to server under one request nodejs I have some files downloaded and I wanna push them to a server. Every time I try to push the file I get the error
Error: Can't set headers after they are sent.
I have a for loop that reads all the files and parse them and after that I want to send them to the server one by one.
app.get('/dataparser', function(req, res) {
var fs = require('fs');
var obj;
var jsonGis = new Array();
var jsonArray;
var filePaths = [];
const downloadFolder = './sampletest/';
var mtimes = {};
var reloadTimes = 10000;
fs.readdir(downloadFolder, (err, files) => {
    files.forEach(file => {
      filePaths.push("sampletest/" + file);
    });
})
var execFunction = function() {
    for (var i = 0; i < filePaths.length; i++) {
        parseFile(filePaths[i], mtimes[filePaths[i]]);
    }
};
execFunction();
setInterval(execFunction, reloadTimes);
function parseFile(fileName, lastModifiedTime) {
    fs.stat(fileName, function(err, fd) {
            for (var i=0, len = filePaths.length; i<len; i++) {
              if (fd.mtime !== lastModifiedTime) {
                  mtimes[fileName] = fd.mtime;
                  fs.readFile(filePaths[i], function(err, data) {
                    if (err) {
                        return console.error(err);
                    }
                    obj = JSON.parse(data);
                    jsonGis.push('"Person1"');
                    jsonGis.push('"' + obj.pages[1].answers[2].values[0] + '"');
                    jsonGis.push('"person2"');
                    jsonGis.push('"' + obj.pages[1].answers[0].values[0] + '"');
                    jsonGis.push('"codewals"');
                    jsonGis.push('"42343GSDS"');
                    jsonGis.push('"geometry":{');
                    jsonGis.push('"x":' + obj.pages[1].answers[4].values[0].coordinates.latitude + ',');
                    jsonGis.push('"y":' + obj.pages[1].answers[4].values[0].coordinates.longitude);
                    var str = "[{ " + jsonGis[0] + jsonGis[1] + jsonGis[2] + ": " + jsonGis[3] + "," + jsonGis[4] + ": " + jsonGis[16] + "}}]"
                    //pushing to the server
                    console.log("check here");
                    console.log(str);
                    var qs = require("querystring");
                    var http = require("http");
                    var options = {
                        "method": "POST",
                        "hostname": "twst2.gtw.com",
                        "port": null,
                        "path": "localpath/",
                        "headers": {
                            "accept": "application/json",
                            "content-type": "application/x-www-form-urlencoded",
                        }
                    };
                    var req = http.request(options, function(res) {
                        var chunks = [];

                        res.on("data", function(chunk) {
                            chunks.push(chunk);
                        });

                        res.on("end", function() {
                            var body = Buffer.concat(chunks);
                            console.log(body.toString());
                        });
                    });
                    req.write(qs.stringify({features: str}));
                    res.send("The server was updated");
                    req.end();
                  });
            }
        }
    });
};

Just need to send the data to the server from file1.json and then file2.json then file3.json and so on.

A: Try creating a separate callback function that includes .write, .send, and .end, then let it be the callback for .request.


text:
Q: How to apply a polygon mask layer in ggplot I'm looking to crop the density plot to only land while keeping to sf.
Here's a simple example problem:
library(tidyverse)
library(sf)
library(albersusa)
library(ggthemes)
library(jsonlite)

dat <-
  fromJSON(
    "https://services1.arcgis.com/Hp6G80Pky0om7QvQ/arcgis/rest/services/Fortune_500_Corporate_Headquarters/FeatureServer/0/query?where=1%3D1&outFields=LATITUDE,LONGITUDE,NAME,PROFIT&outSR=4326&f=json"
  )

dat <- as.data.frame(dat$features$attributes)

top_50 <- dat %>%
  arrange(desc(PROFIT)) %>%
  head(50)

ggplot() +
  geom_sf(data = usa_sf()) +
  geom_density_2d_filled(aes(x = LONGITUDE, y = LATITUDE),
                         data = top_50,
                         alpha = .5) +
  xlim(-125,-66.5) +
  ylim(20, 50) +
  theme_map() +
  theme(legend.position = "none")

Not sure if I'm getting close to a solution but here's some of the code I've been trying:
test <- (MASS::kde2d(
  top_50$LONGITUDE, top_50$LATITUDE,
  lims =  c(-125,-66.5, 20, 50)
))

ggpoly2sf <- function(poly, coords = c("long", "lat"),
                      id = "group", region = "region", crs = 4326) {
  sf::st_as_sf(poly, coords = coords, crs = crs) %>%
    group_by(!! as.name(id), !! as.name(region)) %>%
    summarize(do_union=FALSE) %>%
    sf::st_as_sf("POLYGON") %>%
    ungroup() %>%
    group_by(!! as.name(region)) %>%
    summarize(do_union = TRUE) %>%
    ungroup()
}

v <- contourLines(test)
vv <- v
for (i in seq_along(v)) vv[[i]]$group <- i
vv <- do.call(rbind, lapply(vv, as.data.frame))

dsi_sf <- ggpoly2sf(vv, coords = c("x", "y"), region = "level") %>% st_as_sf()

usa <- usa_sf()

dsi_i_sf <- st_intersection(usa$geometry, dsi_sf)

ggplot() +
  geom_sf(data=usa) +
  geom_sf(data=dsi_i_sf,color="red") +
  geom_density2d_filled(aes(x = LONGITUDE, y = LATITUDE),
                 data = top_50,alpha=.4) +
  xlim(-125,-66.5) +
  ylim(20, 50) +
  theme(legend.position = "none")

A: Create a rectangle of the same plot dimensions:
rec_box <- data.frame(x=c(-125,-125,-66.5,-66.5,-125), y=c(20,50,50,20,20))

Create an outline of the US and extract only the lat/lon points into a dataframe:
outline <- map("usa", plot=FALSE)

outline <- data.frame(x=outline$x,y=outline$y)

Bind the two together to create a polygon with a hole in the middle:
mask <- rbind(rec_box,outline)

Add a geom_polygon() to plot the mask data and color appropriately:
  geom_polygon(data=mask,
                aes(x=x,y=y),color="white",fill="white")

Everything combined:
library(tidyverse)
library(sf)
library(albersusa)
library(ggthemes)
library(jsonlite)

dat <-
  fromJSON(
    "https://services1.arcgis.com/Hp6G80Pky0om7QvQ/arcgis/rest/services/Fortune_500_Corporate_Headquarters/FeatureServer/0/query?where=1%3D1&outFields=LATITUDE,LONGITUDE,NAME,PROFIT&outSR=4326&f=json"
  )

dat <- as.data.frame(dat$features$attributes)

top_50 <- dat %>%
  arrange(desc(PROFIT)) %>%
  head(50)

usa <- usa_sf()

outline <- map("usa", plot=FALSE)

outline <- data.frame(x=outline$x,y=outline$y)

rec_box <- data.frame(x=c(-125,-125,-66.5,-66.5,-125), y=c(20,50,50,20,20))

mask <- rbind(rec_box,outline)

ggplot() +
  geom_sf(data = usa_sf()) +
  geom_density_2d_filled(aes(x = LONGITUDE, y = LATITUDE),
                         data = top_50,
                         alpha = .5) +
  xlim(-125,-66.5) +
  ylim(20, 50) +
  geom_polygon(data=mask,
                aes(x=x,y=y),color="white",fill="white") +
  theme_map() +
  theme(legend.position = "none")

Really a thing of beauty.

A: For a mask layer over the US with AK & HI inset:
library(tidyverse)
library(sf)
library(albersusa)
library(ggthemes)
library(jsonlite)
library(spatstat)

dat <-
  fromJSON(
    "https://services1.arcgis.com/Hp6G80Pky0om7QvQ/arcgis/rest/services/Fortune_500_Corporate_Headquarters/FeatureServer/0/query?where=1%3D1&outFields=LATITUDE,LONGITUDE,NAME,PROFIT&outSR=4326&f=json"
  )

dat <- as.data.frame(dat$features$attributes)

top_50 <- dat %>%
  arrange(desc(PROFIT)) %>%
  head(50)

usa <- usa_sf()

top50sf <- st_as_sf(top_50, coords = c("LONGITUDE", "LATITUDE")) %>%
  st_set_crs(4326) %>%
  st_transform(st_crs(usa))

# usa polygons combined
usa_for_mask <- usa_sf() %>%
  st_geometry() %>%
  st_cast('POLYGON') %>%
  st_union()

# bounding box of us & inset AK + HI,
# expand as needed
us_bbox <- st_bbox(usa_for_mask) %>%
             st_as_sfc() %>%
             st_as_sf()

us_mask <- st_difference(us_bbox, usa_for_mask)

ggplot() +
  geom_sf(data = usa) +
  geom_density_2d_filled(aes(x = LONGITUDE, y = LATITUDE),
                         data = top_50,
                         alpha = .5) +
  geom_sf(data = us_mask, fill = 'white') +
  xlim(-125,-66.5) +
  ylim(20, 50) +
  theme_map() +
  theme(legend.position = "none")

Created on 2021-04-05 by the reprex package (v1.0.0)
You can expand the bounding box to get rid of the purple border around the plot.
This does what you're asking for, but almost certainly isn't spatially accurate.  It can get a point across to a general audience, but don't make any big decisions based on it.
More accurate spatial interpolation methods can be found here:
https://rspatial.org/raster/analysis/4-interpolation.html
https://mgimond.github.io/Spatial/interpolation-in-r.html


text:
Q: Variable number of CollectionContainers in CompositeCollection Lets say I have a Canvas on which I want to display a number of X and Y samples which belong to a variable number of groups.
I have a ViewModel which has an ObservableCollection of groups. I can display all samples of a  chosen group by binding an itemscontrol to one of the classes. But now I want to show all samples of a the groups combined. I've found the CompositeCollection which allows this, but I cant seem to find out how to bind the groups collection to the CompositeCollection so I can add and remove groups and automaticly update the canvas.

A: CollectionViewSource supports the concepts of groups, and the HierarchicalDataTemplate supports the display of hierarchical data. Between the two you should be able to create a solution in my opinion


text:
Q: UICollectionViewCell alpha not changing when using '.reloadItems' I have been using UICollectionView.reloadData() to update my cells on the fly and this has worked perfectly, although, it causes the animation to be extremely clunky. I hook into func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell and perform logic to determine the cells UI.
Here is that methods code:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RepCollectionViewCell", for: indexPath) as! RepCollectionViewCell

        let mask = CAShapeLayer()
        let path = UIBezierPath(arcCenter: CGPoint(x: cell.bounds.midX, y: cell.bounds.midY),
                                radius: cell.bounds.width / 2, startAngle: -CGFloat.pi / 2, endAngle: 2 * .pi, clockwise: true)

        path.close()

        mask.frame = cell.bounds
        mask.path = path.cgPath

        var alpha = 1.0
        var color = UIColor.white
        var size = 0.0

        switch reps[indexPath.row] {
        case currentRep + 3:
            size = FONT_SIZE / 4
        case currentRep + 2:
            size = FONT_SIZE / 3
        case currentRep + 1:
            size = FONT_SIZE / 2
        case currentRep:
            color = .green
            size = FONT_SIZE
        case currentRep - 1:
            size = FONT_SIZE / 2
            alpha = 0.75
        case currentRep - 2:
            size = FONT_SIZE / 3
            alpha = 0.50
        case currentRep - 3:
            size = FONT_SIZE / 4
            alpha = 0.25
        default:
            color = .clear
            alpha = 0
        }

        cell.layer.mask = mask
        cell.repCount.text = String(reps[indexPath.row])
        cell.backgroundColor = color
        cell.repCount.font = UIFont(name: FONT_NAME, size: CGFloat(size))
        cell.alpha = CGFloat(alpha)

        return cell
    }

Now as mentioned the alpha is set correctly when using UICollectionView.reloadData() but, when I use the UICollectionView.reloadItems(at: [IndexPaths]) method and pass an array of indexPaths, the cells alpha does not update. However, the background colour, font size, contentView alpha etc... will update.
Here is the code I am using to generate the indexPaths of the cells that need to be updated and the subsequent call.
private func focusCollectionView()
    {
        self.MyUICollectionView.reloadItems(at: generateIndexPaths())
        self.MyUICollectionView.scrollToItem(at: IndexPath(item: myVar - 1, section: 0), at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
    }

    private func generateIndexPaths() -> [IndexPath]
    {
        var indexPaths = [IndexPath]()

        if(myVar - 4 >= 0)
        {
            indexPaths.append(IndexPath(row: myVar - 4, section: 0))
        }
        if(myVar - 3 >= 0)
        {
            indexPaths.append(IndexPath(row: myVar - 3, section: 0))
        }
        if(myVar - 2 >= 0)
        {
            indexPaths.append(IndexPath(row: myVar - 2, section: 0))
        }
        if(myVar - 1 >= 0)
        {
            indexPaths.append(IndexPath(row: myVar - 1, section: 0))
        }

        indexPaths.append(IndexPath(row: myVar, section: 0))

        if(myVar + 1 < _myOtherVar)
        {
            indexPaths.append(IndexPath(row: myVar + 1, section: 0))
        }
        if(myVar + 2 < _myOtherVar)
        {
            indexPaths.append(IndexPath(row: myVar + 2, section: 0))
        }
        if(myVar + 3 < _myOtherVar)
        {
            indexPaths.append(IndexPath(row: myVar + 3, section: 0))
        }

        return indexPaths
    }

Here is a demo of the two results, the first using 'reloadData'and the second using 'reloadItems': https://imgur.com/a/ECOnYIj
I do not know why this is occurring and what to do to fix it, any ideas?

A: As far as I understood the background color should show through? Or did I misunderstood the intention?
So testing with your code it seems alpha for the cell is not applied, see

Idea
Setting the backgroundColor of the cell to .clear would allow us to use the alpha of the contentView and we could still see the background through.
To Test it
In UICollectionViewController subclass I used:
self.collectionView.backgroundColor = .black

I slightly modified your code here (like suggested by rmaddy in his answer):
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
...
cell.myLabel.text = String(reps[indexPath.row])
cell.contentView.alpha = 1
...

Then changed each

*

*cell.backgroundColor = to cell.contentView.backgroundColor =

*cell.alpha = to cell.contentView.alpha =
In MyUICollectionViewCell I set the backgroundColor of the cell to UIColor.clear:
self.backgroundColor = .clear

Besides that, the code for the CollectionViewCell is rather uninteressting, here just for reference:
class MyUICollectionViewCell: UICollectionViewCell {

    let myLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        self.contentView.addSubview(self.myLabel)
        self.myLabel.textAlignment = .center
        self.myLabel.snp.makeConstraints { (maker) in
            maker.edges.equalToSuperview()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

In my test case myVar is the index of the selected item, so I removed the -1 in scrollToItem, so that it looks like this:
private func focusCollectionView()
{
    self.collectionView.reloadItems(at: generateIndexPaths())
    self.collectionView.scrollToItem(
        at: IndexPath(item: myVar, section: 0),
        at: .centeredHorizontally,
        animated: true)
}

Demo
So when testing it in the simulator it looks like this:

Is this what you were looking for?


text:
Q: What does rotating the compass do? I've unlocked field E3, it has a little compass on it, if I click on the compass, I can change the direction it's pointing at, after rotating it a full circle I got an achievement. Bombing it didn't seem to do anything at all.
What use does this compass have? I'm assuming it has some effect in the game, especially since it also shown on the world map that the level has a compass. What do I have to do to get it to do something?

A: Yes, the compasses do something.

 When you set the compasses correctly

the reward is

 five fields, when beaten, will each yield 1 talisman fragment of set rarity

after that, the compasses have no effect.

A: There are 7 compasses in the game. Each must be set to a specific direction (random by game, so yours will be different from mine.)

 On the load screen you will see 7 gems... if they are level 5 gems they are correct, otherwise they are wrong. Each gem corresponds to a different compass.

It's worth mentioning you do NOT have to beat (or even play) the level to change the compass setting, merely load the level, change the compass and then reload the level to see if you got it correct.


text:
Q: Attach file in php and inserting in a database this is a normal HTML method of attaching a file.
form enctype=<"multipart/form-data" action="savefile.php" method="POST" name="myform">
Send this file:
 input name="myfile" type="file" onchange="document.forms['myform'].submit() ;"

</form>

savefile.php
move_uploaded_file($_FILES["myfile"]["tmp_name"],

"upload/" . $_FILES["myfile"]["name"]);

echo "Stored in: " . "upload/" . $_FILES["myfile"]["name"];

it works perfectly, my difficulty is that when I attach a file and it sends when I refresh the page, the file I attached still remains in the attachment,  how can I clear it so it shows "No chosen file"

A: You need to redirect the user with
 header("Location: yourpage.php");

Also, submitting your form that way might not work on every browser.

A: <input name="myfile" type="file" onchange="document.forms['myform'].submit() ;" />

And JAVASCRIPT
var myInput = $("#input[name='myfile']");

function resetInput(){
    myInput.replaceWith( myInput.val('').clone( true ) );
};

Call resetInput() after the upload.
Ripped and adapted From this thread


text:
Q: Get Kubuntu 18.04.3 multi-monitor support to launch apps in primary screen? Setting up a 2nd display(HDMI output) on a laptop(Lenovo z70) with NVidia card/drivers( Kubuntu 18.04.3 ) and in the Display settings I setup the 2nd monitor to be above the laptop/Primary display(attached above in Display settings dialog).
But when I start a new application, they start on the 2nd screen.  Only if I setup my screen layout so my laptop(Primary) screen is to the left of the 2nd screen does it function with apps starting on the primary screen.
Running rxandr didn't change anything:
PRIMARY="eDP-1-1"
SECONDARY="HDMI-1-1"
xrandr --output ${PRIMARY} --primary --mode 1920x1080 --pos 0x0 --rotate normal \
       --output ${SECONDARY} --mode 1920x1080 --above ${PRIMARY} \
       --output DP-1-1 --off \
       --output HDMI-1-2 --off
The ONLY way I've found to get this to work mostly as 'expected' is to right click on an app's Title bar, More Actions -> Special Window Settings -> Initial Placement - Force - Under Mouse
So why does the "primary" screen setting work only when it is to the left of the other screen(s) and is there a way to get this to work besides forcing through multiple menu levels off an app title bar?


text:
Q: sizeof(function_name) I tried sizeof(printf) , sizeof(foobar) etc. where foobar is a user defined function. It returns 1 without any warning or error. Why 1?

A: The size of functions is not well defined in C, so the value is meaningless.


text:
Q: How can I view images smaller than the typical thumbnail size at their original size? I'm using 20.04 and I've noticed something that I really don't like about it: in Pictures, small images such as pixel art or icons are scaled-up as thumbnails. This is annoying because I remember using an older version of Ubuntu and it never had that issue: when the images were the same size as the thumbnails or smaller, they would render in the file manager at their actual size i.e. each pixel of the image would be shown as a pixel on screen. I don't like having small pictures scaled-up and all blurry: it looks awful, and I actually find that images used as icons (like the ones used with html files so that your page has a tiny image on its tab) are actually harder to see correctly when they are scaled-up because aside from blur, you're also looking at anti-aliasing at a scale where it doesn't work.
Is there a way of configuring nautilus so that the thumbnails can be made from larger images scaled-down, but small images are not scaled-up? Or alternatively, if there isn't a way of configuring nautilus to do this, is there another file manager where there is?