text:
Q: getting error in android application: Attempt to invoke interface method on a null object reference I have Three radio buttons inside radiogroup and want, when user check any radio button it must be remain checked until user check any other button (either user close the app or not) and for this purpose I has used sharedPreferences to store this selected checkbox value and retrieve when activity is loaded, but getting error when I loads the activity for selecting checkbox. Below is my code.
Activity.java:
public static SharedPreferences pref;
public static String lang;
public static String chk;
public static RadioButton gujarati;
public static RadioButton hindi;
public static RadioButton english;
public static EditText txtV;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.select_language);
//
//  String chk = pref.getString("key_name", null);
//  if(chk=="Gujarati"){
//      gujarati.setChecked(true);
//  }
//  else if(chk=="Hindi"){
//      hindi.setChecked(true);
//  }
//  else{
    //  english.setChecked(true);
    //}
    //editor.remove("key_name3"); // will delete key key_name3
    //editor.remove("key_name4"); // will delete key key_name4

    // Save the changes in SharedPreferences
    //editor.commit(); // commit changes
    //editor.clear();
     //editor.commit();

    RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
    gujarati = (RadioButton) findViewById(R.id.radio0);
    hindi = (RadioButton) findViewById(R.id.radio1);
    english = (RadioButton) findViewById(R.id.radio2);
    txtV = (EditText) findViewById(R.id.editText1);

    //int radio_selected = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE).getInt("my_selected_radio",0);
    //int radio_selected = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE).edit().putInt("my_selected_radio",selectedValue).commit();
    chk = pref.getString("key_name", null);

    if(chk == "Gujarati"){
        gujarati.setChecked(true);
    }
    if(chk == "Hindi"){
        hindi.setChecked(true);
    }
    if(chk == "English"){
        english.setChecked(true);
    }

    group.setOnCheckedChangeListener(new OnCheckedChangeListener(){

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            if(checkedId == R.id.radio0) {
                lang = "Gujarati";
                pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                Editor editor = pref.edit();
                editor.putString("key_name", lang);
                editor.commit();
                chk = pref.getString("key_name", null);
                txtV.setText(chk);

            } else if(checkedId == R.id.radio1) {
                lang = "Hindi";
                pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                Editor editor = pref.edit();
                editor.putString("key_name", lang);
                editor.commit();
                chk = pref.getString("key_name", null);
                txtV.setText(chk);
            } else {
                lang = "English";
                pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                Editor editor = pref.edit();
                editor.putString("key_name", lang);
                editor.commit();
                chk = pref.getString("key_name", null);
                txtV.setText(chk);

            }

        }

    });

activity.xml:
<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="25dp" >

    <RadioButton
        android:id="@+id/radio0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="RadioButton" />
</RadioGroup>

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioGroup1"
    android:layout_below="@+id/radioGroup1"
    android:layout_marginLeft="15dp"
    android:ems="10" >

    <requestFocus />
</EditText>

Logcat:
01-05 04:21:35.055: E/AndroidRuntime(2665): FATAL EXCEPTION: main
01-05 04:21:35.055: E/AndroidRuntime(2665): Process: com.finaldbparse.finaldbparse, PID: 2665
01-05 04:21:35.055: E/AndroidRuntime(2665): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.finaldbparse.finaldbparse/com.finaldbparse.finaldbparse.SelectLanguage}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.os.Looper.loop(Looper.java:135)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.ActivityThread.main(ActivityThread.java:5221)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at java.lang.reflect.Method.invoke(Native Method)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at java.lang.reflect.Method.invoke(Method.java:372)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
01-05 04:21:35.055: E/AndroidRuntime(2665): Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference
01-05 04:21:35.055: E/AndroidRuntime(2665):     at com.finaldbparse.finaldbparse.SelectLanguage.onCreate(SelectLanguage.java:55)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.Activity.performCreate(Activity.java:5933)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
01-05 04:21:35.055: E/AndroidRuntime(2665):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
01-05 04:21:35.055: E/AndroidRuntime(2665):     ... 10 more

A: Here:

chk = pref.getString("key_name", null);

1. You are not initializing pref instance of SharedPreferences but calling getString method. do it as:
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
chk = pref.getString("key_name", null);

2. Use String.equals for comparing Strings instead of ==
3. Initializing pref  in onCreate method then no need to initialize again as currently you are doing in setOnCheckedChangeListener

A: You got NPE because pref=NULL at

chk = pref.getString("key_name", null);

initialize pref before the used. do like
pref = getApplicationContext().getSharedPreferences("MyPref", 0); in onCreate(....)

A: As you have implemented an onCheckedChangeListener event which is always gets called automatically whenever your activity starts. So the problem occurs is though your sharedpreference value is correct you are getting but after that immediately your CheckedChangeListener is called so the value which you have from your preference gets reset and you are getting incorrect result.
That is why i have removed the old value whenever you are going to check another radio button.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.select_language);

    group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            pref = getApplicationContext().getSharedPreferences("MyPref", 0);
            Editor editor1 = pref.edit();
            editor1.remove("key_name");
            if (checkedId == R.id.radio0) {
                lang = "Gujarati";
                pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                Editor editor = pref.edit();
                editor.putString("key_name", lang);
                editor.commit();
                // chk = pref.getString("key_name", null);
                txtV.setText(lang);

            } else if (checkedId == R.id.radio1) {
                lang = "Hindi";
                pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                Editor editor = pref.edit();
                editor.putString("key_name", lang);
                editor.commit();
                // chk = pref.getString("key_name", null);
                txtV.setText(lang);
            } else if (checkedId == R.id.radio2) {
                lang = "English";
                pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                Editor editor = pref.edit();
                editor.putString("key_name", lang);
                editor.commit();
                // chk = pref.getString("key_name", null);
                txtV.setText(lang);

            }
        }

    });

    pref = getApplicationContext().getSharedPreferences("MyPref", 0);
    chk = pref.getString("key_name", null);
    System.err.println("Get value is=====" + chk);
    if (chk != null) {
        if (chk.equals("Gujarati")) {
            gujarati.setChecked(true);
        }
        if (chk.equals("Hindi")) {
            hindi.setChecked(true);
        }
        if (chk.equals("English")) {
            english.setChecked(true);
        }
    }
}


text:
Q: javafx + javascript on desktop app I don't have any experience in JavaFX and I know a little about javascript. I want to develop a desktop app in JavaFX and adding some javascript functionality in JavaFX code. I have a .js file with the functions I need to use, but I don't know how to use them.
What are the main steps for doing it? I've been told it is possible

A: You can use scripting and script event handlers in an fxml document.
You can also embed a WebView to process HTML and JavaScript.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oscillation coil: where is the electric field? Let assume a simple RF coil fed with an alternating current at RF frequencies, say 100MHz.
I believe that no one doubts that the coil will radiate RF energy in the form of radio waves.
A radio wave is classically composed of an electric vector and a magnetic vector orthogonal one to the other.
Now, let assume a low frequency big coil, say, for magnetic induction, and assume it is fed by a low frequency current (e.g. 1 KHz). An oscillating magnetic field will be perceived near the coil, but I've never heard that the coil also radiates a sensible electric field. Yet, there is no difference with the former RF coil, but the frequency. So, my question is: why is there no sensible electric field radiated by the low frequency coil?

A: One has to distinguish the near field (i.e., the field near the coil) and the far field, i.e., the propagating electromagnetic waves far away from the coil (far away on the scale of the wave length). The major factors that determine whether the oscillating electric current will produce a propagating electromagnetic wave are:

*

*the damping should be weak

*the energy of the electromagnetic wave should be substantial to be detected and to be of interest for practical applications (otherwise you will never hear about it).

Kilohertz frequency waves have wave lengths of several hundred kilometers - too long to be of practical use, and even to be generated by conventional methods (which typically require an antenna of half-wave length size). Yet, such waves are known to exist in the atmosphere and can be rather easily detected (to the extent that in some universities their detection is a subject of an undergraduate lab experiments). They go under the name of whistlers.

A: Since the magnetic field is varying with time, by Maxwell-Faraday's induction law there is a rotation of the electric field. One can then distinguish the propagating and the non-propagating part but that is outside the scope of the question.

A: There is no fundamental difference between 1 kHz, 100kHz or higher frequencies. RF coil may radiate a lot or very little (see magnetic resonance imaging), it depends on how the coil is used.
Oscillating current always produces some waves, but whether it is useful or strong enough for some purpose depends on details. Two of those details are 1) EM wave strength, 2) ease of propagation, 3) information throughput. 1),3) get better with increasing frequency, but 2) gets worse. So some finite frequency windows are used for different uses.
As a general rule of thumb, assuming fixed current amplitude, the higher is the frequency, the higher the amplitude of emitted waves. This is because the higher the frequency, the greater is the acceleration of mobile charges which is what produces electric and magnetic field of EM waves.
Also, with higher frequency information throughput is better because of larger frequency bandwidth available. But too high frequencies propagate badly over obstacles and over long distances, they cannot use ionosphere reflections for long distance propagation, they do not penetrate seawater well etc. So one can't just use GHz or higher frequencies for everything. Along Earth's surface lower frequencies <GHz propagate better.
If the frequency gets very low, radiation intensity of a given emitter gets very low as well and is easily drowned by EM noise, so it is not very common to encounter kHz or slower transmitters/receivers. It is possible to run such low frequency transmitters but to make them effective requires that they are very big (comparable to radiation wavelength). One well known example is the VLF communication with submarines which uses many kilometer long antennae.
https://en.wikipedia.org/wiki/Very_low_frequency


