Q:

How does the Catholic church explain Matthew 19:9, which seems to allow divorce in case of sexual misconduct?

Matthew 19:9 (NIV)

I tell you that anyone who divorces his wife, except for sexual
  immorality, and marries another woman commits adultery.

On a simple examination, it seems to imply that sexual immorality, for example,  adultery,  constitutes grounds for divorce.
Yet this is not the Catholic interpretation. What is the Catholic explanation of this verse?

A:

Good question! In the New American Bible (Revised Edition), which is the translation authorized by the U.S. Council of Catholic Bishops for use in the United States, Matt. 19:9 reads:

I say to you, whoever divorces his wife (unless the marriage is unlawful) and marries another commits adultery.

(Note: you don't specify which translation you're using; that would be helpful information.)
It would be interesting to know what the original Greek says; I may search for or post a question on Biblical Hermeneutics about that.
The NABRE has a note on the verse, referring to a note on Matt. 5:31–32. That note reads:

(Unless the marriage is unlawful): this “exceptive clause,” as it is often called, occurs also in Mt 19:9, where the Greek is slightly different. There are other sayings of Jesus about divorce that prohibit it absolutely (see Mk 10:11–12; Lk 16:18; cf. 1 Cor 7:10, 11b), and most scholars agree that they represent the stand of Jesus. Matthew’s "exceptive clauses" are understood by some as a modification of the absolute prohibition. It seems, however, that the unlawfulness that Matthew gives as a reason why a marriage must be broken refers to a situation peculiar to his community: the violation of Mosaic law forbidding marriage between persons of certain blood and/or legal relationship (Lv 18:6–18). Marriages of that sort were regarded as incest (porneia), but some rabbis allowed Gentile converts to Judaism who had contracted such marriages to remain in them. Matthew’s “exceptive clause” is against such permissiveness for Gentile converts to Christianity; cf. the similar prohibition of porneia in Acts 15:20, 29. In this interpretation, the clause constitutes no exception to the absolute prohibition of divorce when the marriage is lawful.

Thus, it appears that Catholic interpretation of this particular passage considers the statement in Matthew to refer to a specific situation present uniquely in Matthew's community at the time, and thus not applicable generally, and gives precedence to the alternate statements on divorce present in the other synoptic gospels.
The Catechism of the Catholic Church agrees with this interpretation:

Divorce is a grave offense against the natural law. It claims to break the contract, to which the spouses freely consented, to live with each other till death. Divorce does injury to the covenant of salvation, of which sacramental marriage is the sign. Contracting a new union, even if it is recognized by civil law, adds to the gravity of the rupture: the remarried spouse is then in a situation of public and permanent adultery:

If a husband, separated from his wife, approaches another woman, he is an adulterer because he makes that woman commit adultery; and the woman who lives with him is an adulteress, because she has drawn another’s husband to herself.

(CCC, paragraph 2384. The quoted section is cited as "St. Basil, Moralia 73, 1".)
This is why the Church is so forcefully against divorce.

A:

A catholic within the parameters set by the Magestarium can interpret this verse in the following ways:

Sexual immorality can be a valid reason for civil divorce. But such divorced couples cannot remarry.
The word used in Matthew 19:9 for sexual immorality is: porneia. This word can also mean marriage with close relatives. (Ordinary Greek word for adultery is moicheuō) So some interpret this verse as a reference to marriage between close blood relatives (siblings etc.,). Such people can get a divorce (Annulment in Catholic terminology). Such divorced couples can remarry. Here Christ's words except for sexual immorality is interpreted as except for cases where unlawful unions exist. Some do not accept this explanation as a marriage does not happen if there is a serious impediment (like being close blood relative).

Also note that civil divorce is not prohibited for Catholics:

If civil divorce remains the only possible way of ensuring certain legal rights, the care of the children, or the protection of inheritance, it can be tolerated and does not constitute a moral offense. (CCC 2383)


Q:

Android setBackgroundTintList on pre-lollipop devices

I'm working with FloatingActionButton.
The user should be able to switch the FAB background color within a onClick Event.
However, the recommended call to setBackgroundTintList seems to be only compatible from 21+ API.
How do I - correctly - go about it on pre-lollipop devices? Is there any alternative I could use?
Thanks in advance.

A:

You can use also setSupportBackgroundTintList

Applies a tint to the background drawable. Does not modify the current tint mode, which is SRC_IN by default.
Subsequent calls to View.setBackground(Drawable) will automatically mutate the drawable and apply the specified tint and tint mode.

Also take a look on ViewCompat.setBackgroundTintList()

Applies a tint to the background drawable.
This will always take effect when running on API v21 or newer. When running on platforms previous to API v21, it will only take effect if view implement the TintableBackgroundView interface.

I found a solution here on SO that I've used before and is this:
public static void setButtonTint(Button button, ColorStateList tint) {
  if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && button instanceof AppCompatButton) {
      ((AppCompatButton) button).setSupportBackgroundTintList(tint);
  } else {
      ViewCompat.setBackgroundTintList(button, tint);
  }
}

It works for me I hope it works for you too.

A:

simple:
fab.setBackgroundTintList(ColorStateList.valueOf(0xFF4CAF50));

fab is your FloatingActionButton of course and 0xFF4CAF50 just a example color


Q:

Creating Cascading dropdown in asp.net core with razor pages not working

I'm trying to implement a cascading dropdown list with asp.net core 3.1 code first. I have two tables which are vehicle make and vehicle model. the first dropdown would populate the makes and on selecting any make the second dropdown would populate the models. but I keep getting undefined on the model dropdown. below is my implementation. please what am I doing wrong? thanks
IVehicleService interface

    namespace Application.Common.Interfaces
    {
       public interface IVehicleService
       {
         IEnumerable<VehicleMake> GetMakes();
         IEnumerable<VehicleModel> GetModels(int categoryId);
       }
     }

Vehcicle Service

    namespace Application.Common.Interfaces
    {
      public class VehcicleService : IVehicleService
      {
        private readonly IApplicationDbContext _dbContext;
        public VehcicleService(IApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public IEnumerable<VehicleMake> GetMakes()
        {
            IEnumerable<VehicleMake>  makes = _dbContext.VehicleMakes.ToList();
            return makes;
        }
        public IEnumerable<VehicleModel> GetModels(int MakeId)
        {
            IEnumerable<VehicleModel> model = _dbContext.VehicleModels.Where(x => x.VehicleMakeId == MakeId).ToList();
            return model;
        }
    }
     }

My Model Page
namespace Wbc.WebUI.Areas.Tools.Pages
{

    public class SearchByMakeModel : PageModel
    {
       private readonly IVehicleService _vehicleService;
        public SearchByMakeModel(IVehicleService vehicleService)
        {
            _vehicleService = vehicleService;
        }
        [BindProperty(SupportsGet = true)]
        public int MakeId { get; set; }
        public int ModelId { get; set; }
        public SelectList MakeListdll { get; set; }

       public void OnGet()
        {
            MakeListdll = new SelectList(_vehicleService.GetMakes(), nameof(VehicleMake.Id),
            nameof(VehicleMake.Name));
        }

        public JsonResult OnGetSubCategories()
        {
            return new JsonResult(_vehicleService.GetModels(MakeId));
        }
    }
}

My Razor Markup
 <select asp-for="MakeId" asp-items="Model.MakeListdll">
   <option value=""></option>
   </select>

   <select asp-for="ModelId">
    </select>

The interface and its implementation are registered with the dependency injection system in Startup:
services.AddTransient<IVehicleService, VehcicleService>();

My Ayax Call
@section scripts{
    <script type="text/javascript">
        $(function () {
            $("#MakeId").on("change", function() {
                var makeId = $(this).val();
                $("#ModelId").empty();
                $("#ModelId").append("<option value=''>Select Model</option>");
                $.getJSON(`?handler=OnGetModels&MakeId=${makeId}`, (data) => {
                    $.each(data, function (i, item) {
                        $("#ModelId").append(`<option value="${item.Id}">${item.Name}</option>`);
                    });
                });
            });
        });
    </script>
}

A:

First of all, in $.getJson of js, you need to change the handler to SubCategories, because you need to enter OnGetSubCategories to obtain VehicleModel datas.

but I keep getting undefined on the model dropdown

And another important point is that in core, when ajax returns json, the field name will be changed to camel case by default, so you need to change the first letter of the field name after item to lowercase, such as: ${item.id} and ${item.name}.
Since you did not provide the VehicleModel class, here is my custom VehicleModel class:
   public class VehicleModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int VehicleMakeId { get; set; }
    }

Here is js:
@section scripts{
    <script type="text/javascript">
        $(function () {
            $("#MakeId").on("change", function () {
                var makeId = $(this).val();
                $("#ModelId").empty();
                $("#ModelId").append("<option value=''>Select Model</option>");
                $.getJSON(`?handler=SubCategories&MakeId=${makeId}`, (data) => {
                    $.each(data, function (i, item) {
                        $("#ModelId").append(`<option value="${item.id}">${item.name}</option>`);
                    });
                });
            });
        });
    </script>
}