text:
Q: Spring mvc ZonedDateTime conversion to UTC I woudl ike to convert all java8 ZonedDateTimes into UTC time zone on the server side of the application.  I am successfully binding the Java 8 jsr310 date data types into a spring RestController using the @DateTimeFormat.
@RequestMapping(value = "rest/test-date", method = RequestMethod.GET)
public TestCollection findPrivilegesByRoleList(
        @RequestParam(value = "local-date", defaultValue = "2015-05-10") @DateTimeFormat(iso = ISO.DATE) LocalDate requestParamDate,
        @RequestParam(value = "local-date-time", defaultValue = "2015-05-16T15:55:56") @DateTimeFormat(iso = ISO.DATE_TIME) LocalDateTime requestParamLocalDateTime,
        @RequestParam(value = "zoned-date-time", defaultValue = "2015-05-18T11:55:56-04:00") @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime requestParamZonedDateTime
        )

For the ZonedDateTime class, I would like to shift all input ZonedDateTimes to UTC time, so the server side is always working in UTC timezone.   Following best practice #3 - Store it in UTC
http://apiux.com/2013/03/20/5-laws-api-dates-and-times/#comments
For JSON deserialization, I have a custom deserializer for ZonedDateTime that shifts any timezone into UTC.
....
//Parse string into a zoned date time with the specified timezone offset - EST, CET, EDT, PST, ect.
ZonedDateTime zonedDateTimewithTimeZone = ZonedDateTime.parse(string, formatter);

//Shift the date time  to UTC Time
return zonedDateTimewithTimeZone.withZoneSameInstant(ZoneId.of("UTC"));

What is the best way to do the conversion in the controller binding?  I understand this may be forcing multiple responsibilities into the same class, however I want to avoid adding the
ZonedDateTime.withZoneSameInstant
call for every date in every controller.
Thanks


text:
Q: Use Java Reflection to find sum of parameters from list of objects I have a list of Items...
public class Item implements Serializable {
   private Double subTotalCash;
   private Double subTotalCredit;
   private Double totalShipping;
   private Double grandTotal;

   private Integer countSubItems;
   private Integer countSomethingElse;
   private Integer countMoreThingsNotListedHere;

   ...
   // getters and setters here
}

All the parameters that matter are Double, Integer, Float, or Long (all extend Number)
What I want to do is to sum each of the parameters and total them up in one 'Master' Item.
Item masterItem = new Item();
for(Item item:items) {
   addValuesFromItemToMaster(item, master);
}

If it was only a dozen or so values It'd be no big deal, but we're talking about a bunch of parameters and they change frequently enough that I don't want to have to remember to update this code when the Item object changes....So my thought was that I'd use reflection to get all the fields that are assignable from Number and and sum them but how do I do the actual addition?
private void addValuesFromItemToMaster(Item child, Item master) throws Exception {
    if(child == null || master == null) return;

    Field[] objectFields = master.getClass().getDeclaredFields();
    for (Field field : objectFields) {
        if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue; // don't add any static fields
        if(!Number.class.isAssignableFrom(field.getType())) continue;  // If this is not a numeric field
        if(field.getType() == AtomicInteger.class || field.getType() == AtomicLong.class || field.getType() == Byte.class || field.getType() == BigInteger.class) continue;

        Number childValue = (Number)PropertyUtils.getProperty(child, field.getName());
        Number masterValue = (Number)PropertyUtils.getProperty(master, field.getName());

        if(childValue == null) continue;
        if(masterValue == null) masterValue = childValue;

        // is there something I can put here to get the masterValue += childValue?
        // is there a way to cast to the field.getType()?

        BeanUtils.setProperty(master, field.getName(), n);
    }
}

A: // is there something I can put here to get the masterValue += childValue?
// is there a way to cast to the field.getType()?
// setMethod.invoke(master, newValueGoesHere);

Yes, there is:
if (field.getType() == Integer.TYPE || field.getType() == Integer.class) {
    Integer i = masterValue.intValue() + childValue.intValue();
    setMethod.invoke(master, i);
} else if (field.getType() == Long.TYPE || field.getType() == Long.class) {
    Long l = masterValue.longValue() + childValue.longValue();
    setMethod.invoke(master, l);
} else if (field.getType() == Float.TYPE || field.getType() == Float.class) {
    Float f = masterValue.floatValue() + childValue.floatValue();
    setMethod.invoke(master, f);
} else if (field.getType() == Double.TYPE || field.getType() == Double.class) {
    Double d = masterValue.doubleValue() + childValue.doubleValue();
    setMethod.invoke(master, d);
}

A: You can use BeanUtils rather than straight reflection API. With BeanUtils, ensure your class conform to JavaBean rule, and use public static Map describe(Object bean) to get a list of property available on given bean.
Once you get the name of properties, you can get inidividual value by using public static String getProperty(Object bean, String name) and sum it all up


text:
Q: Reusable and customizable charting library on top of d3js I have started building a charting library on top of d3js using javascript's inheritance. My goal is to develop reusable and fully customizable chart components. I read the article: Towards Reusable Charts. Then, I went through the source code of nvd3.
NVD3 uses boiler plate code in each chart like: copying and pasting definitions for width, height, margin etc. BUT I would rather use inheritance to avoid such boiler plate code. I would like properties like: dimensions, axes and functions like zooming and event listeners to be reusable among all charts and customizable through any instance (object) of the chart.
Here is what my current library looks like. (It only supports bubble chart for now.)
var BaseChart = function(){
    this.width = 200;
    this.height = 200;//and others like: margin/ chart title
}

//XYChart inherits from BaseChart
var XYChart = function(){
    //It contains members for axes, axis groups, labels, ticks, domains and ranges
    //Example: One of the members it contains is "this.yAxis"
    this.yAxis = d3.svg.axis().scale(this.scaleY)
            .orient("left")
            .ticks(this.yTickCnt)
            .tickSize(-this.width);
}

//Extends XYChart and adds zooming
var ZoomableXYChart = function(){
    this.zoom = function(){
        this.svg.selectAll(this.dataShape)
            .attr("transform", function(d, i) {
                var translate = that.calculateTranslation(d);
                return "translate(" + translate.x + "," + translate.y + ")";
            });
    }
}

//Extends zoomable XY chart and adds support for drawing shapes on data points
var BubbleChart = function(){
    this.dataShape = "path";

    this.drawChart = function()
    {
        this.prepareChart();//Attaches zooming, draws axes etc.
        var that = this;
        this.svg.selectAll(that.dataShape)
            .data(that.data)
            .enter()
            .append(that.dataShape)
            .attr("transform", function(d) {
                return that.transformXYData(d);
            })
            .attr("d", symbolGenerator().size(100).type(function(d) {
                return that.generateShape(d);
            }))
            .attr("fill", function(d) {
                return that.generateColor(d);
            })
            .on("click", function(d) {
                that.onClickListener(this, d);
            })
    }
}

I can create a chart in this way:
var chart = new BubbleChart();
chart.data = someData;
chart.width = 900;
chart.elementId = "#myChart";
chart.onClickListener = function(this,d){}
chart.drawChart();

This solution allows me to use common properties and functions across all charts. In addition to that, it allows any instance of any chart to override default properties and functions (like: onClickListener).
Do you see any limitations with such a solution? I haven't really seen javascript's inheritance used for d3.js and I wonder why? Is "chaining" that important? Using Mike Bostock's suggestions, how can we share functions like zooming across all XY charts? Isn't inheritance absolutely necessary to share functions and properties?


text:
Q: Let $f(x)=x^n+p_1x^{n-1}+p_2x^{n-2}+ ...+p_n.$ The positive roots of the equation $f(x)=0$ do not exceed $\sqrt[r]{p}+1$ where $-p$ is the greatest Let $$f(x)=x^n+p_1x^{n-1}+p_2x^{n-2}+ ...+p_n.$$The positive roots of the equation $f(x)=0$ do not exceed $\sqrt[r]{p}+1$ where $-p$ is the greatest negative coefficient and $p_r$ is the first negative coefficient of $f(x)$.
The proof given is as follows :

Any value of $x$ that make $x^n>p(x^{n-r}+x^{n-r-1}+...+1)$ will make $f(x)$ positive . Let $x>1$ . Then, $x^n>p(x^{n-r}+x^{n-r-1}+...+1)$ will hold if $x^n>p\frac{x^{n-r+1}-1}{x-1}$ i.e , if $x^n>p\frac{x^{n-r+1}}{x-1}$ i.e if $x^{r-1}(x-1)>p$ i.e if $(x-1)^r>p$ i.e if $x>\sqrt[r]{p}+1$.

However, in the proof given above I am not getting how are they asserting the fact"Any value of $x$ that make $x^n>p(x^{n-r}+x^{n-r-1}+...+1)$ will make $f(x)$ positive" . I do not get how they are drawing this conclusion .

A: If all coefficients are positive, there will be no positive roots. So some of the coefficients are negative. The first negative coefficient is $p_r$. Let us assume $p$ positive. We also assume $-p$ as the greatest negative coefficient.
$x^n+p_1x^{n-1}+p_2x^{n-2}+ ...+p_r x^{n-r} + \cdots +p_n \ge x^n+ p_r x^{n-r} + \cdots +p_n > x^n - p(x^{n-r}+x^{n-r-1}+...+1)$
The first inequality is true because all coefficients till $p_r$ are positive (and $x$ is positive).
The second inequality is true because if we made every negative coefficient equal to the largest negative coeff, we get the worst case.
So now if $x^n - p(x^{n-r}+x^{n-r-1}+...+1) > 0$ then surely $f(x) > 0$.
The rest of the proof follows.