Update
If you don't want the field name in the returned json to become camel case, then you can add the following statement in the startup to cancel it:
services.AddMvc().AddJsonOptions(jsonOptions =>
        {
            jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

Here is the test result:


Q:

Does Windows performance degrade past a certain level of CPU utilization?

Is there a recommended average CPU threshold in running Windows boxes based on experience in other shops?
Background:
We are running with Windows Server 2003 32-bit OS.  Servers are handling a major enterprise-level web application suite with a high frequency of small transactions mixed in with much larger transactions - overall average is 13ms.
Our average overall CPU utilization of the Windows servers are ~60% during prime-shift.  And we question at what level does the Windows OS begin to shimmy on the CPU scheduling road?
Thanks.

A:

OK there's a few things you need to watch out for here.
Firstly is redundancy / fallover. If you have 5 machines running at 90% capacity, and one of the machines fails, then the other 4 machines have to pick up the slack ... whoops ... that takes them over 100% capacity and you will likely start to have a cascade failure on your hands.
Secondly, IF you're running multiple processes, then remember that the OS takes compute cycles to SWITCH processes too. This means that if the system load gets too high, the system can start spending too long loading and suspending tasks for execution, and less and less time actually executing the processes.
Thirdly, if you're running MS SQL server, for goodness sake configure it correctly or get someone to do it for you. MS SQL server will suck up all available RAM for cache and can bog down the machine if you don't limit its RAM usage. I have had clients who were complaining about RAM usage on a server, doubled the RAM, and noticed no performance gain because MSSQL server sucked it all up again!
Hope those help :-)


Q:

How to mock service in groovy/src class under test with Grails 3.3.x

I've recently upgraded to grails 3.3.1 and realised that grails.test.mixin.Mock has been pulled to separate project which has been build just for backward compatibility according to my understanding org.grails:grails-test-mixins:3.3.0.
I've been using @Mock annotation to mock Grails service injected into groovy/src class under test. What is the tactic to mock collaborating services in this case? Is there anything from Spock what I can use or should I fallback to grails-test-mixins plugin?
Class under test:
import gra
ils.util.Holders

import grails.util.Holders

class SomeUtilClass {

    static MyService myService = Holders.grailsApplication.mainContext.getBean("myService")

    static String myMethod() {
        // here is some code
        return myService.myServiceMethod()
    }
}

My test spec (Grails 3.2.1):
import grails.test.mixin.Mock
import spock.lang.Specification

@Mock([MyService])
class ValidatorUtilsTest extends Specification {

    def 'my test'() {
        when:
            def result = SomeUtilClass.myMethod()
        then:
            result == "result"
    }
}

A:

Due to you use Holders.grailsApplication in your SomeUtilClass, you can try to add @Integration annotation:
import grails.testing.mixin.integration.Integration
import spock.lang.Specification
@Integration
class ValidatorUtilsTest extends Specification {

    def 'my test'() {
        when:
        def result = SomeUtilClass.myMethod()
        then:
        result == "result"
    }
}

Not sure, but hope it work for you.


Q:

Increase maximum size of POST or PUT request to Kentico REST services over 64KB

Using Kentico 10, we're having issues raising the maximum request limit size above the default 64KB limit for any requests that go to the [servername]/rest/ services. All POST or PUT requests over that limit are met with server error 413 - request entity too large. In other parts of the application (such as the Kentico Admin) this limit does not exist as we're able to send POST and PUT requests with much higher amounts of data.
We've tried adding the following configuration to our web.config file but this does not affect the 64KB limit:
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="2097151" />
    </requestFiltering>
  </security>
</system.webServer>

In addition, we've added a location element to the web.config with the following settings:
<location path="rest">
  <system.web>
    <httpRuntime executionTimeout="2400" maxRequestLength="2097151" />
  </system.web>
  <system.webServer>
    <serverRuntime uploadReadAheadSize="2000000000" maxRequestEntityAllowed="32000000" />
    <security>
      <requestFiltering>
        <fileExtensions allowUnlisted="true" />
        <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
    </security>
  </system.webServer>
</location>

Neither of the configuration changes above had any affect on the POST or PUT requests over 64KB.
Kentico routes any requests to [servername]/rest/... through their URLRewritingEngine and rewrites those requests to DocumentRESTService.svc, ObjectTranslationRESTService.svc, or RESTService.svc depending on the type of call. So adding configuration sections to the system.serviceModel doesn't affect the use of those services.
How can we change this limit for the Kentico web services?

A:

This can be done by adding the following pieces of code into the <system.serviceModel> section at the end of the web.config file:
Insert a <webHttpBinding> element into the <bindings> sub-section:
<webHttpBinding>
  <!-- Limits set to 10 MB (specified value in bytes) -->

  <binding name="RESTQuotaBinding" maxReceivedMessageSize="10485760" maxBufferPoolSize="10485760" maxBufferSize="10485760" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">
     <readerQuotas maxDepth="32" maxStringContentLength="10485760" maxArrayLength="10485760" maxBytesPerRead="10485760" />
     <security mode="None" />
  </binding>
</webHttpBinding>

Add a <service> element under the <services> sub-section:
<service name="CMS.WebServices.RESTService">
   <host>
     <baseAddresses>
       <add baseAddress="http://localhost/KenticoCMS/rest" />
     </baseAddresses>
   </host>
   <endpoint address="" bindingConfiguration="RESTQuotaBinding" binding="webHttpBinding" contract="CMS.WebServices.IRESTService" />
</service>

https://docs.kentico.com/k10/integrating-3rd-party-systems/kentico-rest-service/configuring-the-rest-service#ConfiguringtheRESTservice-Enablinguploadoflargedata


Q:

How can I make sure that Async task is only calling once

I have a method which has a async task and it is called from several different services and those services runs periodically . I want to make sure when one task is on going , no other thing can call it unless the task is finished.
public class Helper {

    public static void doSomethingAsync() {
        new AsyncTask<String, Void, Integer>() {
            @Override
            protected void onPreExecute() {
            }

            @Override
            protected Integer doInBackground(String... strings) {
                //doing something
            }

            @Override
            protected void onPostExecute(Integer resultCode) {

            }
        }.execute();
    }

    public static void someOtherMethod(){

    }
}

A:

AsyncTask.getStatus() will give the status of the task, i.e. whether finished or not.
Declare a member variable
private static AsyncTask<String, Void, Integer> mTask;

Modify your method as,
public static void doSomethingAsync() {

    if(null != mTask && mTask.getStatus() != AsyncTask.Status.FINISHED){
       return; //Returning as the current task execution  is not finished yet.
    }

    mTask = new AsyncTask<String, Void, Integer>() {
        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Integer doInBackground(String... strings) {
            //doing something
        }

        @Override
        protected void onPostExecute(Integer resultCode) {

        }
    };
    mTask.execute();
}


Q:

Retrofit to parser json with an indefinite number of object names

I'm using retrofit to handle rest-api calls.
I have a rest API that returns the following json
    "MyObject": {
      "43508": {
        "field1": 4339,
        "field2": "val",
        "field3": 15,
        "field4": 586.78
      },
      "1010030": {
        "field1": 1339,
        "field2": "val212",
        "field3": 1,
        "field4": 86.78
      },...
    }

Please notice that the object MyObject contains objects with a name that is actually an id.
For all the other rest APIs I'm using retrofit without problems.
In this case it seems not possible to use the standard approach: defining a class containing the fields expected in the response.
Is there a way to transform this json into a json containing an array of
{
    "field1": xxx,
    "field2": "yyy",
    "field3": www,
    "field4": zzz
}

Or is there a better way to deal with this problem without going back to "manually" parsing the json?

A:

Try to use next approach:
public class Response {

    Map<String, YourObject> MyObject;
    // getter, setter
}

public interface GitHubService {
  @GET("some_path")
  Call<Response> listMyObjects();
}

All you objects will be parsed to Map. You can get the list of all ids via keySet() method or list all entries with entrySet().


Q:

How can I do a Ctrl+Click on protractor?

I have tried weird combination as the following, but none of them are working:
var ptor = protractor.getInstance();
ptor.actions().mouseMove(node).keyDown(ptor.Key.CTRL).sendKeys(ptor.Key.CLICK).perform();

A:

You need to chain mouseMove(), keyDown() and click():
var elm = element(by.id('my_id'));

browser.actions()
    .mouseMove(elm)
    .keyDown(protractor.Key.CONTROL)  // COMMAND for Mac
    .click()
    .perform();

Tested it on Chrome by clicking on a link - opens up a link in a new tab.

Note that, starting with protractor 1.5, there is a global browser object that should be used instead of protractor.getInstance(), see Breaking Changes.


Q:

Best way to pass variables between Arduino and PC over serial?

I've written an Arduino sketch which reads data from a remote control receiver and returns a value between 0 and 1023 for that channel. I basically want to send this data (something in the format of channel:value, eg, Channel 1 : 1023, Channel 2 : 511) to a PC program (which I plan to write myself).
The most efficient way I can think to do this is to use two bytes of data, with the first 6 bits representing the channel (2^6 = 64 possible channels, way more than I need), and the last ten representing the value (2^10 = 1024, perfect). But I'm not sure on the best way to implement this in C++, or if this is even the most ideal way to do this. So:

What is the best way to craft individual bytes and work with binary numbers in C++? Preferably storing the values in memory as such (ie, no bool arrays, where each index takes up it's own byte). Two bytes of data is more than enough for what I need.
Is this the easiest/simplest/most efficient/recommended way to implement what I am trying to achieve? I basically want to pass variables as is between programs, are there any other ways to do this?

A:

You can declare a packed struct to hold these two values:
struct chan_value_t
{
  uint8_t  channel : 6;
  uint16_t value   : 10;
};

But to send it as two bytes, you'll need to either (1) "union" it with a two-byte array:
union chan_value_t
{
  struct {
    uint8_t  channel : 6;
    uint16_t value   : 10;
  };
  uint8_t bytes[2];
};

chan_value_t cv;

void setup()
{
  Serial.begin( 9600 );

  cv.channel = 2;
  cv.value = 800;
  for (int i=0; i<sizeof(cv.bytes); i++) {
    Serial.print( cv.bytes[i], HEX );
    Serial.print( ' ' );
  }
  Serial.println();
}

void loop() {}

(The struct is anonymous when nested in this union; the union has the name.)
Or (2) cast a pointer to the struct to a pointer to bytes:
struct chan_value_t {
  uint8_t  channel : 6;
  uint16_t value   : 10;
};

chan_value_t cv;

void setup()
{
  Serial.begin( 9600 );

  cv.channel = 2;
  cv.value = 800;
  uint8_t *bytes = (uint8_t *) &cv; // cast &cv to a pointer to bytes
  for (int i=0; i<sizeof(cv); i++) {
    Serial.print( bytes[i], HEX );
    Serial.print( ' ' );
  }
  Serial.println();
}

void loop() {}

They both print the hexadecimal value of the bytes: 0x02 and 0xC8.  800 is 0x320, shifted left by 6 bits is 0xC800.
To send this to the PC, you may want to start with a special character sequence and finish with a checksum of some sort (Fletcher checksum is easy).  Then it's easy to throw away garbage characters and know when there are transmission errors.


Q:

How to call a function inside another function?

Im new to the community and coding in general, chose python as my first language and finished a couple of online courses.
I am trying to work on a project to practice and keep improving, Its a credit card number validator, checks the digits, prefix and checksum, but Im getting stuck at a very basic concept.
I m defining a function as an input for the user the enter de credit card number, then Id like to call the function inside another one that validates the prefix and the check sum, but I keep getting a traceback as if my variable is not defined.
# User inputs the cc number
def inp_cc():
    cc_number = input("Insert credit card number: ")
    return cc_number

# This will validate the prefix and lenght and print it if its correct,
otherwise will show an error
# Code is not completed as I keep getting the traceback

def val_tc():
    inp_cc()
    if len(cc_number) == 13 or len(cc_number) == 16:
        cc_brand = "Visa"
        print("Credit card number: %s" % cc_number,"Credit card brand: %s" % cc_brand)
    else:
        quit()

# Here I call the val_tc() function that should also call the inp_cc()

val_tc()

This is the error I get:
Traceback (most recent call last):
  File "main.py", line 17, in <module>
    val_tc()
  File "main.py", line 11, in val_tc
    if len(cc_number) == 13 or len(cc_number) == 16:
NameError: name 'cc_number' is not defined

Thanks in advance!

A:

The reason for the error is that you didn't actually assign the return value of the inp_cc function to anything. Here's a fixed version:
def inp_cc():
    cc_number = input("Insert credit card number: ")
    return cc_number

def val_tc():
    cc_number = inp_cc()  # FIXED
    if len(cc_number) == 13 or len(cc_number) == 16:
        cc_brand = "Visa"
        print("Credit card number: %s" % cc_number,"Credit card brand: %s" % cc_brand)
    else:
        quit()

val_tc()


Q:

Can I declare variables inside an Objective-C switch statement?

I think I'm going blind, because I can't figure out where the syntax error is in this code:
if( cell == nil ) {
    titledCell = [ [ [ TitledCell alloc ] initWithFrame:CGRectZero
        reuseIdentifier:CellIdentifier ] autorelease
    ];

    switch( cellNumber ) {
        case 1:
            NSString *viewDataKey = @"Name";
etc...

When I try to compile it, I'm getting an Error: syntax error before '*' token on the last line.
Sorry for such a basic question, but what am I missing?

A:

I don't have a suitable Objective-C compiler on hand, but as long as the C constructs are identical:
switch { … } gives you one block-level scope, not one for each case.  Declaring a variable anywhere other than the beginning of the scope is illegal, and inside a switch is especially dangerous because its initialization may be jumped over.
Do either of the following resolve the issue?
NSString *viewDataKey;
switch (cellNumber) {
    case 1:
        viewDataKey = @"Name";
    …
}

switch (cellNumber) {
    case 1: {
        NSString *viewDataKey = @"Name";
        …
    }
    …
}

A:

You can't declare a variable at the beginning of a case statement. Make a test case that just consists of that and you'll get the same error.
It doesn't have to do with variables being declared in the middle of a block — even adopting a standard that allows that won't make GCC accept a declaration at the beginning of a case statement. It appears that GCC views the case label as part of the line and thus won't allow a declaration there.
A simple workaround is just to put a semicolon at the beginning of the case so the declaration is not at the start.

A:

In C you only can declare variables at the begining of a block before any non-declare statements.
{
   /* you can declare variables here */

   /* block statements */

   /* You can't declare variables here */
}

In C++ you can declare variables any where you need them.


Q:

CircleCI Run JUnit Tests on Compiled Artifacts

I have a java project built with Gradle in CircleCI.  This java project consists entirely of Selenium tests + framework that run on a pre-existing environment with SauceLabs.  I'd like to take the artifacts I'm generating (jar file) and let other team use it to exercise the my tests as part of their own pre-deploy test process but I'm not sure how I can accomplish this.
What would the yaml file look like to run JUnit tests on a jar file for CircleCI?  I've spent a good amount of time looking for answers online and I can't seem to find anything that meets this use case.

A:

I've finally figured out how to do this.  Below are some excerpts from my circle.yml files.

Generate and Save the artifacts in the automation project.

compile:
  post:
    - ./gradlew shadowJar
    - mkdir -p $CIRCLE_ARTIFACTS/build/libs
    - cp build/libs/* $CIRCLE_ARTIFACTS/build/libs

Download those artifacts in some other build project

dependencies:
  pre:
    # Install JQ - used when fetching automation artifacts
    - sudo apt-get update; sudo apt-get install jq
    - curl "https://circleci.com/api/v1.1/project/github/:org/:project/latest/artifacts?build=master&filter=successful&circle-token=$TOKEN" >> artifacts.txt
    - mkdir -p $HOME/automation
  post:
    # Fetch our UI automation jar
    - echo export ART_URL=$(cat artifacts.txt | jq '[.[]? | select(.url | contains("automation-ui-all.jar"))][0] | .url') >> $HOME/.circlerc
    - wget -O $HOME/automation/automation-ui-all.jar $ART_URL?circle-token=$TOKEN

Execute the Tests

- java -cp $HOME/automation/automation-ui-all.jar Main TEST_ENV=https://test.com


Q:

How to get Windows OS Environment Variable from System Property

I am encountering a strange problem about System Property environment variable.
As you know, we can open Computer->Property->Advanced System Settings->Advanced->System Environment Variables->User Variables for admin
I change Variable TEMP' value to C:\mytemp\ and click OK to save it.
However, In command line, when I echo %TEMP%, it still show original path, C:\Users\admin\AppData\Local\Temp.
When I input %TEMP% in explorer, it will go to C:\mytemp
Now I want to user API to get the path, GetEnvironmentVariable() will also return path which is same as echo %TEMP% in command line. how can I get the path as exploer did.
Thanks in advance.
PS. OS is Win7 x86

A:

Changing environment path through Computer->Property->Advanced System Settings->Advanced->System Environment Variables->User Variables will take effect immediately. However, please be noted that those programs which are running will not get the latest environment variable.
So I thought that you simply didn't reopen a new cmd for echo.
Open a new cmd, and echo again, the new path will be shown.


Q:

Is it correct to write a MySQL query like this?

Hello everyone what i want to know is if  writing a query like this is correct:
SELECT (SELECT t.name FROM type t WHERE t.id=a.id_type) AS TYPE,
       a.title title,a.description description,u.name name,u.email email
FROM advert a
INNER JOIN user u ON u.id=a.id_user
WHERE a.id='2';

I tested the query and it works, but what i want to know if it is correct by the standards to use a subquery and then a join .
Sorry if my question is stupid but i could't find an answer.

A:

Yes, this is allowed. It's called a correlated subquery. However, I think MySQL usually executes joins better:
SELECT t.name AS type, a.title title,a.description description,u.name name,u.email email
FROM advert a
INNER JOIN user u ON u.id=a.id_user
LEFT JOIN type t ON t.id = a.id_type
WHERE a.id = '2'


Q:

load file content into structure only if file exists or use default values

I have the following code:
typedef struct my_data {
 char* name;
}my_data;

my_data data[]={
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

void loaddata()
{
    FILE * in;
    if((in = fopen("data.txt","rt")) != NULL) {
        printf("start loading\n");
        int i = 0;
        while(!feof(in))
        {
            fscanf(in,"%s", &data[i].name);
            printf("%s\n",data[i].name);
            i++;
        };
    }
    else
        printf("loading not required\n");
    fclose(in);
}

And it gives me a "killed" error.
How can I load data from file data.txt into existing structure and in case file doesn't exist to use default values which were defined ?

A:

No need "&" in:
fscanf(in,"%s", &data[i].name);

and no need to close filestream if it's not opened.
void loaddata()
{
    FILE * in;
    if((in = fopen("data.txt","rt")) != NULL) {
        printf("start loading\n");
        int i = 0;
        while(!feof(in))
        {
            fscanf(in,"%s", data[i].name);
            printf("%s\n",data[i].name);
            i++;
        };
        fclose(in); /* need closing */
    }
    else
        printf("loading not required\n");
    /* no need closing */
}

UPD: create structure with allocated memory, not pointer. Pointer accesses part of program, not memory, so you cannot save data there.
typedef struct my_data {
    char name[10];
}my_data;


Q:

How to modify the default capacity instance role for EKS using CDK?

We're trying to setup logging using an EKS cluster. We're currently running a cluster with a single EC2 instance. AWS has provided kubectl commands that create the necessary kubernetes config.
When applying this to our existing EKS setup, we cannot properly define the instance role that has the permissions to write to CloudWatch.
the cloudwatch agent shows these errors in its pod logs:
2020-01-07T10:20:14Z E! CreateLogStream / CreateLogGroup with log group name /aws/containerinsights/eks-test-EKS/performance stream name ip-10-0-2-156.eu-central-1.compute.internal has errors. Will retry the request: AccessDeniedException: User: arn:aws:sts::662458865874:assumed-role/eks-test-ekstestEKSDefaultCapacityInstanceRole9446-7MD87BB2AA51/i-01e94e054f3c34383 is not authorized to perform: logs:CreateLogStream on resource: arn:aws:logs:eu-central-1:662458865874:log-group:/aws/containerinsights/eks-test-EKS/performance:log-stream:ip-10-0-2-156.eu-central-1.compute.internal
    status code: 400, request id: 645166c7-34fb-4616-9f27-830986e27469

The problem seems to me that CDK creates this cloudformation IAM instance role without the permission to write to CloudWatch:
  ekstestEKSDefaultCapacityInstanceRole9446FBA6:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/AmazonEKSWorkerNodePolicy
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/AmazonEKS_CNI_Policy
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/AmazonEC2ContainerRegistryReadOnly
      Tags:
        - Key: Name
          Value: eks-test/eks-test-EKS/DefaultCapacity
        - Key:
            Fn::Join:
              - ""
              - - kubernetes.io/cluster/
                - Ref: ekstestEKSBA2E781A
          Value: owned
    Metadata:
      aws:cdk:path: eks-test/eks-test-EKS/DefaultCapacity/InstanceRole/Resource

AWS also mentions that one should "check the IAM role", but the thing is that I don't know how to modify it.
In the EKS Cluster construct I can set a cluster role, but this is not the same and the instance role is still created with the missing permissions.
Is there some other CDK method I can modify the instance role or a workaround if there isn't?
UPDATE:
I've linked back to this question from an issue on CDK's github page. Someone mentioned the upcoming IAM roles for service accounts feature, but I'm wondering if "regular" IAM role mapping to kubernetes roles is the way to go here...
UPDATE:
The role seems to be created based on the AutoScalingGroup according to the CDK code. I assume this can be overwritten to add different roles...

A:

You can set the policy after creating the cluster on the DefaultCapacity
const cluster = new Cluster(this, name, clusterProps);
cluster.defaultCapacity?.role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName('CloudWatchFullAccess'));


Q:

How to register an android app user by using Laravel Api

I want to register a user by using laravel api. Api is live on the server also working on postman but in my app its not working. I am using retrofit2 library to use it. Here is the error
2019-05-06 17:23:44.134 473-473/com.engrsoft.www.onlineservices E/response String: Response{protocol=http/1.1, code=200, message=OK, url=http://zattest.com.zawataafnantechnologies.com/newapi/api/register}

Api.java

public interface Api {

    @FormUrlEncoded
    @POST("register")

    Call<ResponseBody> register(
            @Field("name") String name,
            @Field("email") String email,
            @Field("password") String password
    );

RetrofitClient.java

public class RetrofitClient {

    private static final String BASE_URL="http://zattest.com.zawataafnantechnologies.com/newapi/api/";

    private static RetrofitClient retrofitClient;
    private Retrofit retrofit;

    private RetrofitClient(){
        retrofit= new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static synchronized RetrofitClient getRetrofitClient(){
        if (retrofitClient == null){
            retrofitClient = new RetrofitClient();
        }
        return retrofitClient;
    }
    public Api getApi(){
        return retrofit.create(Api.class);
    }

RegisterActivity.java

Register Method. Response is coming but not success
public void register(){

                        Call<ResponseBody> call = RetrofitClient
                                .getRetrofitClient()
                                .getApi()
                                .register(txt_username,txt_email,txt_password);
                        call.enqueue(new Callback<ResponseBody>() {
                                         @Override
                                         public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                                             String s= response.toString();
                                             Log.e("response String", s);
                                             Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();

                                         }

                                         @Override
                                         public void onFailure(Call<ResponseBody> call, Throwable t) {
                                             Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

                                         }
                                     }
                    }

A:

This message
2019-05-06 17:23:44.134 473-473/com.engrsoft.www.onlineservices E/response String: Response{protocol=http/1.1, code=200, message=OK
does not signify an error response as you said. In fact it is an Ok / success message which means the request has succeeded.
Now you are not logging the response body. So change
String s= response.toString();
to
String s= response.body().toString(); for receiving proper message from backend


Q:

node.js -- get data out of a callback function

my node.js code like this:
var data = "";
//redis client
client.get(key,function(err,value){
    data += value;
});
//output
console.log(data);

BUT, it prints nothing. Why so? and how can i get the data out of the callback function?
thanks a lot.

A:

Your passing the redis client a callback which will be called later (when the data is returned over the network), but then right after making the redis call you're trying to print the value before redis has sent you a value.  You need to wait for redis to return a value.
Try this
var data = "";
//redis client
client.get(key,function(err,value){
    data += value;
    //output
    console.log(data);
});


Q:

Broken Spring Boot Debugging process - ignoring breakpoints

I've encountered the same issue twice. As soon as I try to upgrade the spring boot maven plugin version to something greater than 1.0.1 release the application does not stop on any of the debug breakpoints.
During the development we identified the problem and we had to fallback to 1.0.1 while being on Spring Boot parent 1.1.9 What are the risks of such decision I can only guess.
 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.1.9.RELEASE</version>
                <!-- <version>1.0.1.RELEASE</version> works flawlessly-->
            </plugin>
        </plugins>
    </build>

http://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html  - this link never helped. The application just hangs waiting infinitely.
There is a workaround if you are running in default profile just by debugging the application class, but hey I can't configure anything else in this case.
Screenshot demonstrating how the debugger failed to stop on the very first breakpoint and application started instead.

A:

The goal spring-boot:run forks java process and your application is started in the other one then your debugger is attached. You have to use that page http://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html to setup correct debugging parameters for forked process and then use IntelliJ's feature "Remote Debug".


Q:

Understanding cluster state update

I'm reading gossip akka cluster documentation and still have one little misunderstanding about gossip.
As said in this answer, two nodes are gossiping about the value and then who seen this value. But this comes with some issue about convergence. Here's how I see this:
S - is a seen set.

The issue is at some time, only node 4 knows that convergence happened. node 1, 2 and 3 still think it does not. I'm interesting about how should node 4 deal with convergence?
Should it initiate a new gossip round that convergence happened? Or how can other nodes know about it?

A:

Nodes 1-3 will still be gossiping (well, 3 probably already knows about convergence because it knows 4 has the value.) As they continue gossiping they will be exchanging notes on who has seen the value.
Node 4 (and 3 really), and all subsequent nodes knowing about convergence continue gossiping but without the random weighting mentioned in your other question. In the protocol section of your linked doc it says:

While the cluster is in a converged state the gossiper only sends a small gossip status message containing the gossip version to the chosen node. As soon as there is a change to the cluster (meaning non-convergence) then it goes back to biased gossip again.


Q:

Where are trace files saved in PeopleSoft?

In PeopleSoft Enterprise, there is an option to enable tracing options from the signon screen. (Tracing options are also accessible after logon from PeopleTools > Utilities > Debug)
I've enabled tracing for SQL statements for debugging purposes. However, I can't figure out where to find my trace logs on the server once the session is complete.
Where are trace logs saved in PeopleSoft when trace flags are enabled?

A:

Typically they are on the Application Server under the directory for your environment.
e.g.

<PS_HOME>/appserv/<domain>/LOGS (quoted from article)
/opt/test/psft/pt/8.53/appserv/prd/LOGS/PSAPPSRV.10742/process_state.txt (quoted from blog entry)
$PS_CFG_HOME/appserv/<DOMAIN>/LOGS (quoted from blog entry)


Q:

Xcode fails to generate Adhoc IPA

Everything was working as expected but I've recently updated Xcode to 7.1.1 and it stopped to build IPA files in Adhoc.
After successfully archiving I click the Export option -> Save for Ad Hoc Deployment -> select my development team -> hit Next with "Export one app for all compatible devices" option -> Next (with Rebuild from bitcode checked). The error I get is this:

A:

The only workaround I found was to uncheck the "bitcode" option then everything went normal.


Q:

rotating cogs in java

First of all my english is rubbish, so please understand.
I have been asked to do a little simulation/animation in java.
I have a few cog on board one of the cogs rotates all the time on its axis. when I move any other cog close to the rotating one it has to start rotating  and teeth can not overlap each other.
I think this link describes it quite well
http://www.csharphelper.com/howto_animate_gear.gif
I don't know how to make this cogs interact together, i will be really happy if some can show some code example
Many thanks for any help

A:

If you know how to rotate the kog, you could cheat a bit, and hard-code the timing so that they rotate at the right time :P

A:

This is a classic LCM (Least Common Multiple) problem: try to formulate a solution from the dimensions (radius or diameter or circumference) of the cogs.


Q:

What is the most optimal data structure to use for this scenario?

I'm doing a data migration at the moment and one task I'm doing is matching primary keys from the old DB to the new one for each table. There's probably about 40 tables in the whole migration and as I'm only moving some of the data across, I want to prevent creating duplicate new records in the new DB.
So I want to store multiple collections of pairs of integers (oldPK and newPK). Each collection represents a table and each pair represents a row I've already migrated across. I am frequently going to be searching on the oldPK in order to see if I've already migrated a particular row in a table.
I'm unsure about how many pairs of integers I may have, although I am sure that it will not exceed the number of rows in the old DB's table, which would typically be from 100 to about 5000. (I could entertain the idea of different collections having different data structures)
Also, I will not be populating the list all at once, it is likely to occur one integer pair at a time, typically when I've written that record to the new DB.
I've tried using a List - T being a class that has integers A and B, but it seems to slow down as the collection gets very big.
Is there a better data structure I could use for this scenario?
CONCLUSION
ok so I just did a test with all different data types (eg. hashset, list, dictionary, SortedDict, SortedSet, SortedList, Hashtables).
Hashtable came out hands down the fastest. We're talking calculations which took the other data structures 5-10 seconds, it would take less 0.1 seconds!

A:

Use a hashtable.  This has very quick lookup to see if a particular key - for example your old ID - is in it.  It will not slow down appreciably even if you have gazillions of rows in it.


Q:

Did any character in "A Scanner Darkly" resemble Philip K. Dick himself?

The ends of the book and movie versions of "A Scanner Darkly" list people author Philip K. Dick knew who suffered illnesses due to long-term drug use, and Dick himself is on the list.
Indeed, as wiki explains, Dick had a long history of amphetamine use and even shared a house with other addicts -- experience that no doubt helped him write about the cranked-up addict roommates in "A Scanner Darkly" with such realistic description and dialogue.
With that in mind, I've always wondered -- did any of the main characters in "A Scanner Darkly" resemble Philip K. Dick himself? In other words, did he write himself into his story?
(The movie had five main characters: Keanu Reeves as relatively straight-edge Bob Arctor/Fred/Bruce. Robert Downey, Jr. as fast-talking schemer James Barris. Woody Harrelson as lunky stoner Ernie Luckman. Rory Cochrane as burned-out geek Charles Freck. Winona Ryder as shady cokehead Donna Hawthorne/Audrey/Hank.)

A:

While in an interview, Dick says that "everything in A Scanner Darkly I actually saw," in the
author's note for the book, in which he makes the dedication you mention, he says:

I myself, I am not a character in this novel; I am the novel.


Q:

get standard output and error output in different files in C

I'm trying to solve a problem because I'm learning to use system calls in C. I used a Ubuntu 12.04 64bit.
I have this statement:
Implement a code that allows to redirect the standard out of the two commands deferred into a file (standard output) and all error output into another file (error file). The names of the files will be specificated using out parameter (for the name of standard out) and parameter -err (for the name of error file).
Syntax: after2 [args...] --do  [args...] --out --err
It's not specified in the statement but I think that I need to use pipes.
Also I can't use printf, scanf, getc...  family functions.
And i have that code:
#include <syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int cmd1 = system("sleep 5");
    int cmd2 = write(1, "hello world", 11);

    if((cmd1 != (0)))
    {
        write(1,"error in command 1",18);
    }
    if((cmd1==(0)))
    {
        write(1, "hello world", 11);
    }
    return EXIT_SUCCESS;
}

My question is, do you know some examples about similar questions? I look for some but I didn't find, also if you know other ways to help me I'm happy to accept.
I post the code that I've now without erase the last version, by this way all people can see the evolution.
#include <syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    const char* cmd1 = system("sleep 5");
    const char* cmd2 = write(1, "hello world", 11);
    int out_fd = creat("out.txt",0644);
    int err_fd = creat("err.txt",0644);

    if(out_fd < 0){
        write(2, "Can't open file out.txt", strlen("Can't open file out.txt"));
        dup2(err_fd, 2);
        write(2, "Can't open file out.txt \n", strlen("Can't open file out.txt \n"));

        return -1;
        }else if(err_fd < 0){
            write(2, "Can't open file err.txt", strlen("Can't open file err.txt"));
            dup2(err_fd, 2);
            write(2, "Can't open file err.txt \n", strlen("Can't open file err.txt \n"));

            return -1;
        }
    if((cmd1 !=(0)))
    {
        write(2, "There is an error on command1", strlen("There is an error on command1"));
        dup2(err_fd, 2);
        write(2, "Error on command1 \n", strlen("Error on command1 \n"));

        return -1;
        }else if((cmd1==(0)))
        {
            write(1, "success on command1", strlen("success on command1"));
            dup2(out_fd, 1);
            write(1, "success on command1 \n", strlen("success on command1 \n"));
            write(1, "hello world", 11);

            if((cmd2==(0)))
            {
                write(1, "hello world", strlen("hello world"));
                dup2(out_fd, 1);
                write(1, "hello world \n", strlen("hello world \n"));

            }
            if((cmd2 != (0)))
            {
                write(2, "There is an error on command2", strlen("There is an error on command2"));
                dup2(err_fd, 2);
                write(2, "Error on command2 \n", strlen("Error on command2 \n"));

            }
        }
return 0;
}

This time prints in the shell hello worldsuccess on command1There is an error on command2 and success on command1 and hello world in out.txt and There is an error on command2 in err.txt but I don't know why prints There is an error on command2 and in the same time prints hello world, any idea
Obviously I've some errors yet but I'm not sure what I need to do if anyone can help me I'll be happy!
Thanks.

A:

Well, finally I've got a code that seems that it works, I changed the command cmd2 = write(1, "hello world", 11); for  cmd2 = system("echo $HOME"); because I've troubles to write in a file a write function, changing this I achieve my objective fastly:
#include <syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    const int cmd1 = system("sleep 5");
    int out_fd = creat("out.txt",0644);
    int err_fd = creat("err.txt",0644);

    if(out_fd < 0){
        //write(2, "Can't open file out.txt", strlen("Can't open file out.txt"));
        dup2(err_fd, 2);
        write(2, "Can't open file out.txt \n", strlen("Can't open file out.txt \n"));

        return -1;
        }else if(err_fd < 0){
            //write(2, "Can't open file err.txt", strlen("Can't open file err.txt"));
            dup2(err_fd, 2);
            write(2, "Can't open file err.txt \n", strlen("Can't open file err.txt \n"));

            return -1;
        }
    if((cmd1 !=(0)))
    {
        //write(2, "There is an error on command1", strlen("There is an error on command1"));
        dup2(err_fd, 2);
        write(2, "Error on command1 \n", strlen("Error on command1 \n"));

        return -1;
        }
    if((cmd1==(0)))
    {

        //write(1, "success on command1", strlen("success on command1"));
        dup2(out_fd, 1);
        write(1, "success on command1 \n", strlen("success on command1 \n"));
        const int cmd2 = system("echo $HOME");;

        if(( cmd2==(0)))
        {

            //write(1, "success on command2", strlen("success on command2"));
            dup2(out_fd, 1);
            write(1, "success on command2 \n", strlen("success on command2 \n"));

        }
        else if(( cmd2 !=(0)))
        {

            //write(2, "There is an error on command2", strlen("There is an error on command2"));
            dup2(err_fd, 2);
            write(2, "Error on command2 \n", strlen("Error on command2 \n"));

        }
    }
return 0;
}

Only have a little problem, when I build an exe appears a warning who says:
warning:implicit declaration of function 'creat'[-Wimplicit-function-declaration]
int out_fd = creat("out.txt",0644);
If anyone knows how to correct it please tell me. Thanks for all your help!


Q:

Qt Creator: как различать debug и release из проекта?

В pro-файле нужно указать разные настройки для debug и release конфигурации. Почитал документацию, вроде как утверждается, что нужно использовать named scopes debug и release. Я сделал небольшой тестовый проект такого вида:
TEMPLATE = app
SOURCES += main.cpp

message(===Run config===)
debug {
    message(===Debug===)
    SOURCES += debug.cpp
}

release {
    message(===Release===)
    SOURCES += release.cpp
}

В файлах debug.cpp и release.cpp опрделена одна и та же фунция.
Открываю проект в Qt Creator, настраиваю проект для сборки с использованием MinGW, выбираю конфигурацию Debug, запускаю сборку - в результате в консоли вижу:
Project MESSAGE: ===Run config===
Project MESSAGE: ===Debug===
Project MESSAGE: ===Release===
Project MESSAGE: ===Run config===
Project MESSAGE: ===Debug===
Project MESSAGE: ===Release===
Project MESSAGE: ===Run config===
Project MESSAGE: ===Debug===
Project MESSAGE: ===Release===

Конфигурирование выполняется три раза, причём на каждом разе включена одновременно и дебаговая и релизная конфигурации. Как следствие в проект включаются одновременно оба файла и на этапе линковки получаем сообщение об ошибке:
Src\build-qmake-test-Desktop_Qt_5_12_3_MinGW_64_bit-Debug/../qmake-test/release.cpp:4: multiple definition of `printMessage()'

Подскажите пожалуйста, в чём тут дело? Может быть я что-то делаю не так? Какой правильный способ определять релизная сейчас конфигурация или дебаговая?

A:

Похоже я нашёл решение. Оно здесь. Оказывается это баг не то в qmake, не то в Qt Creator. Нужно писать так:
CONFIG(debug, debug|release) {
    message(===Debug===)
    SOURCES += debug.cpp
}

CONFIG(release, debug|release) {
    message(===Release===)
    SOURCES += release.cpp
}

Причём открывающая фигурная скобка должна быть на той же строке что и конструкция CONFIG. Иначе выражение будет всегда считаться как TRUE.


Q:

Google Chrome Stable crashing at launch

After a recent update in Ubuntu 16.04 chrome refused to launch with the following output to terminal:
~$ google-chrome-stable
[5525:5562:0327/115046.503718:ERROR:nss_util.cc(724)] After loading Root   Certs, loaded==false: NSS error code: -8018
[5525:5550:0327/115046.527819:ERROR:in_progress_cache_impl.cc(93)] Could  not read download entries from file because there was a read failure.
--2018-03-27 11:50:46--  https://clients2.google.com/cr/report
Resolving clients2.google.com (clients2.google.com)... 216.58.213.110,  2a00:1450:4009:811::200e
Connecting to clients2.google.com   (clients2.google.com)|216.58.213.110|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘/dev/fd/4’

Crash dump id: 77bf82c7db6d1e8e

     0K                                                         602K=0s

Bus error (core dumped)

I tried purging chrome with sudo apt purge google-chrome-stable and reinstalling but it still wouldn't launch even after a reboot.

A:

The only thing that worked was purging both google-chrome-stable and chromium-browser with sudo apt purge google-chrome-stable and sudo apt purge chromium-browser and then deleting any files and folders which point to chrome or chromium under ~./cache/ and ~./config/. eg. rm -r ~/.cache/google-chrome/ etc.


Q:

Why won't my phototransistor interrupt my microcontroller?

I bought a couple of phototransistors. They all have one lead shorter than the other. I assume that, like normal diodes, this means that the longer lead goes to V+ and the short end goes to GND.
I set the phototransistor up like so:

I put the output line into my interrupt pin on my microcontroller. When I shine a bright light on the phototransistor, the microcontroller doesn't interrupt.
BUT!!
When I put the same output into my ADC my microcontroller says it reads 5V with the light shining on the phototransistor. It also reads 0.8V when the phototransistor is covered.
Why would a multimeter and ADC read the output as Low/High but it won't trigger an interrupt on my microcontroller. (I know the problem isn't the code because I can take a straight wire from 3.3V to the interrupt pin and it will interrupt.)
EDIT
The logic level is 5V. I put the output pin to a green LED which then goes to ground. When I shine the light on the phototransistor, the green LED lights up. So I'm confident I have enough current.
I want it to trigger when light shines on it and pulls the pin high.
SOLUTION
I had two problems here that combined into a really annoying problem. The first problem was the one stated above. The other problem was that there wasn't enough current flow. I solved both problems by stacking four phototransistors in parallel in a pullup configurations and reversing the leads.
Thanks to Nedd for the suggestion to switch from pulldown to pullup. That made them much more sensitive. I also realized I had my phototransistors pointing the wrong direction.
For this reason I've marked Nedd's answer as the most correct.
I know my solution is not ideal. It's pretty hackish, which is why I didn't answer my own question and mark it as correct. In the future I will probably opt for a different solution, such as the TI OPT-101.

A:

The residual 0.8v shows that the photo transistor has current leakage even when dark.  Using a lower value Re may help.  Better yet, reverse the positions of the resistor and photo transistor, then detect a low going signal when shining the light, (a higher value resistor could be used in this case)..


Q:

Getting the key of an array item while in a numerically indexed loop

Possible Duplicate:
For..In loops in javascript - key value pairs

I need to loop through an array in order, just like in this question. However, I also need to get access to the key name. How can I do that while in a numerically indexed loop?
for(i=0; i<arr.length; i++){
    alert(arr[i].key); // clearly won't work
}

but
for(key in arr){
    alert(arr[key]); // works, but it doesn't loop through in the right order
}

A:

You cannot list through an JavaScript object's properties and expect them to be returned in a particular order.
Read this blog post and check out the part about for loop order.


Q:

Do we accept edits that simply update the characters used for accidentals?

I recently rejected some edits to previous posts of mine that used Gb, F# notation where the edit was just replacing these notations with G♭ and F♯, using Unicode code points U+266D–U+266F.
Personally I don't see a point to this — the unicode chars are harder to type and leave more room for error on the rendering side, so I think we should leave it up to the author and seek internal consistency. I rejected the edits as not substantive.
Not wearing the mod hat anymore, I'm not too worried about this, but seeing that the proposed edit was from an enthusiastic new user, I think we should have some guidance on the books: should we proactively be mopping up old posts to use the new unicode glyphs, a la Wikipedia? Yea or nay?

A:

I have accepted these sorts of edits before, on the grounds that the actual music notation symbols look better than # and b, and thus are improvements to the original post. But....
Your comment that use of the Unicode code points may "leave more room for error on the rendering side" has caused me to think again about this. I use the Unicode characters all the time, but I have seen some users complain in the comments that the Unicode characters aren't rendering on their systems. Further, I have noticed that the Unicode characters seem to render as smaller characters, which are often not as legible as their simpler Latin alphabet approximations (especially on smaller screens). E.g. # vs ♯, b vs ♭, x vs , bb vs . I don't know how to best communicate a natural with a Latin character, but ♯ and ♮ can be difficult to distinguish, so it may be best to use # for sharp and ♮ for natural.
All of this to say that, upon reflection, I don't think that changing these symbols to their Unicode counterparts improves the clarity of a post, and it may even reduce clarity. I won't be accepting these edits any longer, and I may even go back to using Latin characters, except for naturals, in the interest of improved clarity and access.

A:

I'd have to agree that an edit like that is non-substantive and should be rejected.
I get the utility of unicode chars, and if an edit was fixing numerous other problems, then sure, using the correct symbols for sharp and flat would be fine, but the b and # work well enough.
In the case of a new user, I think just reiterative the requirement for substantive change should be enough.


Q:

Error correction that adapts to different error rates

Say we have $N$ bits that we'd like to store in an $M$-bit error correcting code, where $M > N$.  Given $\epsilon > 0$, as long as $N > N_0(\epsilon)$ we can recover the original bits as long as any $N(1+\epsilon)$ of the $M$ bits are correct.
Now say the bits are ordered in decreasing order of importance.  Can we pick a single $M$-bit code so that if $K > K_0(\epsilon)$ out of the $M$ bits are uncorrupted, we can recover the first $K(1 - \epsilon)$ original bits correctly?  Here the difference is that the code is independent of $K$.

A:

This is impossible as stated.  Consider $M = N, K = N/2$.  Up to $\epsilon$, we're asking to be able to recover the whole input from the whole code, and the first half of the input from either the first half of the code or the second half.  But if we can recover the first half of the input from the first half of the code, this implies we can recover the second half of the input from the second half of the code, and vice versa.  Thus we can recover both halves of the input from the first half of the code, which is impossible.


Q:

VBA: Limiting cell range with functions

How do you write a function in VBA that lets the user enter a range as a parameter, and set the upper/lower bounds for that range (in case they enter a whole column)?
I have a function that looks at a cell and sees if it contains any words listed in a glossary (I just allow the user to select a column (range) that is the list of glossary terms. I currently use a for each cell in range loop to go through the range, but I don't want to waste steps going through ALL the cells in column A, even if I am checking first if Len(cell.value) <> 0.
I am guessing it's done with a select statement, but I'm now sure how to do that to a range that was passed as a parameter (I call it cell_range right now).
Any help would be greatly appreciated!
Added Info:
The data type of the range is of type string. It's a list of English words (glossary terms) and I am writing a function that will look at a cell and see if it includes any of the terms from the glossary. If it does, the code returns the glossary term plus the offset cell to the right (the translated term).
EDIT (06.20.11)
Finalized code thanks to experimentation and suggestions below. It takes a cell and looks for any glossary terms in it. It returns the list of terms, plus the translated terms (second column in glossary).
Function FindTerm(ByVal text As String, ByVal term_list As range) As String

Static glossary As Variant
Dim result As String
Dim i As Long

glossary = range(term_list.Cells(1, 1), term_list.Cells(1, 2).End(xlDown))

For i = 1 To UBound(glossary)
    If InStr(text, glossary(i, 1)) <> 0 Then
       result = (glossary(i, 1) & " = ") & (glossary(i, 2) & vbLf) & result
    End If
Next

If result <> vbNullString Then
    result = Left$(result, (Len(result) - 1))
End If

FindTerm = result

End Function

A:

Why not limit your loop to the filled cells efficiently?
For Each c In Range("a:a").SpecialCells(xlCellTypeConstants)
   ....
Next c

A:

To answer the direct question, you can't restrict what is passed as a parameter, but you can derive a new range from a passed range.
That said, looping through a range is very slow.  There are may alternative methods:

Query based methods, as suggested by Remou
Copy the range to a variant array and loop through that
Dim vDat as variant
vDat = cell_range
vDat is now a two dimensional array
Use the built in search function Find
cell_range.Find  ...
Use Application.WorksheetFunction.Match (and/or .Index .VLookup)

Which one best suits depend on the specifics of your case
Edit
Demo of the variant array approach
Function Demo(Glossary As Range, search_cell As Range) As String
    Dim aGlossary As Variant
    Dim aSearch() As String
    Dim i As Long, j As Long
    Dim FoundList As New Collection
    Dim result As String
    Dim r As Range
    ' put data into array
    aGlossary = Range(Glossary.Cells(1, 1), Glossary.Cells(1, 1).End(xlDown))

    ' assuming words in search cell are space delimited
    aSearch = Split(search_cell.Value, " ")
    'search for each word from search_cell in Glossary
    For i = LBound(aSearch) To UBound(aSearch)
        For j = LBound(aGlossary, 1) To UBound(aGlossary, 1)
            If aSearch(i) = aGlossary(j, 1) Then
                ' Add to found list
                FoundList.Add aSearch(i), aSearch(i)
                Exit For
            End If
        Next
    Next

    'return list as comma seperated list
    result = ""
    For i = 1 To FoundList.Count
        result = result & "," & FoundList.Item(i)
    Next
    Demo = Mid(result, 2)
End Function


Q:

Passing expressions by reference inside expressions

I am fairly new to Julia, so apologies for any misunderstandings of the language I may have.  I have mostly used Python recently, and made heavy use of SymPy and its code generation features, and it seems like Julia with its metaprogramming features is built for writing code in exactly the kind of style I like.
In particular, I want to construct block matrices in Julia from a set of smaller building blocks with some different operations in between.  For debugging purposes and because the various intermediate matrices are used in other calculations, I want to keep them as expressions containing variables, such that I can quickly loop over and test different different inputs, without wrapping everything in a function.
Now, for a minimal case study, say I have two expressions mat1 = :a and mat2 = :b that I want to combine to form a new, third expression:
mat3 = :($mat1 + $mat2)

The above method works fine until I modify mat1 and mat2, in which case I have to re-evaluate mat3 in order to reflect this update.  This is caused, I presume, by the fact that $mat1 + $mat2 is not passing mat1 and mat2 by reference, but rather interpolates the expressions inside at the time of evaluation of that line.  The behaviour I want to achieve is that mat1 and mat2 are not inserted until I call eval(mat3), preferably with minimal boilerplate.
Is it possible to achieve this in a handy syntax?

A:

mat3 will reflect the mutation of mat1 and mat2, but not rebinding of mat1 and mat2. It is important to understand the distinction between mutation and rebinding.
Mutation
Mutation occurs when the data of an object is modified. Note that this does not affect any names, only objects. This can manifest in many ways, including functions like push! and assignment syntax with a complex left-hand side, like A[1] = 5.
For example, all of the following are examples of mutation:
A = [1, 2, 3]
A[1] = 4

The name A is unchanged; A still points to the same object. The object that A represents is modified.
A = :(f(x))
A.args[1] = :g

The name A is unchanged; A still points to the same object. The object that A represents is modified.
mat1 = :(f(x))
mat2 = :(f(y))
mat3 = :($mat1 + $mat2)
mat1.args[1] = :g

The name mat1 is unchanged; it still points to the same object. That object is modified. mat3 references that same object also, and because it's been modified, it will reflect the changes. Indeed, now mat3 contains :(g(x) + f(y)).
Rebinding
(also known as assignment)
Rebinding occurs when no object data is modified but the target of a name is changed to that of a different object. This is indicated by a simple = assignment, with the left hand side being the thing rebound.
x = 2
x = 3

Here x is being rebound from the object 2 to the object 3. We are not changing the object 2. In fact, because 2 is an immutable object, it is not allowed to mutate the object 2. Instead, the reason the observable value of x has changed is because it references a different object now: 3.
A = [1, 2, 3]
A = [4, 2, 3]

Once again here we are not mutating the vector A; we're creating a new vector and now A references this new vector. Distinguishing between mutation and rebinding is important. Once again, mutation acts on objects, and rebinding acts on names.
mat1 = :x
mat2 = :y
mat3 = :($mat1 + $mat2)
mat1 = :z

Note here that the simple assignment does not mutate the object :x that mat1 references; it simply rebinds mat1 to the different object :z. This means that mat3, which contains the object :x, will not be affected.
Note that Symbol is an immutable type, so you cannot mutate it. Thus it is impossible to do what you're proposing.
A better way to do what you're proposing is to use a function instead of a single expression. A function can be called multiple times, producing different objects.
mat1 = :x
mat2 = :y
mat3() = :($mat1 + $mat2)  # function definition
mat3()  # :(x + y)
mat1 = :z
mat3()  # :(z + y)


Q:

grep remote machine with ] character

I am trying to search a file in remote server.The pattern I am looking for is ] LEADER, e.g. [T2] LEADER matches.My command is: ssh myname@ip grep -r "] LEADER" logfile However, the error grep : LEADER: no such file is reported. May I know how to solve this?

A:

The shell aborbs the double quotes, so the "grep" on the remote machine sees three arguments - "]", "LEADER" and "logfile"
Change to:
   ssh myname@ip grep -r "\"] LEADER \"" logfile


Q:

How can I change image source in javascript using "this"?

I have a div element with id = "image" having no background-image initially.
I have an another image, on which when I hover, somefunction(this) is called.
Now, I want this function to change that div's background image to the hovered image.
I am doing something like this...
HTML:

 a division

CSS:
#image{ background-image : url(''); }

JS:
function somefunction(element)
{
    var x = document.getElementById('image');
    x.style.background.src = element.src;
}

But It's not working anyway, and I want to do this using "this" only.

A:

Try this code

function somefunction(element)
 {
  var x = document.getElementById('image');
  x.style.backgroundImage = "url('"+element.src+"')"
 }

 a division


Q:

Корректное сохранение/использования числа HEX

Получаю число на входе (int) в hex
например 0xff6699ff
но если я его, например, читаю через
System.out.println(0xff6699ff);
то вместо ожидаемого 4284914175 в десятичной системе,
я получаю -10053121
Как мне получить корректное отображение?

A:

Для хранения этих чисел используйте тип long. Тип int вмещает максимальное значение 2147483647, а вам этого не хватает. Происходит переполнение и число становится отрицательным.
Если вы добавите в конец числа литеру L, то вывод будет верным.
System.out.println(0xff6699ffL);

Соответственно, ваш список должен состоять из объектов класса Long:
ArrayList<Long> hexColors;


Q:

How do I reorganize data in R consisting of 8 repeating rows, with 24 columns?

I'm quite new to R, so please be patient with me (at the same time I'll try to respect your time by being as descriptive as possible).
I've got data that I've been trying to format properly for a while now that describes 8 measurements taken every hour for a little over a year. Because of the way that I had to retrieve the data, the spreadsheet I have now lists the data in a tabular format, with the 8 variable names listed as repeating rows, and each hour of the day as a separate column, like this:
var1[0] var1[1] var1[2] var1[3] var1[4] var1[5] var1[6] var1[7] var1[8] var1[9] var1[10] var1[11] var1[12] var1[13] var1[14] var1[15] var1[16] var1[17] var1[18] var1[19] var1[20] var1[21] var1[22] var1[23]
var3[0] var2[1] var2[2] var2[3] var2[4] var2[5] var2[6] var2[7] var2[8] var2[9] var2[10] var2[11] var2[12] var2[13] var2[14] var2[15] var2[16] var2[17] var2[18] var2[19] var2[20] var2[21] var2[22] var2[23]
var3[0] var3[1] var3[2] var3[3] var3[4] var3[5] var3[6] var3[7] var3[8] var3[9] var3[10] var3[11] var3[12] var3[13] var3[14] var3[15] var3[16] var3[17] var3[18] var3[19] var3[20] var3[21] var3[22] var3[23]
var4[0] var4[1] var4[2] var4[3] var4[4] var4[5] var4[6] var4[7] var4[8] var4[9] var4[10] var4[11] var4[12] var4[13] var4[14] var4[15] var4[16] var4[17] var4[18] var4[19] var4[20] var4[21] var4[22] var4[23]
var5[0] var5[1] var5[2] var5[3] var5[4] var5[5] var5[6] var5[7] var5[8] var5[9] var5[10] var5[11] var5[12] var5[13] var5[14] var5[15] var5[16] var5[17] var5[18] var5[19] var5[20] var5[21] var5[22] var5[23]
var6[0] var6[1] var6[2] var6[3] var6[4] var6[5] var6[6] var6[7] var6[8] var6[9] var6[10] var6[11] var6[12] var6[13] var6[14] var6[15] var6[16] var6[17] var6[18] var6[19] var6[20] var6[21] var6[22] var6[23]
var7[0] var7[1] var7[2] var7[3] var7[4] var7[5] var7[6] var7[7] var7[8] var7[9] var7[10] var7[11] var7[12] var7[13] var7[14] var7[15] var7[16] var7[17] var7[18] var7[19] var7[20] var7[21] var7[22] var7[23]
var8[0] var8[1] var8[2] var8[3] var8[4] var8[5] var8[6] var8[7] var8[8] var8[9] var8[10] var8[11] var8[12] var8[13] var8[14] var8[15] var8[16] var8[17] var8[18] var8[19] var8[20] var8[21] var8[22] var8[23]

var1[24] var1[25] var1[26] var1[27] var1[28] var1[29] var1[30] var1[31] var1[32] var1[33] var1[34] var1[35] var1[36] var1[37] var1[38] var1[39] var1[40] var1[41] var1[42] var1[43] var1[44] var1[45] var1[46] var1[47]
var2[24] var2[25] var2[26] var2[27] var2[28] var2[29] var2[30] var2[31] var2[32] var2[33] var2[34] var2[35] var2[36] var2[37] var2[38] var2[39] var2[40] var2[41] var2[42] var2[43] var2[44] var2[45] var2[46] var2[47]
var3[24] var3[25] var3[26] var3[27] var3[28] var3[29] var3[30] var3[31] var3[32] var3[33] var3[34] var3[35] var3[36] var3[37] var3[38] var3[39] var3[40] var3[41] var3[42] var3[43] var3[44] var3[45] var3[46] var3[47]
var4[24] var4[25] var4[26] var4[27] var4[28] var4[29] var4[30] var4[31] var4[32] var4[33] var4[34] var4[35] var4[36] var4[37] var4[38] var4[39] var4[40] var4[41] var4[42] var4[43] var4[44] var4[45] var4[46] var4[47]
var5[24] var5[25] var5[26] var5[27] var5[28] var5[29] var5[30] var5[31] var5[32] var5[33] var5[34] var5[35] var5[36] var5[37] var5[38] var5[39] var5[40] var5[41] var5[42] var5[43] var5[44] var5[45] var5[46] var5[47]
var6[24] var6[25] var6[26] var6[27] var6[28] var6[29] var6[30] var6[31] var6[32] var6[33] var6[34] var6[35] var6[36] var6[37] var6[38] var6[39] var6[40] var6[41] var6[42] var6[43] var6[44] var6[45] var6[46] var6[47]
var7[24] var7[25] var7[26] var7[27] var7[28] var7[29] var7[30] var7[31] var7[32] var7[33] var7[34] var7[35] var7[36] var7[37] var7[38] var7[39] var7[40] var7[41] var7[42] var7[43] var7[44] var7[45] var7[46] var7[47]
var8[24] var8[25] var8[26] var8[27] var8[28] var8[29] var8[30] var8[31] var8[32] var8[33] var8[34] var8[35] var8[36] var8[37] var8[38] var8[39] var8[40] var8[41] var8[42] var8[43] var8[44] var8[45] var8[46] var8[47]

There was initially quite a bit more to the data, but I've stripped it down to this in an effort to get to the bottom of the issues I've been having. (In the above example, what I'm trying to imply is that at each hour (t1, t2, t3, etc.) the variables (var1, var2, var3, etc.) are recorded.
My goal is to reformat it so that it resembles something like this:
var1[0] var2[0] var3[0] var4[0] var5[0] var6[0] var7[0] var8[0]
var1[1] var2[1] var3[1] var4[1] var5[1] var6[1] var7[1] var8[1]
var1[2] var2[2] var3[2] var4[2] var5[2] var6[2] var7[2] var7[2]
var1[3] var2[3] var3[3] var4[3] var5[3] var6[3] var7[3] var7[3]
.       .       .       .       .       .       .       .
.       .       .       .       .       .       .       .
.       .       .       .       .       .       .       .
[all the way to 9216, which is the number of hours in 384 days]

So far, I've tried working with it in Excel at length and cannot find a way to do this. I've also looked into writing a C++ script as I've done before, but I feel like there may be a simpler way. My latest effort has been to turn to R, as I've been trying to learn it and I hear that it is well-suited for this kind of data manipulation. With R, I attempted to follow an example I found that had me recreate the data as a matrix of a different length (found here), but this led to fantastically erroneous data. (I'm sure I probably misused the method). I also looked into the solution discussed here, but I was unable to modify the code to work with my situation. Perhaps I'm overlooking something simple?
Does anyone have any suggestions? As I said, at this point I'm trying to do this in R, but I'm open to suggestions in Excel, C, or python. (I'm definitely open to suggestions in other languages but that'll probably require a bit more thorough explanation :) )
Thanks!
[edit:]
The above data samples were meant to be descriptive. Below is what the actual first 25 lines of the data looks like; the only change I've made is to substitute the variable names for confidentiality reasons:
Metric,Year,Month,Day,DOW,12am,1am,2am,3am,4am,5am,6am,7am,8am,9am,10am,11am,12pm,1pm,2pm,3pm,4pm,5pm,6pm,7pm,8pm,9pm,10pm,11pm
varA,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,9,22,10,18,24,26,11,21,24,10,0,0,0,0,0
varB,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,10,13,18,28,26,25,25,21,23,13,0,0,0,0,0
varC,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,0,1,7,9,5,1,4,4,1,7,1,0,0,0,0
varD,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,9,23,17,27,29,27,15,25,25,17,1,0,0,0,0
varE,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,44,32,33,65,37,42,62,75,71,50,0,0,0,0,0
varF,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,89,82,83,94,37,77,100,100,90,60,0,0,0,0,0
varG,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,100,100,100,100,95,100,100,100,100,100,0,0,0,0,0
varH,2013,1,20,Sun,0,0,0,0,0,0,0,0,0,9,10,92,12,101,34,14,64,29,86,0,0,0,0,0
varA,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,5,12,23,20,22,24,9,19,15,12,13,9,0,0,0
varB,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,6,14,21,27,26,23,19,22,16,16,16,12,0,0,0
varC,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,2,5,4,10,6,10,2,7,7,4,5,5,0,0,0
varD,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,7,18,27,30,28,34,12,26,22,16,18,14,0,0,0
varE,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,0,50,20,15,67,33,71,47,36,64,58,67,0,0,0
varF,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,60,70,45,70,90,67,100,100,79,91,92,89,0,0,0
varG,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,100,100,100,100,100,94,100,100,100,91,100,100,0,0,0
varH,2013,1,21,Mon,0,0,0,0,0,0,0,0,0,20,12,31,20,29,16,12,12,16,16,34,41,0,0,0
varA,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,9,14,18,25,16,20,22,11,23,13,9,4,0,0,0
varB,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,20,23,17,28,14,18,30,17,27,17,17,6,0,0,0
varC,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,4,8,2,3,2,6,7,2,4,1,2,1,0,0,0
varD,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,13,22,20,29,18,26,29,13,27,14,11,5,0,0,0
varE,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,83,90,43,30,29,17,32,60,71,54,89,100,0,0,0
varF,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,100,100,86,65,43,56,74,90,90,73,100,100,0,0,0
varG,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,100,100,100,100,100,100,100,100,100,100,100,100,0,0,0
varH,2013,1,22,Tue,0,0,0,0,0,0,0,0,0,14,23,17,30,16,14,12,8,9,13,14,6,0,0,0

As you can see, in the full dataset there are five additional columns at the beginning corresponding to the variable names, as well as date information.

A:

Assuming your data is in matrix M, this should work:
output <- NULL
last.count <- 9216/8 - 1
for (i in 0:last.count) {
  output <- rbind(output, t(M[8*i + 1:8,]))
}

ps: rbind can be slow (depending on the data size), in which case you can pre-allocate output matrix


Q:

Find matrix of linear transformation $\mathcal{A}$

Let linear transformation is defined as
$\mathcal{A}(1,1,1)=(1,0,0)$
$\mathcal{A}(1,-1,0)=(1,1,1)$
$\mathcal{A}(1,0,1)=(1,1,1)$
Find matrix of $\mathcal{A}$ and inverse (not in matrix representation, if exists).
Attempt:
Transformation $\mathcal{A}$ can be represented as $\mathcal{A}:\mathbb{R^3}\rightarrow \mathbb{R^3}$ which can be represented by $\mathcal{A}:\mathcal{P_2}\rightarrow \mathcal{P_2}$ where $\mathcal{P_2}$ is the space of polynomials $p(x)=a+bx+cx^2$.
$\mathcal{A}(1,1,1)=(1,0,0)\Rightarrow A        \begin{bmatrix}
        a  \\
        b  \\
        c  \\
        \end{bmatrix}=        \begin{bmatrix}
        \alpha \\
        0   \\
        0  \\
        \end{bmatrix}$
How to find matrix of $\mathcal{A}$?
Is this approach (with polynomial vector space) correct?

A:

Let
$$
A=\begin{bmatrix}
a_1&b_1&c_1\\
a_2&b_2&c_2\\
a_3&b_3&c_3\\
\end{bmatrix}
$$
we have:
$$
A \begin{bmatrix}1\\1\\1 \end{bmatrix}=\begin{bmatrix}1\\0\\0 \end{bmatrix}
\Rightarrow \begin {cases}
a_1+b_1+c_1=1\\
a_2+b_2+c_2=0\\
a_3+b_3+c_3=0\\
\end {cases}
$$
$$
A \begin{bmatrix}1\\-1\\0 \end{bmatrix}=\begin{bmatrix}1\\1\\1 \end{bmatrix}
\Rightarrow \begin {cases}
a_1-b_1=1\\
a_2-b_2=1\\
a_3-b_3=1\\
\end {cases}
$$
$$
A \begin{bmatrix}1\\0\\1 \end{bmatrix}=\begin{bmatrix}1\\1\\1 \end{bmatrix}
\Rightarrow \begin {cases}
a_1+c_1=1\\
a_2+c_2=1\\
a_3+c_3=1\\
\end {cases}
$$
Find $b_i=1+a_i$ and $c_i=1-a_i$ from the last two systems, so that $b_i+c_i=2$, and substitute in the first system. You find:
$$
A=
\begin{bmatrix}
-1&0&2\\
-2&-1&3\\
-2&-1&3\\
\end{bmatrix}
$$
that clearly is not invertible.


Q:

Run tests from inner classes via Maven

I have following tests structure:
public class WorkerServiceTest {

    public class RaiseErrorTest extends AbstractDbUnitTest{
        @Test
        public void testSomething(){
        }

        ...
    }

    ...
}

It's done because I don't want to create a separate class file for every test case extending AbstractDbUnitTest.
The problem is that mvn test doesn't run test from my inner class. Is there is a way how to configure Maven to run such tests? Of course I can create methods in the parent class calling the inner class methods but I want a clearer way.

A:

Yes, this is possible using the new (well, it's not new anymore) Enclosed runner (since JUnit 4.5) that runs all static inner classes of an outer class.
To use it, just annotate the outer class with @RunWith(Enclosed.class) and make the inner classes static.
@RunWith(Enclosed.class)
public class WorkerServiceTest {

    public static class RaiseErrorTest extends AbstractDbUnitTest{
        @Test
        public void testSomething(){
        }

        ...
    }

    ...
}

And mvn test will run them.

A:

I explain (a little more) the solution that I found...
Maven (AFAIK) uses by default the plugin "maven-surefire-plugin" to run any tests defined at your maven project. According to the documentation of this plugin, by default, it excludes tests that are enclosed at inner static classes (or at least it was with version that i'm using - 2.18.1).
So what i did was to put a empty exclude rule; resulting with a pom's build section like this:
<build>
  <plugins>
  ...
  <!-- ~~~~~~~~~~ SUREFIRE -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.18.1</version>
      <configuration>
        <excludes>
          <exclude></exclude>
        </excludes>
      </configuration>
    </plugin>
    ...
  </plugins>
</build>


Q:

Modern 7.0 ComboBox fires 'select' event on every value change

The combobox in modern fires the "select" event every time the input changes. This is very different from classic. With it doing this there is no way to differentiate between a user making a selection and pragmatically setting the value of the field.
This was reported as a bug in the Sencha forums:
https://www.sencha.com/forum/showthread.php?468730-Modern-6-5-2-ComboBox-fires-select-event-on-every-value-change
The link above also contains a fiddler to demonstrate the issue.
Has anyone run into this as an issue, and how did you overcome it?

A:

forceSelection: true will help to solve this problem but will not cancel the bug in cases when forced selection is not needed
Edit:
This behavior is due to method syncValue (search in this source - method is private and hasn't documentation)
I don’t understand why the component developer chose to create a record even if it isn’t exist.
Comment from source file:

Either user has typed something (isInput), or we've had a setValue to a value which has no match in the store, and we are not forceSelection: true. We create a new record.

I propose to fix this behavior using the following override:
fiddle
Ext.define('Ext.field.SelectOverride', {
    override: 'Ext.field.Select',
    autoCreateRecord: false,
    syncValue: function() {
        var me = this,
            store = me.getStore(),
            forceSelection = me.getForceSelection(),
            valueNotFoundText = me.getValueNotFoundText(),
            is, isCleared, isInput, value, matchedRecord;

        if (me.reconcilingValue || !store || !store.isLoaded() || store.hasPendingLoad()) {
            return;
        }

        me.reconcilingValue = true;

        me.getSelection(); // make sure selection config is flushed

        is = {};
        is[me.syncMode] = true;
        value = ((isInput = is.input || is.filter)) ? me.getInputValue() : me.getValue();
        isCleared = value == null || value === '';

        if (!isCleared) {
            if (me.getMultiSelect()) {
                return me.syncMultiValues(Ext.Array.from(value));
            }

            matchedRecord = (isInput ? store.byText : store.byValue).get(value);

            if (matchedRecord) {
                if (!matchedRecord.isEntity) {

                    matchedRecord = matchedRecord[0];
                }
            }
            else if (!forceSelection) {
                matchedRecord = me.findRecordByValue(value);
            }
        }

        // Either user has typed something (isInput), or we've had a setValue
        // to a value which has no match in the store, and we are not forceSelection: true.
        // We create a new record.
        if (!isCleared && !matchedRecord && !forceSelection && me.autoCreateRecord) {
            matchedRecord = me.createEnteredRecord(value);
        }
        else {
            if (isInput || is.store) {
                if (!matchedRecord && forceSelection) {
                    me.setValue(null);
                    me.setSelection(null);

                    if (!is.filter) {
                        me.setFieldDisplay();
                    }
                }
            }            else {
                if (isCleared) {
                    if (me.mustAutoSelect()) {
                        matchedRecord = store.first();

                        if (me.getAutoSelect() === 'initial') {
                            me.setAutoSelect(false);
                        }
                    }
                    else {
                        me.setSelection(null);
                    }
                }
                else if (!matchedRecord && valueNotFoundText) {
                    me.setError(valueNotFoundText);
                }
            }
        }

        if (matchedRecord) {
            me.setSelection(matchedRecord);
        }

        me.reconcilingValue = false;
    }
});


Q:

How to insert content in a header of web page from other file?

I have a problem with an included header in a phtml file.
I have an MVC project and the view file is builded like this
<?php
  require_once'header.phtml';

  //SOME PHP COMMAND TO PRINT SOME STUFF

  reuire_once 'footer.phtml';
?>

When I press F12 in Google Chrome the header content apears in the body of the page, like this :

            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title></title>

                    <title>UserList</title>
                    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
                    <link rel="stylesheet" type="text/css" href="../css/Mystyle.css">
                    <meta name="description" content="MVC MiniShop Project">
                    <meta name="keywords" content="MVC Online Store">
                    <meta name="author" content="Vasile Vetisan">
                    <meta charset="UTF-8">

Home

Link

Link

Link

Link

USER LIST IS:

USER_ID	FIRST_NAME	LAST_NAME	USERNAME	EMAIL	PASSWORD

2	Test	Unu	test1	test1@gmail.com

Even if I change the structure of the ViewUser page like this:

<?php
   require_once 'header.phtml'
?>

     //SOME GENERATED STUFF WITH PHP

The result is the same as previous :( .
So  as summary of my post I need a method to insert content in header of a phtml page from another page using php or phphtml extenxions.
I have tried a lot of stuff so I need some new ideas or answers.

A:

I think the very good, easy and effective way of including parts is using php, where part.html is file with your code.
 <?php
 include "part.html";
 ?>

Example:
part.html

 Hello world!

index.php

<?php
include "part.html";
?>

output should be

 Hello World!


Q:

What is the verb for receiving a licence?

The verb for granting someone a license (such as a copyright license) seems to be "license", as in "we licensed the software to Foo".
What is the verb for receiving a license?  Also "license"?  As in "we licensed the software from Foo"?
If so, I find the ambiguity of "we licensed the software" irritating, as it does not convey whether we granted or received the license without adding a "to" or "from".

A:

To be clear, we usually use license as a phrasal verb, which Wikipedia defines  as

a verb and a particle and/or a preposition co-occur forming a single semantic unit

When the combination is a verb and preposition, it is often called a prespositional verb.
The verb license alone can be ambiguous.

I licensed the software.

Is the subject the grantor or receiver of the license?
Consequently, we can use license from to indicate the subject is the receiver (licensee), and license to to indicate the subjet is the grantor (licensor).

I licensed the software from Microsoft.
I licensed my new app to Apple.

SUPPLEMENT
There are a number of verbs that describe relationships between parties with different rights where either party can be the subject, the relationship role being clarified with prepositions.  For example

I leased the apartment to a nice couple. I know they'll be good tenants.
and
We leased the apartment from this nice old man. He seems like a great landlord.

Similarly rented.

The driver said, "I rented the car from Hertz."
and
The counterman told the police he rented the car to a well-dressed businessman.

Absent the prepositions, the role of the subject is ambiguous.

I leased the car.

Am I the customer or the rental agency?