text:
Q: AllowAnyOrigin Cors Not working Axios Vuejs I have a server that I have set up, running in production, we have tons of applications calling this web server. The code below is to demonstrate that it allows any origin requests.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");

        app.UseStaticFiles();

        app.UseCors(builder =>
        {
            builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
        });

This works for all servers currently set up. It's on our internal network, and other servers internally will use this service.
I am creating a proof of concept to try and modernize our Applications slowly by using Vue. Except this axios request is getting an error. The other servers that call this method are using .net as well, but it should build the same request.
Here is the error.

Failed to load https://{server}/api/application/36626: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

This is obviously crazy talk by axios. I allow for any origin. I can't imagine we only want to use 'simple-requests' so the w3 standard for simple requests might not work. I thought maybe this could be an incorrect error considering this is an octet-stream returned from the server. The code is below.
<script>
import axios from 'axios'

export default {
  name: 'AppList',
  data () {
    return {
      applist: [],
      errors: []
    }
  },
  created: function() {
    axios.get('https://{server}/api/application/36626')
      .then(r => { console.log(response); })
      .catch(ex => {
        this.errors.push(ex);
      })
  }
}
</script>

EDIT I have full rights to this machine, I have confirmed I can use a Postman GET request from my local machine with no problem.
Edit 2 Working curl command curl -X GET --header 'Accept: application/octet-stream' 'https://{server}/api/Application/36626'

A: It turns out the .Net Core Server was not set up right, it wasn't until I was trying to use the browser on my local machine did the CORS problem crop up.
I'm not sure if the CORS implementation changed and I was not aware, or if I just wasn't doing it right from the start, but I was sure I followed guides.
The first thing I changed was ensuring that the Cors Policy was added before configuring the app to use MVC.
The second thing I did, and I suspect this is optional, but best practice, I also moved the policy logic to the ConfigureServices method.
My final code looked below. I'm keeping as much in tact to preserve the order.
 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
            services.AddOptions();
            services.AddSwaggerGen();
            ///Authentication configuration went here.
            services.AddSingleton<IConfiguration>(Configuration);
            services.AddMvc();

        }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseExceptionHandler("/Home/Error");
        app.UseStaticFiles();
        app.UseCors("CorsPolicy");

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseSwagger((httpRequest, swaggerDoc) =>
        {
            swaggerDoc.Host = httpRequest.Host.Value;

        });
        app.UseSwaggerUi(swaggerUrl: "/{appname}/swagger/v1/swagger.json");

A: Activating the cors didn't work for me for the PUT and DELETE methods, what I did was add some configuration lines in the web.config file to remove the WebDav module.
I used this inside the existing tag system.webServer tag in the web.config file
<modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
</modules>

I found the lines in this site:
Modify the web.config
https://hovercraft.ie/asp-net-core-web-api-put-delete-methods-not-allowed-405-error/
Hope this helps.


text:
Q: ASP.NET MVC 2 Dynamic QueryString Management I am very new to ASP.NET MVC and currently, I am involved in developing a new application in ASP.NET MVC 2. I am having problem in managing a long querystring parameters that comes from dBase.
For example, in any non-mvc app the following URL works well:
http ://example.com/test.aspx?first_name=fname&last_name=lname&email_id=email&address1=add1&address2=add2&city=city&state=state&zip_code=zip and so on.
The QueryString parameter can be determined on the fly (i.e. at run-time). Now for dynamic QueryString how routing will be done?
Also for a simple URL, the URL will be as follows (in ASP.NET MVC):
http ://example.com/test/id/category
But for above mentioned dynamic & long QueryString how the URL will look like? Will all the QueryString parameters be separated through slash (/)?
Thanks in advance for your help.
Best Regards,
Vikas Anand

A: Your url would look like this:
http ://example.com/test/id/category?first_name=fname&last_name=lname&email_id=email&address1=add1&address2=add2&city=city&state=state&zip_code=zip

A: You could write a route in your global.asax. assuming the order of the query params never change and are always present. This example assumes HomeController:
routes.MapRoute
(
"myExample", // route name
"Home/Test/{id}/{first_name}/{last_name}/{email_id}/{address1}/{address2}/{city}/{state}/{zip}, // url pattern
new { controller = "Home", action = "Test", id = "", first_name = "", last_name = "", email_id = "", address1" = "", address2 = "", city = "", state = "", zip = "" } // param defaults
);

HomeController/Test
public ActionResult Test(int id, string first_name, string last_name, int email_id, string address, string address2, string city, string state, string zip) {}


text:
Q: Creating a Mock for HTTPMethods In my controller I have a line of code like this
string method = HttpContext.Request.HttpMethod;

and based on if it is a GET or POST, method is doing different things that I want test.  But first I should be able to mock this.  We are using NSubstitute.
I did some research and the closest I found was this answer but none of them are using NSubstitue.
Mocking Asp.net-mvc Controller Context
Any help is appreciated.

A: Creating mocks and configuring return values is described in the NSubstitute documentation.
So we can create a mock IFoo using:
var foo = Substitute.For<IFoo>();

We can configure a member to return a specific value using Returns:
// Make HttpMethod property return "GET"
foo.HttpMethod.Returns("GET");

// Make someOtherMock.GetFoo() return foo
someOtherMock.GetFoo().Returns(foo);

And we can inject a mocked value into another class:
var x = new Context(foo, ... );

I think that's everything required to port the linked code examples1. If you need any more info please comment and I'll update the answer.

1 I'm avoiding posting the full translation as it probably varies for different MVC versions. Hopefully this answer will help you port any snippet you need.


text:
Q: How to cast an int's address to char pointer in C? Currently the below code gives me a warning when i try to compile it:
int z;
char *w;
w = &z;
How can i cast &z properly so that w stores the pointer to z's address?

A: Try:
w = (char*) &z;

A: Don't forget that generally casting pointers in C is a bad idea. Sure, there are some times when it is the right thing to do, but we can't see exactly what you're doing here. In most cases there is a better, more portable way to do whatever it is which you are aiming at here.


text:
Q: Display query results in new form after selecting item in listbox I have 2 forms: RoomSelect and RoomActiveSessions.
RoomSelect form contains of listbox (listbox1) and a button (button1). The listbox is binded to a local database table called "Room" and displays 4 different room numbers.
Room table
(PK)RoomID RoomName
CMP2001      room 1
MB20312      room 2
FR45312      room 3
TRY2233      room 4

RoomID is used as a foreign key in aother table, Sessions
(PK)sessionID (FK)roomID sessionStartDate sessionTimeStart sessionTimeEnd
1ACMP2343       CMP2001     09/05/2013          12:00 AM         14:00 PM
2ACMP2343       MB20312     05/05/2013          09:00 AM         11:00 PM
1ACMP3456       TRY2233     15/05/2013          12:00 AM         13:00 PM
2ACMP3456       CMP2001     01/05/2013          10:00 AM         13:00 PM
1ABIO3422       MB20312     30/04/2013          11:00 AM         13:00 PM
2ABIO3422       CMP2001     01/04/2013          14:00 AM         16:00 PM
1ABIO2217       FR45312     12/05/2013          16:00 AM         18:00 PM
2ABIO2217       MB20312     03/05/2013          12:00 AM         14:00 PM

RoomActiveSession form contains of dataGridView where I would like to display my results.
The process should look like this:

*

*User start application on the form RoomSelect.

*User selects the room number and click OK.

*RoomSelect form closes and RoomActiveSession opens with the current sessions displayed for the given room number

I presume that to achieve this I need to use the value from the listbox as a parameter when running a query on a database, but I dont know how to access it. When I try to get it with:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            MessageBox.Show(listBox1.SelectedItem.ToString());
        }

I get System.Data.RowView, not the value from the DB.
I would appreciate some help with my problem
EDIT:
One more question. How can I open a new form after highlighting room number and clicking OK on RoomSelect form?

A: If it's a DataRowView that you're getting, then do this:
if (listBox1.SelectedItem is DataRowView)
{
    DataRowView drv = (DataRowView)listBox1.SelectedItem;
    String s = drv["RoomID"] as String;
    if (!String.IsNullOrEmpty(s))
        MessageBox.Show(s);
}

A bit verbose for your goal, perhaps, but just for demonstration of what is really in that SelectedItem property.


text:
Q: How to Calculate Distance in laravel using lat long How can i calculate distance in laravel5.5 with SQL query ?
My code mention below.
$specialProducts = Products::select('products.id', 'products.name', 'products.product_img', 'products.slug', 'products.price','products.lat','(3959 * ACOS(COS(RADIANS($lat))* COS(RADIANS(22.2765097))* COS(RADIANS(70.792523) - RADIANS(70.7583265))+ SIN(RADIANS(22.2897874))* SIN(RADIANS(22.2765097)))) AS distance')
            ->join('subcategories', 'subcategories.id', '=', 'products.sub_category_id')
            ->join('categories', 'categories.id', '=', 'subcategories.category_id')
            ->join('store', 'store.id', '=', 'products.store_id')
            ->where('products.status', 1)
            ->where('products.special', 1)

            ->orderBy('products.created_at', 'DESC')
            ->get();

A: If you have the values for the latitude and longitude in your DB, then you can get the distance between them using the SQl query as in the below example using raw SQL with DB:raw().
$lat = 41.118491 // user's latitude
$lng = 25.404509 // user's longitude

SELECT *,
( 6371 * acos( cos( radians($lat) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians($lng) ) + sin( radians($lat) )
* sin( radians( latitude ) ) ) )
AS calculated_distance
FROM settings as T
HAVING calculated_distance <= (SELECT distance FROM settings WHERE sid=T.sid)
ORDER BY distance_calc

If you want to get distance in miles instead of kilometers, replace 6371 with 3959.
The calculation process may take a long time so, you might want to cache the result for next use.

A: It is better to do it with php instead of mysql. Check my response here.
https://stackoverflow.com/a/50040011/1262144


text:
Q: How do I configure this Spring project correctly? Me and my team are trying to setup a Spring project, and would like to implement REST services. But when I try to deploy it to tomcat 7, I get an error. Here is the output:
Jan 22, 2012 9:39:34 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Jan 22, 2012 9:39:34 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:niths' did not find a matching property.
Jan 22, 2012 9:39:34 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Jan 22, 2012 9:39:34 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Jan 22, 2012 9:39:34 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 497 ms
Jan 22, 2012 9:39:34 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jan 22, 2012 9:39:34 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.25
Jan 22, 2012 9:39:34 PM org.apache.catalina.startup.ContextConfig webConfig
SEVERE: Unable to determine URL for WEB-INF/classes
javax.naming.NameNotFoundException: Resource /WEB-INF/classes not found
    at org.apache.naming.resources.BaseDirContext.listBindings(BaseDirContext.java:733)
    at org.apache.naming.resources.ProxyDirContext.listBindings(ProxyDirContext.java:546)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1197)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:825)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:300)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1568)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1558)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

Jan 22, 2012 9:39:37 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jan 22, 2012 9:39:37 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Jan 22, 2012 9:39:37 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Jan 22, 2012 9:39:37 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3208 ms

I have tried Googling javax.naming.NameNotFoundException: Resource /WEB-INF/classes not found without luck. I am guessing the project was not deployed at all.
The project is hosted on this GitHub repo.

*

*Deployment descriptor

*The REST controller
I have added a very simple method for testing my application: getBaz(), which I guess would be invoked at localhost:8080/niths/rest/baz.
I am having a hard time figuring out what is missing as this is my first Spring project, and would therefore be grateful if someone skilled in the arts of Spring would point out what's the problem!

A: From your pom.xml file, it seems that you excluded your classes and libs from the generated war :
<warSourceExcludes>WEB-INF/classes/**,WEB-INF/lib/**</warSourceExcludes>

Try again by removing this line.


text:
Q: AWK Script to read from log file I have a requirement to read certain parameters from log file and then update to a database. I am trying to achieve the first part, i.e. to read from log file using awk commands in a shell script
Log file may consists of below lines or more-
[2018-05-22T11:35:17,857] [RQST: rqst_3ADE-5439-598D-1B8B | TB: 9000042] - [588455375] - INFO - com.test.webapp.services.functions.TestTransactionService - Line 769 - requestType="TESTING",partnerName="Test Merchant 123",testId="123456",lob="TEST1_TO_TEST2",tranType="TEST1",paymentType="P2M",amount="110.00",currency="840",processor="CBN",network="TestSend",responseCode="00", acctNumLastFour="0087",binCountry="USA",binCurr="USD"
[2018-05-22T11:35:17,857] [RQST: rqst_2AEF-2339-598D-1B8B | TB: 9000043] - [588455376] - INFO - com.test.webapp.services.functions.TestTransactionService - Line 770 - requestType="TESTING",partnerName="Test Merchant 234",testId="234567",lob="TEST2_TO_TEST3",tranType="TEST2",paymentType="P2M",amount="120.00",currency="850",processor="CBN",network="TestSend",responseCode="00", acctNumLastFour="0087",binCountry="USA",binCurr="USD"
[2018-05-22T11:35:17,857] [RQST: rqst_4EDA-4539-598D-1B8B | TB: 9000044] - [588455377] - INFO - com.test.webapp.services.functions.TestTransactionService - Line 771 - requestType="TESTING",partnerName="Test Merchant 345",testId="345678",lob="TEST3_TO_TEST4",tranType="TEST3",paymentType="P2M",amount="130.00",currency="860",processor="CBN",network="TestSend",responseCode="00", acctNumLastFour="0087",binCountry="USA",binCurr="USD"

I need to apply filters processor and paymentType and retrieve values of the amount, currency, network and responseCode to variables in a shell script which will be inserted into an Oracle DB table.
I am new to ShellScript and AWK and unable to wrap this. I have tried using
awk '/amount/{print}' testAPI.log

however, is returning all rows which have amount.

A: I tried with the three entries in the question, below gives you the output you want
it checks if $5 is paymentType="P2M" and if $8 is having the value processor="CBN" basically, the filter you were looking for, substitute with the required filters you need.
cat testAccelAPI.log | grep -i "[RQST: rqst" | cut -d ' ' -f 19 | awk -F, '{ if($5=="paymentType=\"P2M\"" && $8=="processor=\"CBN\"") print $5 "=" $6 "="$7 "="$8 "=" $9 "="$10}' | cut -d= -f 4,6,8,9 | tr = " "

A: since you didn't specify the expected output, here is a template you can tailor for your needs
$ awk -F' - ' '{n=split($NF,a,",");
                for(i=1;i<=n;i++) {split(a[i],b,"="); kv[b[1]]=b[2]}}
     kv["processor"]=="\"CBN\""
  && kv["paymentType"]=="\"P2M\""{print kv["amount"],kv["currency"]}' file

"110.00" "840"
"120.00" "850"
"130.00" "860"

you can trim the double quotes as well but not sure it's needed as is...


text:
Q: Setting HTML check box to check using javascript I have a constructor that creates a series of checkboxes inside a loop.
I am trying to set the checkboxes to checked, but it is not working.
The code is below:
function customMultiSelect(pDiv, pOptions, inputID, currentSelected)
{
    this.Div = pDiv;
    this.options = pOptions;
    this._initialise();

    for (var idxOption = 0; idxOption < pOptions.length; idxOption++) {

        var checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.style.width = "30px";
        checkbox.style.border = "none";
        checkbox.style.float = "right";

        if (pOptions[idxOption] != "") {
            var arrTemp2 = pOptions[idxOption].split(",");
            var sText = arrTemp2[0];

            if (arrTemp2.length > 1) {
                sText = arrTemp2[1];
            }

            checkbox.value = arrTemp2[0];
            checkbox.id = inputID + "|" + idxOption;
            checkbox.checked = true;
            var textLabel = document.createElement("label");
            textLabel.appendChild(checkbox);
            textLabel.innerHTML += arrTemp2[1];
            textLabel.style.display = "block";
            textLabel.style.clear = "right";

        }

        this.Div.appendChild(textLabel);
    }

}

A: Just put checked attribute instead of checkbox.checked = true; :
checkbox.setAttribute('checked', true);

A: Your problem is because you use textLabel.innerHTML += arrTemp2[1]; so that the HTML is rewritten and parsed. Before that you use checkbox.checked = true only manipulates the DOM property, while in HTML it's only <input type="checkbox">, so the result is textLabel.innerHTML = '<input type="checkbox">' + arrTemp2[1];, gives you an unchecked checkbox again.
You should use checkbox.setAttribute('checked', 'checked'), then the HTML will be <input type="checkbox" checked>, in such case  textLabel.innerHTML += arrTemp2[1]; equals textLabel.innerHTML = '<input type="checkbox" checked="checked">' + arrTemp2[1];

About the difference between HTML attribute and DOM property:
setAttribute actually manipulates the HTML attribute. If a DOM property is not set, the attribute will populate to the property. However, when property is set, change attribute will not affect property. For example you have a input tag:
<input type="text" value="asdf">

And you input something in the field, say "qwer", then you will see the difference
document.querySelector('input').value // "qwer"
document.querySelector('input').getAttribute('value') // "asdf"

And when you change its attribute
document.querySelector('input').setAttribute('value', 'zxcv')

You will not see any change in the page, because document.querySelector('input').value is still "qwer". The change actually takes place in HTML, open devtool you will see:
<input type="text" value="zxcv">

And finally, its the DOM property sent out when you submit a form, not the attribute.


text:
Q: How to pass data-id value of anchor tag to Code-Igniter controller function and show result in data-modal? I'm working on Code-Igniter project and I'm trying to show data on click event of anchor tag. For that I'm passing data-index value using AJAX to Controller and to Model. After that I'm getting result, but the result is not shown in modal-box.
Here is my Code:
View:
<a id="propDetail" name="propDetail" data-toggle="modal"
    data-index="<?= $property->property_id; ?>"
    title="Details of <?= $property->property_code; ?>"
    data-target="#myModal" class="open-Details">
    <?= $property->property_code; ?>

AJAX Code:

I'm putting the value in variable in controller.
Controller Code:
public function index()
    {

        $user = $this->ion_auth->user()->row();
        $data['username'] = $user->username;
        $data['user_id'] = $user->id;

        $id=$this->input->post('property_id');
        $area=$this->input->post('area_id');
        $cluster=$this->input->post('cluster_id');
        if( $area =='') {
            $area =0;
        }
        if($cluster == ''){
            $cluster=0;
        }

        $propDetail = $this->input->post('propDetail');

        $data['areas'] = $this->p->area();
        $data['clusters'] = $this->p->cluster();
        //$data['clusters'] = $this->p->clusterAll($area);
        $data['title'] = 'Property List';

        $data['properties'] = $this->p->getPropertyByAreaCluster($area, $cluster);
        $data['propDetails'] = $this->p->defectsView($propDetail);

        $this->load->view('template/header', $data);
        $this->load->view('Property/property_view', $data);
        $this->load->view('template/footer');
    }

Model Code:
public function defectsView($propDetail)
   {
        $query = $this->db->query("call modalView(?)", $propDetail);
        if ($query) {
            $data = $query->result();
            $query->next_result();
            $query->free_result();
            return $data;
        } else {
            return false;
        }
   }

I'm getting result if I'm passing hard coded value to the procedure (I'm using Stored Procedure).
Here is my Modal view:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Property Datails of

            <?php if($propDetails) {
              foreach ($propDetails as $propDetail) { ?>

                Property Code:
                <?= $propDetail->property_code; ?>

                Defect Added DAte :
                <?= $propDetail->property_added_date; ?>

                Room ASYS No.:
                <?= $propDetail->property_ASYS_no;?>

                Address:
                <?= $propDetail->property_address_1;?>

                Room Count:
                <?= $propDetail->rooms;?>

                Defect Count:
                <?= $propDetail->defects;?>

            <?php } } ?>

Edit:
here is my output:

I'm not getting, where I'm made a mistake. Any kind of help is welcome, Thanks in advance.

A: Since you are sending response via AJAX, you need to echo the output. Else ajax will get blank the response.
Also depending on how you send the response add dataType in ajax.
Eg: is sending html response add dataType:'html', if sending json response add dataType : 'json'
JS CODE :

PHP CODE :
echo $this->load->view('Property/property_view', $data,true);


text:
Q: Is this matrix class thread safe when writing on different indices? As you may notice there is a double* storage behind this. Any value read/written is translated into a flat index so it is stored in a large single dimentional array.
I need to know whether i can write on different indices in an object of this type in different threads? I am using the operator () to set the values. The bounds are predefined when intantiating the object. i.e: Matrix m(rows,cols);
I am using this in boost threads and having issues. Do i need to put any scoped locks? but that would be a performance cost i believe.
class matrix
{
public:
    matrix(size_t rows, size_t cols):_rows(rows),_cols(cols),_data(0)
    {
        reset(rows,  cols);
    }
    matrix():_data(0),_rows(0),_cols(0){}
    ~matrix()
    {
        if (0 != _data)
        {
            delete [] _data;
        }
    }

    matrix(const matrix& copythis)
        :_data(0),_rows(0),_cols(0)
    {
        if (0 != _data)
        {
            delete [] _data;
        }
        _rows = copythis.rows();
        _cols = copythis.cols();
        _data = new double [_rows * _cols];

        if (0 == _data)
        {
            NL_THROW("Insufficient memory to create a cloned matrix of double of " << _rows << " X " << _cols);
        }

        memcpy(_data, copythis._data, _rows * _cols * sizeof(double) );

    }

public:

    const matrix& operator = (const matrix& copythis)
    {
        if (0 != _data)
        {
            delete [] _data;
        }
        _rows = copythis.rows();
        _cols = copythis.cols();
        _data = new double [_rows * _cols];

        if (0 == _data)
        {
            NL_THROW("Insufficient memory to create a cloned matrix of double of " << _rows << " X " << _cols);
        }

        memcpy(_data, copythis._data, _rows * _cols * sizeof(double) );

        return (*this);

    }

    double* cArray()
    {
        if (0 == _data)
        {
            NL_THROW("Matrix is not initialised");
        }
        return _data;
    }

    void reset(size_t rows, size_t cols)
    {
        if (0 != _data)
        {
            delete [] _data;
        }
        _rows = rows;
        _cols = cols;
        _data = new double[rows * cols];

        if (0 == _data)
        {
            NL_THROW("Insufficient memory to create a matrix of double of " << _rows << " X " << _cols);
        }
        memset(_data, 0, sizeof(double) * _rows * _cols);
    }

    double& operator () (size_t rowIndex, size_t colIndex) const
    {
        if (rowIndex >= _rows)
        {
            NL_THROW("Row index " << rowIndex << " out of range(" << _rows - 1 << ")");
        }

        if (colIndex >= _cols)
        {
            NL_THROW("Column index " << colIndex << " out of range(" << _cols - 1 << ")");
        }

        size_t flatIndex = colIndex + rowIndex * _cols;
        return _data[flatIndex];

    }

    Array rowSlice(size_t rowIndex) const
    {
        if (rowIndex >= _rows)
        {
            NL_THROW("Cannot slice matrix, required row: " << rowIndex << " is out of range(" << (_rows - 1) << ")");
        }
        Array retval(_data + rowIndex * _cols, _cols);

        /*
        for(size_t i = 0; i < _cols; i++)
        {
            retval[i] = operator()(rowIndex, i);
        }
        */
        return retval;
    }

    Array colSlice(size_t colIndex) const
    {
        if (colIndex >= _cols)
        {
            NL_THROW("Cannot slice matrix, required row: " << colIndex << " is out of range(" << (_cols - 1) << ")");
        }
        Array retval(_rows);
        for(size_t i = 0; i < _rows; i++)
        {
            retval[i] = operator()(i, colIndex);
        }
        return retval;
    }

    void fill(double value)
    {
        for(size_t rowIndex = 0; rowIndex < _rows; rowIndex++)
        {
            for(size_t colIndex = 0; colIndex < _cols; colIndex++)
            {
                size_t flatIndex = colIndex + rowIndex * _cols;
                _data[flatIndex] = value;
            }
        }
    }

    bool isEmpty() const
    {
        if (0 == _rows) return true;
        if (0 == _cols) return true;
        return false;
    }

    size_t rows() const {return _rows;}
    size_t cols() const {return _cols;}

private:
    double* _data;
    size_t _rows;
    size_t _cols;
};

A: If you can guarantee that all your threads never collide on the same element of the matrix, then you won't need locking. In practice it's not realistic to expect such a guarantee, so you'll need locking.

A: The way this class is written, you need locks on every method except the getters rows() and cols(), pretty much at the broadest possible scope on each of those methods.
You can't even rely on the size_t type being atomic from saving you any locks, because reset() sets both _row and _col  non-atomically.  Any operation that needs to know about _row and _col, e.g. isEmpty(),  will run into trouble if reset() is called from another thread.


text:
Q: Ubuntu 22.04 home wifi doesnt work sometimes I can't connect with my laptop to my home wifi sometimes but it does always connect to the acces point of my phone (which is connected to the wifi that doesn't work). I tried this but nothing.
iwconfig:
lo        no wireless extensions.

enp2s0    no wireless extensions.

wlo1      IEEE 802.11  ESSID:"..."
          Mode:Managed  Frequency:2.437 GHz  Access Point: 4A:FF:2A:8E:2B:CC
          Bit Rate=130 Mb/s   Tx-Power=3 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:off
          Link Quality=70/70  Signal level=-38 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:2   Missed beacon:0

sudo lshw -c network:
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: enp2s0
       version: 15
       serial: e4:a8:df:b6:3d:14
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=5.18.0-9.1-liquorix-amd64 firmware=rtl8168h-2_0.0.2 02/26/15 latency=0 link=no multicast=yes port=twisted pair
       resources: irq:49 ioport:2000(size=256) memory:d1604000-d1604fff memory:d1600000-d1603fff
  *-network
       description: Wireless interface
       product: MT7921 802.11ax PCI Express Wireless Network Adapter
       vendor: MEDIATEK Corp.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: wlo1
       version: 00
       serial: 38:d5:7a:66:1f:cf
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=mt7921e driverversion=5.18.0-9.1-liquorix-amd64 firmware=____010000-20220209150915 ip=192.168.234.219 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: iomemory:fc0-fbf iomemory:fc0-fbf iomemory:fc0-fbf irq:71 memory:fc02000000-fc020fffff memory:fc02100000-fc02103fff memory:fc02104000-fc02104fff

These are the log lines (from using sudo journalctl -b 0 -u NetworkManager) that appear when I try to connect to my home's wifi
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3332] device (wlo1): state change: need-auth -> prepare (reason 'none', sys-iface-state: 'managed')
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3333] device (wlo1): state change: prepare -> config (reason 'none', sys-iface-state: 'managed')
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3334] device (wlo1): Activation: (wifi) connection 'netplan-wlo1-Wifi-Familia-Dumitru' has security, and secrets exist.  No new
secrets needed.
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3335] Config: added 'ssid' value 'Wifi-Familia-Dumitru'
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3335] Config: added 'scan_ssid' value '1'
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3335] Config: added 'bgscan' value 'simple:30:-70:86400'
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3335] Config: added 'key_mgmt' value 'WPA-PSK WPA-PSK-SHA256 FT-PSK SAE FT-SAE'
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3335] Config: added 'psk' value '<hidden>'
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3635] device (wlo1): supplicant interface state: disconnected -> authenticating
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.3925] device (wlo1): supplicant interface state: authenticating -> associating
jul 09 10:27:44 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355264.4333] device (wlo1): supplicant interface state: associating -> associated
jul 09 10:27:54 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355274.4631] device (wlo1): supplicant interface state: associated -> disconnected
jul 09 10:27:54 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355274.5777] device (wlo1): supplicant interface state: disconnected -> scanning
jul 09 10:27:58 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355278.3423] device (wlo1): supplicant interface state: scanning -> authenticating
jul 09 10:27:58 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355278.3516] device (wlo1): supplicant interface state: authenticating -> associating
jul 09 10:27:58 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355278.3999] device (wlo1): supplicant interface state: associating -> 4way_handshake
jul 09 10:28:01 Valentin-LAPTOP NetworkManager[792]: <info>  [1657355281.2535] device (wlo1): disconnecting for new activation request.

A: Bugs in MT7921 driver on 5.17 kernels. Partly fixed in 5.18, but even newest Ubuntu is still on 5.17


text:
Q: How can I maintain two client sockets together using java I want to create a class that contain two socket I.e socket for client1 and socket for client 2 so that they can chat together.
How can I achieve this.When i run above code i am getting stream corrupted exception .
    My chat is not working. Can someone help me out ?
Here is my code .

This is client code for making socket request
     Client.java
    package customChat;

    import java.net.*;
    import java.io.*;
    import java.util.*;

    public class Client
    {

        private String notif = " *** ";

        private ObjectInputStream sInput;
        private ObjectOutputStream sOutput;
        private Socket socket;

        private String server, username;
        private int port;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        private RemoteAccess access;

        Client(String server, int port,RemoteAccess access ) {
            this.server = server;
            this.port = port;
            this.access = access;
        }

        public boolean start()
        {

            try
            {

                socket = new Socket(server, port);
            }
            catch(Exception ec) {
                display("Error connectiong to server:" + ec);
                return false;
            }

            String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
            display(msg);

            try
            {

                    sInput= new ObjectInputStream(socket.getInputStream());

                    sOutput = new ObjectOutputStream(socket.getOutputStream());

            }
            catch (IOException eIO) {
                eIO.printStackTrace();
                display("Exception creating new Input/output Streams in client: " + eIO);
                return false;
            }

            new ListenFromServer().start();

            try
            {
                sOutput.writeObject(access);
            }
            catch (IOException eIO) {
                display("Exception doing login : " + eIO);
                //disconnect();
                return false;
            }

            return true;
        }

        private void display(String msg)
        {

            System.out.println(msg);

        }

        void sendMessage(RemoteAccess msg)
        {
            try
            {
                System.out.println("I am writing for :"+msg.getTo()+": msg "+msg.getMsg());
                sOutput.writeObject(msg);
            }
            catch(IOException e) {
                display("Exception writing to server: " + e);
            }
        }

        private void disconnect() {
            try {
                if(sInput != null) sInput.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            try {
                if(sOutput != null) sOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try{
                if(socket != null) socket.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }

        }

        public static void sendFile()
        {

            int portNumber          = 1502;
            String serverAddress    = "localhost";
            Scanner scan            = new Scanner(System.in);

            System.out.println("Enter from ");
             long from          =   scan.nextLong();
            System.out.println("Enter to");
             long to            =   scan.nextLong();

            RemoteAccess access     =   new RemoteAccess(to,from,"hello");

            Client client   = new Client(serverAddress, portNumber,access);

            if(!client.start())
            return;

            while(true)
            {
                System.out.println("Please enter msg:");
                System.out.print("> ");
                // read message from user

                String msg = scan.nextLine();
                System.out.println("Sending message");

                    client.sendMessage(new RemoteAccess(to,from,msg));

            }

        }
        public static void main(String[] args)
        {
            sendFile();

        }

        class ListenFromServer extends Thread {

            public void run()
            {
                System.out.println("i am in run method");
                while(true)
                {
                    System.out.println("i am in run method 2");
                    try
                    {
                        System.out.println("i am in run method 3");
                        RemoteAccess access = (RemoteAccess) sInput.readObject();

                        System.out.println("Message read by:"+access.getFrom());
                        if(access !=null)
                        {
                            System.out.println("Message is :"+access.getFrom());
                        }

                    }
                    catch(IOException e)
                    {
                        e.printStackTrace();
                        System.out.println("Excepion caught while listening from server :"+e);
                        display(notif + "Server has closed the connection: " + e + notif);
                        break;
                    }
                    catch(ClassNotFoundException e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }

        }

Server.java

    package customChat;

    import java.io.*;
    import java.net.*;
    import java.text.SimpleDateFormat;
    import java.util.*;

    public class Server {

        private SimpleDateFormat sdf;
        private int port;
        private boolean keepGoing;
        private String notif = " *** ";

        public static ArrayList<ClientThread> al;
        public Server(int port)
        {
            this.port = port;
            sdf = new SimpleDateFormat("HH:mm:ss");
            al = new ArrayList<ClientThread>();
        }

        public void start() {
            keepGoing = true;
            try
            {
                ServerSocket serverSocket = new ServerSocket(port);

                while(keepGoing)
                {
                    display("Server waiting for Clients on port " + port + ".");

                    Socket socket = serverSocket.accept();
                    if(!keepGoing)
                        break;
                    ClientThread t = new ClientThread(socket);
                    Thread t1 =new Thread(t);
                    System.out.println("Connection initiated by:"+t.access.getFrom());
                    Server.al.add(t);

                    t1.start();
                }
                /*try {
                    serverSocket.close();
                    for(int i = 0; i < Server.al.size(); ++i) {
                        ClientThread tc = Server.al.get(i);
                        try {
                        tc.sInput.close();
                        tc.sOutput.close();
                        tc.socket.close();
                        }
                        catch(IOException ioE) {
                            ioE.printStackTrace();
                        }
                    }
                }
                catch(Exception e)
                {
                    display("Exception closing the server and clients: " + e);
                }*/
            }
            catch (IOException e) {
                String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
                display(msg);
            }
        }

        /*protected void stop() {
            keepGoing = false;
            try {
                new Socket("localhost", port);
            }
            catch(Exception e) {
            }
        }*/

        // Display an event to the console
        private void display(String msg) {
            String time = sdf.format(new Date()) + " " + msg;
            System.out.println(time);
        }

        public static void main(String[] args) {
            // start server on port 1500 unless a PortNumber is specified
            int portNumber = 1502;

            // create a server object and start it
            Server server = new Server(portNumber);
            server.start();
        }

    }

    ClientThread.java

    package customChat;

    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Date;

    /*class ListClient
    {

        public static  ArrayList<ClientThread> al=new ArrayList<>();;

    }*/
    public class ClientThread  implements Runnable {

        Socket                  socket;
        ObjectInputStream       sInput;
        ObjectOutputStream      sOutput;
        String                  date;
        RemoteAccess            access;

        public RemoteAccess getAccess() {
            return access;
        }

        public void setAccess(RemoteAccess access) {
            this.access = access;
        }

        // Constructor
        ClientThread(Socket socket) {

            this.socket = socket;

            System.out.println("Thread trying to create Object Input/Output Streams");
            try
            {
                sOutput = new ObjectOutputStream(socket.getOutputStream());
                sInput  = new ObjectInputStream(socket.getInputStream());
                System.out.println("CT input Stream :"+sInput);
                access = (RemoteAccess) sInput.readObject();

                System.out.println(access.getFrom() +"Joined the chat room");
            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println("Exception creating new Input/output Streams: " + e);
                return;
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            date = new Date().toString() + "\n";
        }

        /*private void close() {
            try {
                if(sOutput != null) sOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try {
                if(sInput != null) sInput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            };
            try {
                if(socket != null) socket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    */
        @Override
        public void run()
        {

            System.out.println("List size is :"+Server.al.size());

            for(int i=0;i<Server.al.size();i++)
            {
                try {
                    System.out.println("Socket input Stream :"+Server.al.get(i).socket.getInputStream());
                    System.out.println("Socket :"+socket.getInputStream());
                } catch (IOException e) {

                    e.printStackTrace();
                }
                if(Server.al.get(i).access.getFrom()==access.getTo())
                {
                    System.out.println("I am in if part :"+Server.al.get(i).access.getFrom() +"compare  to :"+access.getTo());
                    PairHandler t = null;
                    try {
                        t = new PairHandler(access.getTo(),Server.al.get(i).socket,Server.al.get(i).socket.getInputStream(),Server.al.get(i).socket.getOutputStream(),socket.getOutputStream(),socket.getInputStream(),socket);
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                    Thread t1       =   new Thread(t);
                    System.out.println("Connection initiated by in CT:"+access.getFrom());

                    t1.start();
                }
                else{
                    System.out.println("I am in else in CT");

                }
            }
        }

    }

PairHandler.java

This is where i am using two client socket

    package customChat;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.net.Socket;

    public class PairHandler implements Runnable
    {

        long                stbId;
        Socket              tvsocket;
        ObjectInputStream   tvsInput;
        ObjectOutputStream  tvsOutput;

        Socket              dtsocket;
        ObjectInputStream   dtsInput;
        ObjectOutputStream  dtsOutput;

        PairHandler(long stbId,Socket tvsocket,Socket dtsocket)
        {
            this.stbId      =   stbId;
            this.tvsocket   =   tvsocket;
            this.dtsocket   =   dtsocket;
            try
            {
                tvsOutput = new ObjectOutputStream(tvsocket.getOutputStream());
                dtsOutput = new ObjectOutputStream(dtsocket.getOutputStream());
                System.out.println("DT output Stream is :"+dtsOutput);
                System.out.println("Tv outPut Stream is :"+tvsOutput);

                System.out.println("RH input Stream :"+tvsocket.getInputStream());
                tvsInput  = new ObjectInputStream(tvsocket.getInputStream());
                System.out.println("Tv input Stream is :"+tvsInput);

                dtsInput  = new ObjectInputStream(dtsocket.getInputStream());
                System.out.println("DT input Stream is :"+dtsInput);
            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println("Exception creating in Pair Handler new Input/output Streams: " + e);
                return;
            }
        }

        public PairHandler(long to, Socket socket, InputStream inputStream, OutputStream outputStream,
                OutputStream outputStream2, InputStream inputStream2, Socket socket2) {

                stbId       =   to;
                tvsocket    =   socket;
                dtsocket    =   socket2;

                try{
                    tvsOutput = new ObjectOutputStream(outputStream);
                    dtsOutput = new ObjectOutputStream(outputStream2);
                    System.out.println("DT output Stream is :"+dtsOutput);
                    System.out.println("Tv input Stream is :"+socket.getInputStream());
                    System.out.println("DT input Stream is :"+socket2.getInputStream());

                    tvsInput  = new ObjectInputStream(socket2.getInputStream());
                    System.out.println("Tv input Stream is 2 :"+tvsInput);

                    dtsInput  = new ObjectInputStream(socket2.getInputStream());
                    System.out.println("DT input Stream is :"+dtsInput);
                    System.out.println("Tv input Stream is :"+tvsInput);

                // TODO Auto-generated constructor stub
                }
                catch (IOException e)
                {
                    System.out.println("Exception in PH");
                    e.printStackTrace();

                }
        }

        @Override
        public void run()
        {
            try
            {

                //dtsInput  = new ObjectInputStream(dtsocket.getInputStream());
                System.out.println("DT socket :"+dtsInput);
                if(dtsInput!=null){
                    RemoteAccess dtMsg = (RemoteAccess) dtsInput.readObject();

                    if(dtMsg !=null){

                        // write to tvscoket
                        System.out.println("I am here in Pair Handler");
                        sendTOTv(dtMsg);
                    }
                }

            //  tvsInput  = new ObjectInputStream(tvsocket.getInputStream());
                System.out.println("TV socket :"+tvsInput);
                if(tvsInput!=null){
                    RemoteAccess tvmsg = (RemoteAccess) tvsInput.readObject();
                    if(tvmsg !=null){

                        // write to dtsocket
                        sendToDT(tvmsg);
                    }
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println("Exception found while msg");

            }
            catch(ClassNotFoundException e2) {
                e2.printStackTrace();

            }

        }

        private void sendToDT(RemoteAccess tvmsg) {
            // TODO Auto-generated method stub

                // if Client is still connected send the message to it
                if(!dtsocket.isConnected())
                {
                    closeDtSocket();

                }
                try {

                    dtsOutput.writeObject(tvmsg);

                }
                catch(IOException e) {
                    System.out.println("Failed to deliver msg");

                }

        }
        private void closeDtSocket() {
            try {
                if(dtsOutput != null) dtsOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try {
                if(dtsInput != null) dtsInput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            };
            try {
                if(dtsocket != null) dtsocket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void closeTvSocket() {
            try {
                if(tvsOutput != null) tvsOutput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            try {
                if(tvsInput != null) tvsInput.close();
            }
            catch(Exception e) {
                e.printStackTrace();
            };
            try {
                if(tvsocket != null) tvsocket.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        private void sendTOTv(RemoteAccess dtMsg) {
            // TODO Auto-generated method stub
            if(!tvsocket.isConnected())
            {
                closeTvSocket();

            }
            try {

                tvsOutput.writeObject(dtMsg);

            }
            catch(IOException e) {
                System.out.println("Failed to deliver msg");

            }

        }

        }

RemoteAccess.java

package customChat;

import java.io.File;
import java.io.Serializable;

class RemoteAccess implements Serializable {

    private static final long serialVersionUID = 1L;

    private long to;
    private long from;
    private File file;
    private String msg;
    private int x ;
    private int y;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    RemoteAccess(){

    }
    RemoteAccess(long to,long from)
    {
        this.to=to;
        this.from=from;

    }

    RemoteAccess(long to,long from,File file)
    {
        this.to=to;
        this.from=from;
        this.file=file;

    }

    RemoteAccess(long to,long from,int x,int y)
    {
        this.to=to;
        this.from=from;
        this.x=x;
        this.y=y;

    }

    RemoteAccess(long to,long from,String msg)
    {
        this.to=to;
        this.from=from;
        this.msg=msg;

    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public long getTo() {
        return to;
    }

    public void setTo(long to) {
        this.to = to;
    }

    public long getFrom() {
        return from;
    }

    public void setFrom(long from) {
        this.from = from;
    }

}

A: I supposed you want to customize client1 and client2. So you should create a class for each one :
public class Client1 extends Socket {
    public Client1() {
        super();
    }
    //Add stuff to customize
}

public class Client2 extends Socket {
    public Client2() {
        super();
    }
    //Add stuff to customize
}

Then create your class that contains your two sockets :
public class ClientDialog {

     private Client1 client1;
     private Client2 client2;

     public ClientDialog() {
         client1 = new Client1();
         client2 = new Client1();
     }

     //Dialog between client

}


text:
Q: Moving hexagons with cube coordinates into a square formation It works for most of it:

The problem starts when the height is alot larger than the width (3x9, 3x11, 5x11 etc.)

As you can see the first line is out of place, increasing the height further will repeat this pattern.
Here is the code (Note: my z and y for cube coordinates is swapped):
void SpawnHexGrid(int Width, int Height)
    {
        int yStart = -Height / 2;
        int yEnd = yStart + Height;

        for (int y = yStart; y < yEnd; y++)
        {
            int xStart = -(Width + y) / 2;
            int xEnd = xStart + Width;

            if (Width % 2 == 0)
            {
                if (y % 2 == 0)
                {
                    xStart++;
                }
            }
            else
            {
                if (y % 2 != 0)
                {
                    xStart++;
                }
            }
            Debug.Log("y: " + y + " , Start: " + xStart + " , End: " + xEnd);

            for (int x = xStart; x < xEnd; x++)
            {
                SetHexagon(new Cube(x, y));
            }
        }
    }

Edit:
After changing to @Idle_Mind solution my grid looks like this:

Edit again:
I found a solution, after changing to @Idle_Mind's solution I corrected the tilting by using y again:
int xStart = -Width / 2 - (y / 2);

but this caused a similar problem as before, but this time I realized it had something to do with the way an int is rounded, when y is negative xStart would be 1 lower then expected, so I just add 1 whenever y is negative:
int add = 0;

    if (y < 0)
    {
        add = 1;
    }
    int xStart = -Width / 2 - ((y - add) / 2);

This works like a charm now, thanks everyone.

A: Change your SpawnHexGrid() to:
void SpawnHexGrid(int Width, int Height)
{
    int xStart = -Width / 2;
    int yStart = -Height / 2;
    int yEnd = yStart + Height;

    for (int y = yStart; y < yEnd; y++)
    {
        int xEnd = xStart + Width + (y%2==0 ? 0 : -1);

        for (int x = xStart; x < xEnd; x++)
        {
            SetHexagon(new Cube(x, y));
        }
    }
}

My test rig:

---------- EDIT ----------
I don't understand why you're using the y value as part of your calculation for x. Make the x constant for a whole column as you'd expect for a regular grid. In my code, the shorter rows still start at the SAME x coord as the longer ones; it's the length of them that changes. Then, when you draw, I simply calculate the position for a normal grid, but add half the width of the hexagon for all odd y positions resulting in the offset you need for the hexagons.
For example, here is a 5x5 grid drawn "normally" without offsetting the odd Y rows.  It's clear that the starting X coordinate for all rows is the same:

So the stored x,y coord are all based on a normal grid, but the drawing code shifts the odd y rows.  Here's where I change the X coord, only for drawing, of the odd y rows:
if (pt.Y % 2 != 0)
{
    center.Offset(Width / 2, 0);
}

So, after adding the offset (again, only at drawing time) for odd Y rows, it now looks like:

And here is the grid shown with the internal coord of each hexagon being displayed:

Hope that makes it clear how I approached it.

A: I believe you're just alternating a different row size for a hexagonal map.  If so something like this should work:
class Program
{
    static void Main(string[] args)
    {
        const int Height = 4;
        const int Width = 4;

        for (int y = 0; y < Height; ++y)
        {
            int rowSize = y % 2 > 0 ? Width + 1 : Width;

            for (int x = 0; x < rowSize; ++x)
            {
                Console.WriteLine($"{x}:{y}");
            }
        }

        Console.ReadLine();
    }
}


text:
Q: Interior material and spacetime of a black hole described from outside This question is mostly about general relativity. Answers regarding the quantum physics behind it are also appreciated, but first I would prefer  solutions from a relativistic viewpoint.

If you fall into a black hole you reach the singularity at $\text{r}=0$ in a finite proper time. In contrast, for a stationary observer on the outside, the infalling object needs an infinite amount of coordinate time to reach the horizon at $\text{r}=\text{r}_s=2\text{G}\text{M}/ \text{c}^2$, in other words, everything that falls into a black hole gets stuck on the horizon and never crosses it.
Relative to a stationary observer outside the black hole the gravitational time dilation on the event horizon $\text{r}_s$ is infinite, so even things moving with $\text{c}$ can not cross the horizon because velocity is distance/time, and if time stands still, there is no movement.
Also, if you try to find the outer coordinate time for a given proper time of an infalling observer who has already passed the horizon, you get physically nonsense results like imaginary numbers. So from the relativistic viewpoint, if someone is inside the black hole, there should not even be any time left on the outside, if I get that right.
That means, for the observer on the outside, the black hole should be hollow with all the stuff plastered outside the horizon (on the "stretched horizon, as Susskind mentions here and here).

Image: sketch of the supposed space-grid at a given coordinate time as viewed from outside the black hole (note the empty place inside the circle in the center of gravity, which would be a hollow shell in 3D)

So my question is:
Right now, speaking from the perspective of a stationary observer on the outside of the black hole, is there even any space inside a black hole, or is the metric of spacetime warped to form a hollow shell with $\text{r}=\text{r}_s$, if you were to describe it from 1 higher dimension? At least that's what it looks like here, here and here.

Image: Susskind saying that even from the perspective of an infalling observer there might not be any spacetime behind the event horizon

Does the singularity in the center even form during the lifespan of an outer observer?

A: There are two kinds of black holes. Eternal black holes, and astrophysical black black.
An eternal black hole has always been around. There could still be stuff coming away from it, and at later times you just see stuff coming away from it today that was a tiny bit closer to the horizon than stuff you saw coming away from it yesterday.
An astrophysical black hole formed from the collapse of matter. And for that one, you can still see the center from before an horizon formed. Well, you can see it as well as you could ever see the center of a star.

Right now, speaking from the perspective of a stationary observer on the outside of the black hole, is there even any space inside a black hole,

For an astrophysical black hole, yes. For an eternal blacks hole, doesn't matter, they don't exist.

or is the metric of spacetime warped to form a hollow shell with $\text{r}=\text{r}_s$, if you were to describe it from 1 higher dimension?

For an eternal black hole you could cut out the spacetime beyond the event horizon and do it at the horizon or somewhere inside. Not that the event horizon is as easy to find as that one example of a spherically symmetric static stationary object alone in the universe would have you believe. In fact, being able to cut it off at the event horizon is almost entirely a tautology and completely devoid of content.
You could also use radar distance instead of that higher dimensional embedding and then the event horizon is an infinite radar distance away so it might seem mysterious.

Does the singularity in the center even form during the lifespan of an outer observer?

That's what cosmic censorship is all about. People want to say no, the only problem is the answer is yes for some parameters choices. So you can claim those parameters are "unphysical" and then say no. But it's become another tautology like the event horizon itself.

If so, what happens to the initial material that was at the center before the black hole formed?

You say "if so" but the rest of your question still makes sense. It's all there. Imagine a 3d spacetime. If it were Minkowski spacetime then surfaces of constant $z$ could be surfaces of constant time. Now we could have a circle of infalling matter. Inside the circle you have flat Minkowksi space. Because of time dilation each surface that is spaced inside the circle a certain distance corresponds to a larger spacing farther outside.
As the circle contracts that effect gets stronger. So that last hour before the center hits the horizon has surfaces of constant outer time that have an infinite number of layers stack up.

Does this center also get warped around the Schwarzschild radius and is technically outside the event horizon

No, the inside isn't outside the horizon spatially. It is before the horizon temporally. The interior of the star before the horizon forms gets time dilated to take forever to form the horizon. So you can still see the center from **before* the horizon formed.


text:
Q: how to break the internet connection with code? hey i know that on some computers you can cut off the wifi with a buttion and i want to do that with my desktop but it's not wireless. is there a way to in code block my computer from the internet then unblock later. anyway i can do this?

A: Try to use WMI - Windows Management Instrumentation to disable network connections.
WMI is visual basic / scripting friendly COM-technology based API and doesn't provide greate abilities though. But hope it helps

A: One possibility would be to use IpReleaseAddress to cut the connection, and IpRenewAddress to re-start it. Another possibility would be to use SetIfEntry to disable/enable the network interface.

A: A rather brute force way on windows if you're getting your address via DHCP is to just make a call to ipconfig /release and ipconfig /renew when you want your access back.


text:
Q: We're seeing "corrupted" opcache on our servers. Any idea how to resolve? We're seeing an odd issue that I've been struggling to resolve.
Every now and then we do a deploy to our servers, and one server will start streaming errors into the logs along the lines of,
require_once(): Failed opening required '/var/www/CrrrectPath/Abstract.php'
(include_path='/var/www/') in /var/www/CorrectPath/Object.php on line 2

The issue is not always an include(). Sometimes a method name gets corrupted in the same way (a single character being replaced with another character).
Having debugged an affected server in production, I can see the files themselves are absolutely fine. My gut here is that the opcache of the files is getting corrupted in some way.
We had "validate_timestamps" enabled, so I figured it was plausible that the files were being re-read mid rsync (we r-sync from one folder to the "live" folder as part of our deploy). We then disabled "validate_timestamps" and are now doing a opcache_reset() when the code has been fully rsynced. The issue does happen less frequently, but we're still seeing occurrences.
Has anyone else come across this issue? Any suggestions for a resolution (other than completely changing how we deploy)?
For info,
$ php -v
PHP 7.0.21-1~ubuntu14.04.1+deb.sury.org+1 (cli) (built: Jul  6 2017 09:38:10) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.21-1~ubuntu14.04.1+deb.sury.org+1, Copyright (c) 1999-2017, by Zend Technologies

Thanks

A: It appears that this issue is/is similar to the following PHP bug,
https://bugs.php.net/bug.php?id=71135
We're re-enabling "validate_timestamps" and not doing opcache_reset() on deploy. Hopefully this will resolve the issue.


text:
Q: Get map from OpenStreetMap and use it as a background with basemap I want to take a bounding box, use the OpenStreetMap API and get a tile, then use it as a background in basemap. This should be easy, but I haven't been able to figure out the API.

A: Go to OSM website (http://www.openstreetmap.org), choose a BBOX and select export.
When you take data from OSM you'll get just the data. You'll need to import it to your database/QGIS/Geoserver and apply some styles to see the data as seen in OSM map. I know nothing about matplotlib-basemap.
To import the data to PostgreSQL you can use osm2pgsql:
osm2pgsql -C 2500 -c -d database_target -U postgre_user -W -s -S ./your_style_file.style your_osm_file.osm
Your database_target must have the GIS extensions.
Getting the same beautiful OSM map appearance is not so easy since there is no official style file to download. You must dig it.


text:
Q: how to call web service in android i am new in Android development and now i am developing small application of google map. i have integrated google map,but now i want to show google places on map therefore i want to call google api web service to get locations, but i don't know how to call web service in android.enter code here
enter code here

public void getLocation()
{
    HttpClient httpClient = new HttpClient()
    AsyncHttpClient client =new AsyncHttpClient();
}

A: You can call Url's with HttpConnection.
For Example:
public String getValuefromUrl(String url)
{
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        ResponseHandler<String> resHandler = new BasicResponseHandler();
        String page = httpClient.execute(httpGet, resHandler);
        Log.v("PAGE",page);
        return page;
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
        return "zero";

    }
}


text:
Q: Jquery https http issue I'm using Fancybox from FancyApps to preview content on my website.

Always enjoy the sunny days!

Basically this is working fine, but in one situation I need to redirect my site to a secure server, so the domain will change.
Example:
https://secure-payment.com/relay/v2/relay.cgi/http://www.mydomain.com/checkout
When I use the link to trigger Fancybox no this page, I just get "The requested content cannot be loaded. Please try again later."
In addition (I don't know if it's relevant) I'm running the script below on the bottom of my page, this is as requested from the payment company.
//
// Variables used for searching
//
var relayurl = "https://relay.ditonlinebetalingssystem.dk/";
var relayurl_replace = "https://relay.ditonlinebetalingssystem.dk/relay/v2/relay.cgi/";
var baseurl = "";

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

//
// Replace all links to NOT use the relay-script when the user clicks on the links
//
function replaceRelayButtons(parent, startTimer) {
    var aEls = parent.childNodes;
    for (var i = 0, aEl; aEl = aEls[i]; i++) {
        //
        // Do recursive call
        //
        replaceRelayButtons(aEls[i]);

        if (aEls[i].tagName == 'A' || aEls[i].tagName == 'a') {
            if (aEls[i].href.indexOf(relayurl) == 0) {
                aEls[i].href = aEls[i].href.replace(relayurl_replace, "");
                aEls[i].href = aEls[i].href.replace(relayurl, "")
                if (aEls[i].href.indexOf("http://") != 0) {
                    aEls[i].href = (baseurl + "/" + aEls[i].href);
                }
            }
        }
        if (baseurl.length > 0) {
            if (aEls[i].tagName == 'IMG' || aEls[i].tagName == 'img') {
                if (aEls[i].src.indexOf(relayurl) == 0 && aEls[i].src.indexOf(relayurl_replace) == -1) {
                    aEls[i].src = aEls[i].src.replace(relayurl, relayurl_replace + "/" + baseurl + "/");
                }
            }
        }
    }

    //
    // Now start the timer which runs this function again to fix all body elements that might not be loaded in the browser yet
    //
    if (startTimer) {
        setTimeout("replaceRelayButtons(document.body, false)",1000)
        setTimeout("replaceRelayForms()",1000)
    }
}

//
// Replace all form actions to NOT use the relay-script when the user clicks on the links
//
function replaceRelayForms() {
    for (i = 0; i < document.forms.length; i++) {
        if (document.forms[i].action.indexOf(relayurl) == 0) {
            document.forms[i].action = document.forms[i].action.replace(relayurl_replace, "");
            document.forms[i].action = document.forms[i].action.replace(relayurl, "")
            if (document.forms[i].action.indexOf("http://") != 0) {
                document.forms[i].action = (baseurl + "/" + document.forms[i].action);
            }
        }
    }
}

//
// Go and replace the urls and form actions
//
if (getURLParam('baseurl') != null) {
    baseurl = getURLParam('baseurl')
}
replaceRelayButtons(document.body, true);

What Might I be doing wrong? Is this even possible?

A: I don't think much is wrong, but you can't load a HTTPS URL into a HTTP url, because it should be a secure URL aswell. This because fancybox generates a iFrame if the URL is another domain.
IE will show you a error, but Firefox will load the page, try it and you will see.
For more detailed information: JavaScript HTTPS to HTTP iFrame Security Question

A: I think the issue of "The requested content cannot be loaded. Please try again later." it's more related to this thread https://stackoverflow.com/a/8509018/1055987 than the fact you are in a secure server.
so try changing this part of your code

Always enjoy the sunny days!

to this

Always enjoy the sunny days!