text:
Q: Unit test RabbitMQ push with C# - .Net Core I have created a .net core API, which pushes a message in RabbitMQ queue. I have used IOptions to read configuration data from .json file and added it as dependency.
Below is the code of my controller:
[Route("api/[controller]")]
public class RestController : Controller
{
    private RabbitMQConnectionDetail _connectionDetail;

    public RestController(IOptions<RabbitMQConnectionDetail> connectionDetail)
    {
        _connectionDetail = connectionDetail.Value;
    }

    [HttpPost]
    public IActionResult Push([FromBody] OrderItem orderItem)
    {
        try
        {
            using (var rabbitMQConnection = new RabbitMQConnection(_connectionDetail.HostName,
                _connectionDetail.UserName, _connectionDetail.Password))
            {
                using (var connection = rabbitMQConnection.CreateConnection())
                {
                    var model = connection.CreateModel();
                    var helper = new RabbitMQHelper(model, "Topic_Exchange");
                    helper.PushMessageIntoQueue(orderItem.Serialize(), "Order_Queue");
                }
            }
        }
        catch (Exception)
        {
            return StatusCode((int)HttpStatusCode.BadRequest);
        }
        return Ok();
    }
 }

Connection details class has the below properties
public class RabbitMQConnectionDetail
{
    public string HostName { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }
}

Now I want to unit test it, but since I am going to test it against a blackbox, I'm not able to think of how to unit test it and looking for kind help.
ConnectionClass
public class RabbitMQConnection : IDisposable
{
    private static IConnection _connection;
    private readonly string _hostName;
    private readonly string _userName;
    private readonly string _password;

    public RabbitMQConnection(string hostName, string userName, string password)
    {
        _hostName = hostName;
        _userName = userName;
        _password = password;
    }

    public IConnection CreateConnection()
    {
        var _factory = new ConnectionFactory
        {
            HostName = _hostName,
            UserName = _userName,
            Password = _password
        };
        _connection = _factory.CreateConnection();
        var model = _connection.CreateModel();

        return _connection;
    }

    public void Close()
    {
        _connection.Close();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            _connection.Close();
        }
    }

    ~ RabbitMQConnection()
    {
        Dispose(false);
    }
}

Helper class
public class RabbitMQHelper
{
    private static IModel _model;
    private static string _exchangeName;
    const string RoutingKey = "dummy-key.";

    public RabbitMQHelper(IModel model, string exchangeName)
    {
        _model = model;
        _exchangeName = exchangeName;
    }

    public void SetupQueue(string queueName)
    {
        _model.ExchangeDeclare(_exchangeName, ExchangeType.Topic);
        _model.QueueDeclare(queueName, true, false, false, null);
        _model.QueueBind(queueName, _exchangeName, RoutingKey);
    }

    public void PushMessageIntoQueue(byte[] message, string queue)
    {
        SetupQueue(queue);
        _model.BasicPublish(_exchangeName, RoutingKey, null, message);
    }

    public byte[] ReadMessageFromQueue(string queueName)
    {
        SetupQueue(queueName);
        byte[] message;
        var data = _model.BasicGet(queueName, false);
        message = data.Body;
        _model.BasicAck(data.DeliveryTag, false);
        return message;
    }
}

A: Tightly coupling your Controller to implementation concerns are making it difficult to test your controller without side-effects. From the sample you provided you have shown that you are encapsulating the 3rd part API implementations and only exposing abstractions. Good. You however have not created an abstraction that would allow you to mock them when testing. I suggest a refactor of the RabbitMQConnection to allow for this.
First have your own backing abstraction.
public interface IRabbitMQConnectionFactory {
    IConnection CreateConnection();
}

And refactor RabbitMQConnection as follows
public class RabbitMQConnection : IRabbitMQConnectionFactory {
    private readonly RabbitMQConnectionDetail connectionDetails;

    public RabbitMQConnection(IOptions<RabbitMQConnectionDetail> connectionDetails) {
        this.connectionDetails = connectionDetails.Value;
    }

    public IConnection CreateConnection() {
        var factory = new ConnectionFactory {
            HostName = connectionDetails.HostName,
            UserName = connectionDetails.UserName,
            Password = connectionDetails.Password
        };
        var connection = factory.CreateConnection();
        return connection;
    }
}

Take some time and review exactly what was done with this refactor. The IOptions was moved from the Controller to the factory and the RabbitMQConnection has also been simplified to do it's intended purpose. Creating a connection.
The Controller now would need to be refactored as well
[Route("api/[controller]")]
public class RestController : Controller {
    private readonly IRabbitMQConnectionFactory factory;

    public RestController(IRabbitMQConnectionFactory factory) {
        this.factory = factory;
    }

    [HttpPost]
    public IActionResult Push([FromBody] OrderItem orderItem) {
        try {
            using (var connection = factory.CreateConnection()) {
                var model = connection.CreateModel();
                var helper = new RabbitMQHelper(model, "Topic_Exchange");
                helper.PushMessageIntoQueue(orderItem.Serialize(), "Order_Queue");
                return Ok();
            }
        } catch (Exception) {
            //TODO: Log error message
            return StatusCode((int)HttpStatusCode.BadRequest);
        }
    }
}

Again note the simplification of the controller. This now allows the factory to be mocked and injected when testing and by extension allows the mocks to be used by the RabbitMQHelper. You can use your mocking framework of choice for dependencies or pure DI.

A: I dont think it is a unit test scenario. If you want to to test with external component ie database or message queue then i suggest you do it as integration test.
What we do is to have a sand box environment with component SQL database and azure message bus. We have code to correctly set the state for this component ie seed the database  and clear the message bus. Then we run test on the environment and check the state of the database or message bus count etc.


text:
Q: spring transactional nested open session? If a method of service is marked as @Transactional with propagation nested, and inside it there are many calls to other @Transactional methods, each one of these methods will use its own session? It should represent many connections to db for just one method call no?

A: It looks like PROPAGATION_REQUIRED is better option for your purpose. From its javadoc:
Support a current transaction; create a new one if none exists.
Refer this link for more details

redpajama_set_name: RedPajamaStackExchange


text:
Q: Designing (properties in) classes for Entity Framework relationships - code first C# I'm doing code first Entity Framework in C# and I am short this one area - how to create properties for relationships between the classes.
A simple example: a Video (Id, Name, Release Date) class and a Genre (name & ID) class.
I already have the solution to the above (ICollection in Genre and  public virtual in Video) but in general how can I determine the property I should put in each class for 1:1, 1:Many, Many:Many relationships ? Is there a kind of a template I could check against ?


text:
Q: Two foreign keys from one table I am trying in following DB ERD that User creates a Profile. A user can see his followers as well as the profiles that users are following.

The problem is:
Both sections either "Followers" or "Following" are users not Profile
Update:
Is the following approach okay or in above diagram?
 SQL> Create table users(
  2  user_id number(5) primary key,
  3  reg_date date,
  4  name varchar2(50),
  5  password varchar2(50));

Table created.

SQL> Create table Follow(
  2  follow_id number(5),
  3  following number(5) constraint User_fk references users(user_id),
  4  follower number(5) constraint User_fk1 references users(user_id));

Table created.

Please advise. Thanks in anticipation

A: *

*Should Profile be an entity/table separated from User, or should they be merged?

This depends on your requirements. If a user has just one profile (as on many sites, e.g. on this one), the profile doesn't need to be a separate entity. Then the question whether the following relationship should point to users or to profiles vanishes. If, however, a user can have more than one profile (which might be guessed from your FK type_id), let's say one for his sports and another for his musical interests, then two entities and tables are needed.

*Should Follower point to User or to Profile?

In the case of just one User entity, follower and following must both point to User, as there is nothing else. This is your SQL solution.
In the case of a separate Profile entity, it's again up to your requirements. Should the follower follow the user as a whole, or is he just interested in a certain profile angle of the user? (Follow Jack, or follow Jack as a sportsman, but not as a musician.) In the first case, following points to the User, otherwise to the Profile.


text:
Q: Moving an element from right to left using CSS3 transitions on load of the document I want to add a transition property to an element which contains text coming from an angular controller.
I want to move it from right to left when the document loads. Is there any way to do that. here is my sample code.
Index file excerpt

               {{log.date}}

                {{log.module}}  {{log.subModule}}

          {{log.desc}}

CSS Except (Right now I tried it with hover but it didn't work too, but I want it to automatically come from right to left on page load.)

#axis:hover .move-left{
    transform: translate(350px,0);
    -webkit-transform: translate(350px,0); /** Safari & Chrome **/
    -o-transform: translate(350px,0); /** Opera **/
    -moz-transform: translate(350px,0); /** Firefox **/
}

A: Use a CSS animation and define the values of the translation inside the keyframes. The forwards value will keep your element with the style of the last keyframe encountered.
CSS
.move-left {
    animation: moveleft 2s 1 normal forwards;
}

@keyframes moveleft {
   from { transform: translateX(0); }
   to   { transform: translateX(350px); }

}

codepen demo

This will wait just until the presence of that element on the DOM but, if you need to wait the full document load (including images and heavy assets) just add a class (e.g. .load) to the .move-left element on load event of the window and fire the animation only if the class has been applied, so the JS and CSS selector would be
Javascript
window.addEventListener("load", function(event) {
    document.querySelector('.move-left').classList.add('load');
});

CSS
.move-left.load {
    animation: moveleft 2s 1 normal forwards;
}

A: You could just use Jquery and .addClass and .removeClass.
For example
jQuery(document).ready(function($){
$('#axis').click(function(){
$('//What you want the class to be added too / Moved').addClass('move-left');
)};
)};

A: You can use animation property of CSS-3 in combination with translateX() property.
    .row {
        animation: 1s ease-out 0s 1 slide;
    }

    @keyframes slide {
        0%{ transform: translateX(100%);}
        100%{ transform: translateX(0%);}
    }

Check out this answer.


text:
Q: Progress in table Im trying to get a progress bar in a table with the height of the progress bar not altering the table height, my css:
  table#t
  {
    behavior: column-resizer;
    overflow: hidden;
    table-layout: auto;
  }

  table#t tr { height:1.4em; }

  table#t > tbody
  {
    padding-left:20px;
  }

  table#t > caption
  {
    foreground-repeat: no-repeat;
    foreground-position: 3px 50%;
    foreground-image-cursor:pointer;
    foreground-image:url(theme:tree-view-glyph-open);
    padding-left:1.4em;
    height:1.4em;
    line-height:1.4em;
    active-on!: is-on-icon()? self:collapsed = !self:collapsed;
    double-click!: !is-on-icon()? self:collapsed = !self:collapsed;
  }

  table#t > caption:collapsed
  {
    foreground-image:url(theme:tree-view-glyph-closed);
  }

  caption:collapsed + tbody
  {
    visibility:collapse;
  }
  p.custom > progress
  {
    behavior:progress;
    background-image:url(images/progress-back.png);
    background-position:2px 2px 2px 2px;

    height: 8px;
    width: 100px;
    padding: 1px;

    foreground-position:1px 1px 1px 1px;
    foreground-image:url(images/progress-body.png);
  }

my html:

Files

Application.exe

1.6 Mb

<progress name="p2" maxvalue="100" value="0"/>

Archive.7z

843 Mb

<progress name="p2" maxvalue="100" value="50"/>

This is what it looks like without the progress bar:
http://imgur.com/MwHFXN3
and with the progress bar:
http://imgur.com/ruj6Pv2
I've tried  tags and setting the height of the progress bar and table in css and html but I can't seem to simply add in the progress bar without losing the height.


text:
Q: Fastest way to get map object to list I have a function that processes text files. I have a list of approximately 73K files that I want to run through this function. The function returns a list of dictionaries, each representing one row in my output. After I process all them, I write the results to a csv using csv.DictWriter.
What I have been doing so far is results = [i for sublist in [*map(lambda f: process_func(f), files] for i in sublist] or list(map(process_func, files)). Each of these takes about 3.5 minutes. When I just do something like map(process_func, files), it takes about 350 ms.
I need to scale this up and the process of turning the map object into a list essentially takes all of the time the script needs to run. Is there a more efficient way to this?


text:
Q: Open Folders since Jquery from CSS Script I have a script on CSS that allows you to simulate a file explorer on HTML.
The problem that I have is that I want to create a button that automatically opens all the folders and subfolders in that list.
Here is an example of the css that is being called when a checkbox is clicked:
li input:checked + ol
{
    background: url('http://www.01800iglesia.org/imagenes/numeros-01.png') 44px 5px no-repeat;
    background-size: 12px 12px;
    margin: -1.25em 0 0 -44px; /* 20px */
    padding: 1.563em 0 0 80px;
    height: auto;
    width: auto;
}
li input:checked + ol > li { display: block; margin: 0 0 0.125em; }
li input:checked + ol > li:last-child { margin: 0 0 0.063em; }

Live example here:
https://jsfiddle.net/qzojy5ko/3/
Is there any way to get the folders open since the click of a button?
Thank you in advance.

A: I've forked and updated your fiddle with a working solution.
https://jsfiddle.net/xgz0z54k/3/
You can use the .prop() to set the value of the checkbox on the click event.
jQuery("#my_button").click(function() {
  $("input").prop("checked", true);
});

A: As stated, you're essentially checking and unchecking checkboxes:
$(function() {

    var folder = $('.folder').next('input');

    $('#my_button').click(function() {
        if (folder.filter(':checked').length == folder.length) {
            folder.prop('checked', false);
            $(this).val('Open Folders');
        } else {
            folder.prop('checked', true);
            $(this).val('Close Folders');
        }
    });

    folder.change(function() {
        if (folder.filter(':checked').length == folder.length) {
            $('#my_button').val('Close Folders');
        } else {
            $('#my_button').val('Open Folders');
        }
    });

});

Ideally, instead of $('.folder').next('input'), you'll want to add a class to the checkboxes themselves, and change that to $('input-class').


text:
Q: Same Output for different set of inputs when using .predict for Random Forest Regression for atomic predictions I am trying to regress the output (.predict) of the random forest regressor back into the input ( as a set of features) for the prediction of the next step and doing this iteratively.
This is because from the POV of physics the output (temperature ) for the current iterative step depends the previous temperature (iterative step).
This same logic was also used while training the data.
y_pred_val is just a list that i have initialized with all zeros to make it of the same data length as other columns of my dataframe.
for jj in range(len(a_val)-1):
    df_X_val = pd.DataFrame({'X1': a_val, 'X2': b_val, 'X3': c_val ,  'X4 (previous predicted temperature)': y_pred_val})
    instance = df_X_val.iloc[[jj],:]
    y_pred_val[jj+1] = (model.predict(instance)[0])
    len(y_pred_val)

While doing this the .predict values just saturated after 3 iterative steps i.e. they all go back to the same leaf even though the features X1,X2 and X3 have different values.
It works with a not so great accuracy if i completely omit the X4 features which is really important here.


text:
Q: How to rewrite code using then block using javascript, react and cypress? i have the code like below which uses lot of nested then clauses. this code is for testing my code written in javascript and react using cypress.
{
export const waitForItems = (retries, nrItems) => {
    cy.apiGetItems().then(items => {
        if(items.length!== nrItems && retries > 0) {
            cy.wait(1000);
            return waitForItems(retries -1, nrItems);
        }
        expect(items.length).to.be.equal(nrItems);
    });
};

const item = {
    name: 'name1',
};
const itemFamily = 'ItemFamily1';
const subfamily = {
    name: 'subfamily1',
}

describe('some test', () => {
    before(() => {
        cy.clickButtonByLabel('Click');
        switchUser(USERNAME);
        waitForItems(NUMBEROFRETRIES, NUMBEROFITEMS);

        cy.apiGetItems({ name: item.name })
            .then(createdItem => {
                item.id = createdItem[0].id;
        })
        .then(() => {
            cy.apiGetItemFamily({
                name: itemFamilyName,
            }).then(family => {
                cy.apiGetSubFamily({
                    name: subfamily1.name,
                    item__family__id__in: family[0].id,
                }).then(subfamily => {
                    subfamily1.id = subfamily[0].id; //error here says cannot read
                    // id of undefined
                    cy.apiPostSomething({
                        ...something,
                        items: [item.id],
                        subfamily: [subfamily1.id],
                    }).then(createdSomething => {
                        something.id = createdSomething.id;
                        cy.apiGetItemVariable({
                            key: ItemVariableName,
                            subfamily__id__in: subfamily1.id,
                        }).then(variable => {
                            cy.apiPostVariableValue({
                                variable: variable[0].id,
                                value: controlValue,
                            }).then(() => {
                                cy.apiGetsubFamily({
                                    name: subfamily1.name,
                            }).then(newControl => {
                                const versions =
                                    newControl[0].versions;
                                const latestVersionControl = versions.find(
                                    v => v.version === '3.9.0'
                                );
                                const id = latestVersionControl.id;
                                cy.apiPatchSomething({
                                    id: Something.id,
                                    controls: [id],
                                });
                            });
                        });
                    });
                });
            });
        });
    });
});

The above code works fine. but sometimes i get error "cannot read id of undefined" in the then(subfamily) clause.
i am not sure why subfamily[0] is still not available when trying to assign it like so
 .then(subfamily => {
     subfamily1.id = subfamily[0].id;
 }

could someone help me fix this. thanks.

A:  First, you should giv a try to async/await syntax, since you use promise. It'll help you writting easier to read code :
describe('some test', () => {
    before(async () => { //add async there
        cy.clickButtonByLabel('Click');
        switchUser(USERNAME);
        waitForItems(NUMBEROFRETRIES, NUMBEROFITEMS);

        const createdItem = await cy.apiGetItems({ name : item.name });
        item.id = createdItem[0].id;
        const family = await cy.apiGetItemFamily({ name: itemFamilyName });
        //and so one
    });
});

This way, you will write your code in a way that seems synchronous.
For your question about subfamily,
It's probably the return value of cy.apiGetSubFamily that doesn't return an array, or is returning an empty array.
Edit about Cypress :
The fact that Cypress doesn't work well with Promise as nothing to do with async/await syntax problem. Since Cypress return thenable, async/await SHOULD be usable.
But because of Cypress paradigm that handle asynchronus in it's way, the await/async syntax leads to undeterministic results when we await one. More info can be found there : https://github.com/cypress-io/cypress/issues/1417


text:
Q: python: in my df, I need to add up a column until i hit a target, then change the data in a different column for each value that makes the target enter code hereI have a df like this :
   Project        position    emp   hrs
0        A  Burger flipper   John  1.25
1        B         cashier  steve  2.25
2        C         cleaner  Karen  0.25
3        A   shift manager  sally  0.25
4        C      supervisor  julie  1.25
5        A         cleaner  Karen  1.75**strong text**
6        B  Burger flipper   John  0.25
7        C  Burger flipper   John  7.50
8        A         cashier  steve  1.25
9        C         cleaner  Karen  0.50
10       A   shift manager  sally  0.75
11       B      supervisor  julie  0.75
12       C         cleaner  Karen  1.75
13       A  Burger flipper   John  2.25

I need to change it so that for emp John, 10 of his hours are registered as Restaurant Manager and the remaining are left as burger flipper.

Any help would be awesome.
have since tried the knapsack problem and tried to apply it to mine - i think my answer is in there somewhere
edit 3: so I have found a way to make add the numbers to find the target:
the numbers pulled from their own separate df for john:
0     1.25
6     0.25
7     7.50
13    2.25
14    3.25
20    4.75
21    0.25
27    0.50
28    0.50
34    2.25
35    2.75
Name: hrs, dtype: float64
then:
num = numbers
limit = 10
num = numbers

limit = 10
def sumofnums(limit, num):
sumofnums = 0
prefix = []
for i in num:
if sumofnums< limit:
sumofnums = sumofnums + i
prefix.append(i)
if sumofnums > limit:
return prefix
print(sumofnums(limit, num))
gives me this result:
[1.25, 0.25, 7.5, 2.25]
so now i need to work out how to display the index of each number returned so I can use that to go back and edit the position for each one. i think.
I am not holding much hope -I cant even work out how to make this page work properly - lol

A: df.loc[:, 'cumsum'] = df.groupby('emp')['hrs'].transform('cumsum')

ind = df[(df['emp'] == 'John') & (df['cumsum'] < 10)].index
df.loc[ind, 'position'] = 'Restaurant Manager'

print(df)

Output
   Project            position    emp   hrs  cumsum
0        A  Restaurant Manager   John  1.25    1.25
1        B             cashier  steve  2.25    2.25
2        C             cleaner  Karen  0.25    0.25
3        A       shift manager  sally  0.25    0.25
4        C          supervisor  julie  1.25    1.25
5        A             cleaner  Karen  1.75    2.00
6        B  Restaurant Manager   John  0.25    1.50
7        C  Restaurant Manager   John  7.50    9.00
8        A             cashier  steve  1.25    3.50
9        C             cleaner  Karen  0.50    2.50
10       A       shift manager  sally  0.75    1.00
11       B          supervisor  julie  0.75    2.00
12       C             cleaner  Karen  1.75    4.25
13       A      Burger flipper   John  2.25   11.25

A 'cumsum' column is created: grouped by 'emp', fetching the 'hrs' column, transform is used.
Get row indices where 'John' and df['cumsum'] < 10.
Through explicit indexing loc (indices on the left, column name on the right) values are set.


text:
Q: XMLTABLE ORA-01401: inserted value too large for column I have a table with xmltype field. In this field there is a xml file.
When i do a select from this field like:
    SELECT
        x.resources as item_name
    FROM LOAD_XML t,
    XMLTABLE (
    '/Document/Chapters/Chapter/Position'
    PASSING  xml_data
    COLUMNS
        resources varchar2(4000) PATH '@Caption'
    ) x
    where
        XML_FILE_NAME = 'test.xml'

I found error strings of xml the Caption is realy long, but not so much:
  <Position Caption="Газовая приточная установка в составе: модуль нагрева рекуперативный, 880 кВт - АТРИ МНР 880 (1 шт.), горелка газовая предварительного смешивания - АТРИ PREMIX 880 модулируемая (1 шт.), блок воздушного фильтра на горелку - АТРИ Premix ФП (1 шт.), модуль фильтров панельных - АТРИ ФП (1 шт.), счетчик газа турбинный - СТГ-50-100-2 (1 шт.), клапан воздухоприемный ОТКРЫТО-ЗАКРЫТО -  ГЕРМИК-С-1500(Н)-2400 (1шт.), вентустановка - АТРИ ВБ 100.22/970(1064) (1шт.), частотный преобразователь Schneider - ATV212HD22N4 22,0 кВт (1шт.), шумоглушитель - пластины 5х200 мм (1шт.), датчик температуры - ТС035Л-50М (1шт.), датчик температуры - КДТ 50 (1шт.), датчик-реле давления воздуха - LGW 3 A2 0,4...3 mbar (1шт.), датчик-реле давления газа ГАЗ МАХ - GW 150 A6 10...150mbar (1шт.), модуль управления и защиты нагревателя + система автоматического поддержания расхода воздуха - ШКА-01-МУЗН.С7+САУ-ПР (1шт.), стационарный измеритель скорости потока воздуха - (1шт.), измеритель дифференциального давления + монтжный комплект - АДР-05.5 (1шт.), модуль обслуживания для уличного исполнения - АТРИ МОУ-880.Г (1шт.), вводное распределительное устройство - Шкаф ВРУ (1шт.), модуль сигнализации и управления главным клапаном - МСУ-ГлКл (1шт.), термостат - FI-TO2A (1шт.), дымоходы утепленные - АТРИ ДХУ (1 компл.)" Number="451" Code="ООО  Инжгазпром " Units="шт." SysID="297" Quantity="1" PriceLevel="2001" PzSync="Yes" Vr2001="10087">

I have an error:
ORA-01401: inserted value too large for column
01401. 00000 -  "inserted value too large for column"
*Cause:    The value inserted was too large for the given column.
*Action:   Do not insert a value greater than what the column can hold.
But the max length of selected fied is max(length(x.resources)) = 1297
Please help!


text:
Q: How do I get the amplitude of a variable sine function? Let's assume that we have a dynamical system
$$G(s) = \frac{Y(s)}{U(s)}$$
And we have measure the input $u(t)$

And we have measure the output $y(t)$.

Here we can see that if we increase the frequency at the input of the system, the output is going to decrease.
The question is simple: How can I find the amplitudes over time of by just knowing $y(t)$ and $u(t)$. Nothing more.
My goal is to estimate a transfer function from arbitrary frequency input and output and I going to use least square to curve fit on a transfer function.
Can I just drag a line of all peaks/tops of the sine waves?

A: Since you have $u(t)$ and $y(t)$, you can compute the Laplace transform of each and get, by your first equation,
$$
G(s) = \frac{L(y(t))}{L(u(t))}.
$$
If your measurements are continuous time and perfect then this is exact. If you have noisy measurements, then this is approximate. If you have discrete measurements you need to look at Hankel matrices and realization theory.


text:
Q: Which operators will cause an Observable to evaluate? I am working with rxjs in particular, but I am asking about ReactiveX in general.
There are many mentions that Oberservable are lazily evaluated, but searching through the docs, I cannot find explicit mention of which operators will cause an Observable to be evaluated. The only operator I know of that will cause evaluation is subscribe. Are there other options?

A: It is the only operator you need. In order to trigger an Observable, you need to subscribe to it. No need to do anything with the results, you only need to subscribe:
functionThatReturnsAnObservable().subscribe(function(data){});

Edit
As cartant said, there are functions that implicitly invoke the subscribe operator, such as the forEach and toPromise functions.


text:
Q: Setting up a shortcut for knitr chunk in Lyx I'm new to Lyx and would very much like to set up a new shortcut for inserting a new Chunk (Insert > Custom Insets > Chunk)
I saw here how to set one up, but this is not the same; the Chunk menu item from the Custom Insets doesn't require the <<>>= and @ characters in the chunks.
Any help appreciated on how to (if possible) assign this command to a new shortcut.

A: Here's how to do it, thanks to scottkosty's instructions on tex.
Go to Tools > Preferences > Editing > Shortcuts and create a new shortcut entering the following text as the function:
flex-insert "Chunk"
Then, just assign a key combination to it and you're done.


text:
Q: Как поменять inet addr (Ubuntu)? Добрый день!Подскажите, пожалуйста, как поменять адрес в Linux Ubuntu 13.10?Пытаюсь командой     ifconfig eth0 192.168.123.15 netmask 255.255.255.0
Но при вызове ifconfig данные остаются старые.

A: В терминале:sudo service network-manager stopsudo service networking stopsudo ifconfig eth0 downsudo ifconfig eth0 your_new_addresssudo ifconfig eth0 upsudo service networking startКак-то так ...
A: Вообще-то синтаксис правильный, правда, не помню точно, поддерживается ли он в linux. а посмотрите, не управляются ли ваши интерфейсы т.н. менеджером соединений (подобная штука точно есть в openSuse и при его работе ifconfig бессилен). Если действительно манагер есть и работает - отключите его. Да, ещё как вариант попробуйте перезапустить ифейс (ifconfig eth0 down && ifconfig eth0 up) ну или весь inetd


text:
Q: jquery load() method not working -- IE8 So been fiddling around with this for a while now but still no luck.
I've tried changing jquery versions, tried doing the whole var $j = jQuery.noConflict();, tried rearranging JS/jquery scripts, tried the no caching thing suggested by jquery website but still my load() doesn't work on IE8.
Can you help us

function loadCont(file){
$j("#maincont").load(file);
alert(file);
return false;
}

As always it loads on every other browser except IE8. The alert() is there for IE8 debugging, and the file is passed successfully to the server with status 200 (checked with Fiddler2), its just not loaded into #maincont
I've tried different methods such as:
$j.ajaxSetup ({
            // Disable caching of AJAX responses
            cache: false
    });

    // Bind ajax call to click
    $j('a.loadlink').click(function(e) {
            $j('#maincont').load($j(this).attr('href') + ' #filecont');  // Dynamically load content from URL in href
            e.preventDefault();
    });

And commenting out all my other JS externel includes "styleswitcher.js and formcheck.js". I know the jQuery is working correctly as I use a jQuery drop down menu. At the moment my current code looks like this, which works fine on every other browser....

All or any help about the code or replies appreciated. Many thanks to all replies.
EDIT: Still looking for a fix for this :(

A: You're using formcheck.js its based on mootools javascript if I'm not wrong. Please put your jQuery file on top and try.
Another thing you can do is instead of creating no conflict object you can directly jQuery. I've used formcheck and jQuery in a same page. Please refer http://www.mymegaenergy.com/enrollments It should work fine if you do these things.


text:
Q: Word for each component of a time-stamp If I have been presented with a time-stamp in the 24-hour format: 12:24:33 (hh:mm:ss)
Is there a word to address a component of this? By a component, I mean each value between 2 delimiters (only the minutes or only the hour etc.)
With reference to the above example:

12, 24, 33 are all ____ of the time-stamp.

A: Components of a timestamp:

Zone and offset information are two more useful components of timestamps that many may not know about.

(Sai Peddy, Java 8 DateTime, Medium)
See also:
Db2 TIMESTAMP_FORMAT on IBM Knowledge Center

A: Well! I am bit late to answer this question. Actually, a word to collectively address all of these components is called Time literal  wiki
time literals

A date literal is a fixed expression that represents a relative range of time, such as last month, this week, or next year.

In computer science, literals are fix values of a given datatype.
Further reading: Time Literals

A: These can also be called fields.
Oxford has this definition:

2.1 Computing A part of a record, representing an item of data.

As for usage in the field1, Lindsay Holmwood says in Timestamp Limitations When Processing RFC3164 Formatted Logs:  (emphasis mine)

According to RFC3164, the TIMESTAMP field in the HEADER section of a syslog packet is in the format of "Mmm dd hh:mm:ss" (e.g. Oct 11 22:14:15). Astute readers will note that there is no year field in the timestamp.

1 a different field ;-)


text:
Q: Collection pluck by relation id and get count I have  Project and Country Model. There is a many to many relations. I get projects with countries. Result is below
array:5 [▼
  0 => array:5 [▼
    "id" => 2
    "account_id" => 1
    "start_date" => "Jul 2012"
    "end_date" => "Aug 2013"
    "countries" => array:1 [▼
      0 => array:2 [▼
        "id" => 148
        "pivot" => array:2 [▶]
      ]
    ]
  ]
  1 => array:5 [▶]
  2 => array:5 [▶]
  3 => array:5 [▶]
  4 => array:5 [▶]
]

I wont to get all unique countries count. In the now I do it with this way
$projects->pluck('countries')->collapse()->pluck('id')->unique()->count()

Question. Can I use pluck with nested relation column and has any more shortly and good solution?? for example like this
$projects->pluck('countries.id')->count();

A: You can use this:
$projects->pluck('countries.*.id')->flatten()->unique()->count()

You can't use:
$projects->pluck('countries.id')...

Because countries is an array of arrays.
But you can use the 'countries.*.id' on those cases

A: Or the other way round...
Country::whereHas('projects', function ($query) {
    // $query->where(); if you want to limit the projects
})->count();

You get unique countries since your fetching from the countries table

A: I find this solution
$projects->groupBy('countries.*.id')->count();


text:
Q: Bayes Theorem with Missing Information I am trying to solve the following with Bayes Theorem but feel as if I am missing information:

Suppose you have a batch of red and a second batch of green
  party-poppers. You know that one batch is reliable and will go off
  with a bang 80% of the time whereas the other batch got wet and will
  only explode 40% of the time. You choose a green party-popper at
  random and pull the string. It doesn't explode. Based on your first
  observation what is the probability that the green batch is the
  unreliable batch.

From the information provided I understand that there is a 50/50 chance of selecting either a red or green party popper. So, our prior must be 0.5. I also know that 80% of one batch explode, meaning 20% of that batch are unreliable and that 40% of the other batch explode meaning that 60% of that batch are unreliable. However, I do not understand how to plug in these values to Bayes Theorem in order to demonstrate the probability that the green batch is the unreliable batch as I do not know whether it is the green or red batch that is more likely to explode.
Any help with this query is very much appreciated.

A: The question is, given that a randomly picked green party popper did not explode, what is the probability of the green batch being unreliable. The first step to solving this is to translate the text into statements. As you noted, the prior is both batched being equally likely to be the unreliable one: $$ \Pr(\text{Green unreliable} ) = \Pr(\text{Red unreliable} ) = .5$$
The other two statements can be translated as follows (where $g=0$ indicates the event where the randomly selected popper does not explode) :
$$ \Pr( g=0\ |\ \text{Green unreliable}) = 0.6 \\
\Pr( g=0\ |\ \text{Red unreliable}) = 0.2
$$
Then we can fill in these numbers in Bayes' theorem:
\begin{align} \Pr( \text{G unreliable}\ |\ g=0) &= \frac{\Pr( g=0\ |\ \text{G unreliable}) \Pr( \text{G unreliable})}{\Pr( g=0\ |\ \text{G unreliable}) \Pr( \text{G unreliable}) + \Pr( g=0\ |\ \text{R unreliable}) \Pr( \text{R  unreliable})}\\
&= \frac{0.6}{0.6+0.2}\\
&= \frac{3}{4}
\end{align}

A: I think you can just leave the (confusing) colors out and rephrases like this:
"You choose a party-popper at random out of one of the batches (fifty-fifty) and pull the string. It doesn't explode. Based on your first observation what is the probability that this party-popper comes from the unreliable batch?"
For this you can use Bayes rule:
$P\left(\text{unreliable}\mid\text{no explosion}\right)=\frac{P\left(\text{no explosion}\mid\text{unreliable}\right)P\left(\text{unreliable}\right)}{P\left(\text{no explosion}\mid\text{unreliable}\right)P\left(\text{unreliable}\right)+P\left(\text{no explosion}\mid\text{reliable}\right)P\left(\text{reliable}\right)}$

A: I do declare that we must assume the batches are of the same size, there is no bias as to which batch was wet, and that wetness does not bias from which batch the popper was selected.
We shall designate the relevant events as being that you select a popper which: is green as $E$, is unreliable as $U$, and does explode as $E$.
The above assumptions and the data provided indicates the following probability measures: $$\begin{align}\mathsf P(G)&=1/2\\\mathsf P(U\mid G)&=1/2\\ \mathsf P(E\mid U)&=2/5&&= \mathsf P(E\mid U,G)\tag{ *} \\\mathsf P(E\mid U^\complement)&=4/5&&=\mathsf P(E\mid U^\complement,G)\tag{*}\end{align}$$
($*$ by reasoning that Explosivity is determined only by the Unreliability of the batch, and not (directly) by its Colour, therefore Colour and Explosivity are independent for a given state of Unreliablity ($E\perp G\mid U$)).
Now the law of total probability states:
$$
\mathsf P(E\mid G)=\mathsf P(E\mid U,G)\mathsf P(U\mid G)+\mathsf P(E\mid U^\complement,G)\mathsf P(U^\complement\mid G)
\\ \mathsf P(E^\complement\mid G)=\mathsf P(E^\complement\mid U,G)\mathsf P(U\mid G)+\mathsf P(E^\complement\mid U^\complement,G)\mathsf P(U^\complement\mid G)
$$
You seek $\mathsf P(U\mid G,E^\complement)$.  Use Bayes' Rule to find this.


text:
Q: Was the universe cold before the Big Bang? I think matter cause something to be hot or cold. So before Big Bang there was no matter in the space so what would have been the temperature of space at that time (if time was even there before Big Bang :).

A: There is no universe before the Big Bang, it is the point at which space and time come into existence. There is no "where" that could have a temperature and no "when" you could call before matter. The question is meaningless.

A: All our notions of space and time , of what was there , what happened etc. come from exploration  of the laws of physics, which are in the form they are in our universe i.e. the laws of physics are valid in the domain of our universe.
Questions regarding what happened before the big bang are questions outside the domain of our known laws of physics. It is equivalent to asking what the laws of physics are in another universe.
The best answer is . We do not know. Other universes do not follow our laws of physics and hence, we cannot say anything about them


text:
Q: Python multiprocessing Queue failure I create 100 child processes
proc_list = [
    Process(target = simulator, args=(result_queue,))
    for i in xrange(100)]

and start them
for proc in proc_list: proc.start()

Each process puts into the result_queue (instance of multiprocessing.Queue) 10000 tuples after doing some processing.
def simulate(alg_instance, image_ids, gamma, results,
                     simulations, sim_semaphore):
  (rs, qs, t_us) =  alg_instance.simulate_multiple(image_ids, gamma,
                                             simulations)
  all_tuples = zip(rs, qs, t_us)
  for result in all_tuples:
    results.put(result)
  sim_semaphore.release()

I should be (?) getting 1000000 tuples at the queue, but after various runs I get these (sample) sizes:
14912
19563
12952
13524
7487
18350
15986
11928
14281
14282
7317
Any suggestions?

A: The multiprocessing.Queue is said to be thread-safe in its documentations. But when you are doing inter-process communications with Queue, it should be used with multiprocessing.Manager().Queue()

A: My solution to multiprocessing issues is almost always to use the Manager objects. While the exposed interface is the same, the underlying implementation is much simpler and has less bugs.
from multiprocessing import Manager
manager = Manager()
result_queue = manager.Queue()

Try it out and see if it doesn't fix your issues.

A: There's no evidence from the OP post that multiprocessing.Queue does not work. The code posted by the OP is not at all sufficient to understand what's going on: do they join all the processes? do they correctly pass the queue to the child processes (has to be as a parameter if it's on Windows)? do their child processes verify that they actually got 10000 tuples? etc.
There's a chance that the OP is really encountering a hard-to-reproduce bug in mp.Queue, but given the amount of testing CPython has gone through, and the fact that I just ran 100 processes x 10000 results without any trouble, I suspect the OP actually had some problem in their own code.
Yes, Manager().Queue() mentioned in other answers is a perfectly fine way to share data, but there's no reason to avoid multiprocessing.Queue() based on unconfirmed reports that "something is wrong with it".


text:
Q: Dimension of Linear code Assume that $\alpha$ is a primitive element of $GF(q)$ and $n=q-1$. The $C$ code over $GF(q)$ with length $n$ defined as follows
$$
\{(f(1),f(\alpha),\ldots,f(\alpha^{n-1}))\mid f \in GF(q)[x],\  \deg(f)<k\}
$$
where $k\leq n$.
How to find the dimension of $C$ code?(let we accept the $C$ is a linear code)

A: The answer of the question is on page 4 of the following link
http://web.stanford.edu/class/ee392d/Chap8.pdf


text:
Q: How do I create a acrylic blur effect in a VCL application? How do I create a acrylic blur effect like the one in UWP apps in a Delphi VCL application?
I tried using the following method I found here:
program DwmTest;
//Author  : Rodrigo Ruz 2009-10-26
{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

type
  DWM_BLURBEHIND = record
    dwFlags                 : DWORD;
    fEnable                 : BOOL;
    hRgnBlur                : HRGN;
    fTransitionOnMaximized  : BOOL;
  end;

//function to enable the glass effect
function DwmEnableBlurBehindWindow(hWnd : HWND; const pBlurBehind : DWM_BLURBEHIND) : HRESULT; stdcall; external  'dwmapi.dll' name 'DwmEnableBlurBehindWindow';
//get the handle of the console window
function GetConsoleWindow: HWND; stdcall; external kernel32 name 'GetConsoleWindow';

function DWM_EnableBlurBehind(hwnd : HWND; AEnable: Boolean; hRgnBlur : HRGN = 0; ATransitionOnMaximized: Boolean = False; AFlags: Cardinal = 1): HRESULT;
var
  pBlurBehind : DWM_BLURBEHIND;
begin
  pBlurBehind.dwFlags:=AFlags;
  pBlurBehind.fEnable:=AEnable;
  pBlurBehind.hRgnBlur:=hRgnBlur;
  pBlurBehind.fTransitionOnMaximized:=ATransitionOnMaximized;
  Result:=DwmEnableBlurBehindWindow(hwnd, pBlurBehind);
end;

begin
  try
    DWM_EnableBlurBehind(GetConsoleWindow(), True);
    Writeln('Test of glass effect');
    Readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

Unfortunately this only makes the windows a white-transparent appearance without any kind of blurring.
How can I achieve this effect?

A: First, you don't need to declare the DWM APIs yourself, since they are already declared in the DwmApi unit. Also, GetConsoleWindow is declared in the Windows unit.
Second, the effect your code is trying to apply is not the UWP effect; instead, it is the Windows Vista Aero effect.
And this does work for me:
program Project3;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Windows, System.SysUtils, DwmApi;

function DWM_EnableBlurBehind(hwnd: HWND; AEnable: Boolean; hRgnBlur: HRGN = 0; ATransitionOnMaximized: Boolean = False; AFlags: Cardinal = 1): HRESULT;
var
  pBlurBehind: DWM_BLURBEHIND;
begin
  pBlurBehind.dwFlags := AFlags;
  pBlurBehind.fEnable := AEnable;
  pBlurBehind.hRgnBlur := hRgnBlur;
  pBlurBehind.fTransitionOnMaximized := ATransitionOnMaximized;
  Result := DwmEnableBlurBehindWindow(hwnd, pBlurBehind);
end;

begin
  DWM_EnableBlurBehind(GetConsoleWindow(), True);
  Writeln('Hello, Aero!');
  Readln;
end.

So why doesn't it work for you? Probably, you are using Windows 8 or later. In these systems, this effect has been removed.
Obviously, when you found this code, your first instinct was to look up the documentation for the DwmEnableBlurBehindWindow function. But apparently you missed the warning a page down:


text:
Q: Nginx reverse proxy using auth_request module and external authentication API - error 404 I am trying to configure nginx as a reverse proxy to protect another server (kibana) using an external authentication API.
This is the url that should log me into kibana dashboard - http://127.0.0.1/kibana_proxy?username=my.user&password=test67
Once the authentication done (i.e. https status 200), nginx is throwing a 404 error. But the error log has this -

2018/10/18 13:33:52 [error] 10718#0: *19 open()
  "/usr/share/nginx/html/app/kibana" failed (2: No such file or
  directory), client: 127.0.0.1, server: _, request: "GET /app/kibana
  HTTP/1.1", host: "127.0.0.1", referrer:
  "http://127.0.0.1/kibana_proxy/?username=my.user&password=test67"

This is my nginx conf file -
server {
    listen *:80;
    server_name _;

    location = /auth {
        set $query '';
        if ($request_uri ~* "[^\?]+\?(.*)$") {
            set $query $1;
        }
        proxy_pass http://127.0.0.1:8080/auth?$query;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
    }

    location /kibana_proxy/ {
        proxy_pass http://127.0.0.1:5601/;
        auth_request /auth;
    }

    error_page 404 /404.html;
    location = /40x.html {

    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {

    }
}

A: Whenever you are using Restricting Access with HTTP Basic Authentication then you should use the following url pattern to access the restricted url
http://username:password@example.com/

It is not possible to pass username and password via query parameters in standard HTTP auth.
Update:
I feel your nginx settings needs some update.  You should rewrite the url to remove the /kibana_proxy/:
location /kibana_proxy/
{
     rewrite ^/kibana_proxy/(.*) /$1 break;
     proxy_pass http://localhost:5200;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection 'upgrade';
     proxy_set_header Host $host;
     proxy_set_header X-Forwarded-For $remote_addr;
     proxy_set_header  X-Real-IP  $remote_addr;
     proxy_cache_bypass $http_upgrade;
}

A: For those seeking answer - here's the nginx server conf that solved the issue for me -
server {
  listen *:80;
  server_name 127.0.0.1;

  location = /auth {
      set $query '';
      if ($request_uri ~* "[^\?]+\?(.*)$") {
         set $query $1;
      }
      # add_header X-debug-message "Parameters being passed $is_args$args" always;
      proxy_pass http://127.0.0.1:8080/auth?$query;
  }

  location /kibana/ {
     rewrite ^/kibana/(.*) /$1 break;
     proxy_pass http://127.0.0.1:5601;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection 'upgrade';
     proxy_set_header Host $host;
     proxy_set_header X-Forwarded-For $remote_addr;
     proxy_set_header  X-Real-IP  $remote_addr;
     proxy_cache_bypass $http_upgrade;
     auth_request /auth;
  }

  location ~ (/app/|/app/kibana|/bundles/|/kibana4|/status|/plugins|/ui/|/api/|/monitoring/|/elasticsearch/) {
     proxy_pass http://127.0.0.1:5601;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
     proxy_set_header Host $host;
     rewrite /kibana4/(.*)$ /$1 break;
  }

  error_page 404 /404.html;
    location = /40x.html {
  }

  error_page 500 502 503 504 /50x.html;
    location = /50x.html {
  }
}


text:
Q: Replacing the duplicate uuids across multiple files I am trying to replace the duplicate UUIDs from multiple files in a directory. Even the same file can have duplicate UUIDs.
I am using Unix utilities to solve this.
Till now I have used grep, cut, sort and uniq to find all the duplicate UUIDs across the folder and store it in a file (say duplicate_uuids)
Then I tried sed to replace the UUIDs by looping through the file.
filename="$1"
re="*.java"
while read line; do
    uuid=$(uuidgen)
    sed -i'.original' -e "s/$line/$uuid/g" *.java
done < "$filename"

As you would expect, I ended up replacing all the duplicate UUIDs with new UUID but still, it is duplicated throughout the file!
Is there any sed trick that can work for me?

A: There are a bunch of ways this can likely be done. Taking a multi-command approach using a function might give you greater flexibility if you want to customize things later, for example:
#!/bin/bash

checkdupes() {
    files="$*"
    for f in $files; do
        filename="$f"
        printf "Searching File: %s\n" "${filename}"
        while read -r line; do
            arr=( $(grep -n "${line}" "${filename}" | awk 'BEGIN { FS = ":" } ; {print $1" "}') )
            for i in "${arr[@]:1}"; do
                sed -i '' ''"${i}"'s/'"${line}"'/'"$(uuidgen)"'/g' "${filename}"
                printf "Replaced UUID [%s] at line %s, first found on line %s\n" "${line}" "${i}" "${arr[0]}"
            done
        done< <( sort "${filename}" | uniq -d )
    done
}

checkdupes /path/to/*.java

So what this series of commands does is to first sort the duplicates (if any) in whatever file you choose. It takes those duplicates and uses grep and awk to create an array of line numbers which each duplicate is found. Looping through the array (while skipping the first value) will allow the duplicates to be replaced by a new UUID and then re-saving the file.
Using a duplicate list file:
If you want to use a file with a list of dupes to search other files and replace the UUID in each of them that match it's just a matter of changing two lines:
Replace:
for i in "${arr[@]:1}"; do

With:
for i in "${arr[@]}"; do

Replace:
done< <( sort "${filename}" | uniq -d )

With:
done< <( cat /path/to/dupes_list )

 NOTE: If you don't want to overwrite the file, then remove sed -i '' at the beginning of the command.

A: This worked for me:
#!/bin/bash

duplicate_uuid=$1
# store file names in array
find . -name "*.java" > file_names
IFS=$'\n' read -d '' -r -a file_list < file_names

# store file duplicate uuids from file to array
IFS=$'\n' read -d '' -r -a dup_uuids < $duplicate_uuid

# loop through all files
for file in "${file_list[@]}"
do
    echo "$file"
    # Loop through all repeated uuids
    for old_uuid in "${dup_uuids[@]}"
    do
        START=1
        # Get the number of times uuid present in this file
        END=$(grep -c $old_uuid $file)
        if (( $END > 0 )) ; then
            echo "    Replacing $old_uuid"
        fi
        # Loop through them one by one and change the uuid
        for (( c=$START; c<=$END; c++ ))
        do
            uuid=$(uuidgen)
            echo "         [$c of $END] with $uuid"
            sed -i '.original' -e "1,/$old_uuid/s/$old_uuid/$uuid/" $file
        done
    done
    rm $file.original
done
rm file_names


text:
Q: Bridge 802.1x traffic between eth0<->eth1, IP NAT eth0<->eth2 Summary:
Given a Linux system (Ubuntu 16.04) with 3 physical ethernet interfaces:
eth0: WAN
eth1: EAPoL authenticator
eth2: Client LAN
I am attempting to configure this:

*

*Bridge br0: eth0<->eth1

*ebtables rules to only forward EAPoL traffic

*IP NAT the remaining traffic br0<->eth2 (everything except the ethernet frames which are type EAPoL)

*The eth0 port would use a spoofed mac (matching the EAPoL authenticator)

The desired end result here is that client computers connected to eth2 could connect to the WAN. The WAN requires 802.1x authentication, which would be bridged to the EAPoL authenticator device attached to eth1.
I was inspired initially by this post, but had trouble getting his configuration working:
https://www.dslreports.com/forum/r30708210-AT-T-Residential-Gateway-Bypass-True-bridge-mode
Questions:
1.) The bridge configuration seems to work, a tcpdump will show me the EAPoL traffic on eth1, however I am having trouble getting the vlan to get dhcp info, using dhclient just hangs. I am not sure I understand the purpose of the vlan here, if I spoof the mac of eth0 is this part even necessary?
2.) It's not clear to me how I would NAT the remaining traffic (everything that isnt EAPoL) between eth0<->eth2. Would I just define an iptables NAT between the interfaces themselves, like this:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth2 -j ACCEPT
iptables -A INPUT 1 -i eth2 -j ACCEPT

The problem I'm running into is that I can either configure one or the other, not both. I can either have the system bridging EAPOL between eth0<->eth1 OR I can IP NAT between eth0<->eth2, but I'm not able to configure both working together. Any suggestions or advice?
Thank you
Edits:
ebtables configuration to filter ethernet frames for EAPoL traffic:
    ebtables -t filter -A FORWARD -i eth1 -p 802_1Q --vlan-encap 0x888e -j ACCEPT
ebtables -t filter -A FORWARD -i eth1 -p 802_1Q -j DROP
ebtables -t filter -A FORWARD -o eth1 -p 802_1Q --vlan-encap 0x888e -j ACCEPT
ebtables -t filter -A FORWARD -o eth1 -p 802_1Q -j DROP


text:
Q: How do you validate an email field in angular 2 using model driven form How do you validate an email field in angular 2 using model driven form, this is what I have so far.
This is my form component
export class signinComponent {
    signinform: FormGroup;
    constructor(public fb: FormBuilder) {
        this.signinform = this.fb.group({
           name: ['', Validators.required],
            email: ['', Validators.required]
        });
    }
}

This is my form html
<form class="ui form" [formGroup]="signinform" novalidate>
    <div>
        <input type="email" class="emailinput" [formControl]="signinform.controls['email']" placeholder="Email Address">
    </div>
</form

A: Validation method:
authEmailValidation( control: FormControl ): {[s:string]:boolean} {
        let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        if ( !pattern.test( control.value ) ) {
            return { email: true };
        }
        return null;
    }

In your component:
this.signinform = this.fbuilder.group( {
                    email : ["", [this.authEmailValidation]],
                    // Other fields....
                } );

Note: dnt forget in constructor :
private signinform : FormGroup;
private fbuilder: FormBuilder
// and import them


text:
Q: Linux header file not recognized in Visual Studio 2017 Linux Project When including a Linux header file, ucontext.h in this case, in a Linux C++ Project on Visual Studio 2017 for my C program, it does not recognize the header file. Even when I include sys/ucontext.h, it does not recognize functions that I should be able to use for a ucontext_t object, such as getContext() and setContext(). Shouldn't I be able to use these functions in a Linux C++ project?
Code I'm writing:
#include <stddef.h>
#include <string.h>
#include <sys/ucontext.h>
// If I use ucontext.h instead, it gives the error: cannot open source file ucontext.h

//TCB structure
typedef struct TCB_t {
    struct TCB_t     *next;
    struct TCB_t     *prev;
    ucontext_t      context;
} TCB_t;

void init_TCB(TCB_t *tcb, void *function, void *stackP, int stack_size)
{
    memset(tcb, '\0', sizeof(TCB_t));
    tcb->context.uc_stack.ss_sp = stackP;
    tcb->context.uc_stack.ss_size = (size_t)stack_size;

    int c = getcontext(tcb->context); // Cannot resolve field getcontext()
}

A:
On this answer to do the following you need Visual Studio Community 2017 15.9.7+ - Tested this solution on Visual Studio Enterprise
  2019 Preview 4.

Visual Studio needs to download all remote headers in your localmachine for correct behavior of intellisense.
New method 'rsync_ssh' doesn't download all headers. You can use old method .zip via sftp_ssh.
0. Add remote connection.
Tools->Options->Cross Platform->Connection Manager
1. Select your connection
Update from Tools->Options->Cross Platform->Connection Manager->Remote Headers Intellisense Manager.
Next click on Explore button.

2. C:\Users[YourUser]\AppData\Local\Microsoft\Linux\HeaderCache\1.0[IdNumber]
Rename the HeaderCache settings.xml.unused file to settings.xml

3. In the settings.xml file Change the syncMethod to sftp_ssh.

4. Update headers cache from Tools->Options->Cross Platform->Connection Manager->Remote Headers Intellisense Manager.
5. Enjoy.
Before

After

A: On my Linux system (Debian Jessie) ucontext.h is in usr/include which in turn includes sys/ucontext.h which gcc will find in usr/include/i386-linux-gnu/sys. The first defines the functions getcontext and setcontext. The second defines the data structures ucontext_t etc.
On the Windows host, VCLinux has installed a copy of the second ucontext.h (which defines the data structures) in C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\Linux\include\usr\include\x86_64-linux-gnu\sys . But the first ucontext.h is not present.
VCLinux/Visual Studio will compile and run this program on the Linux remote:
#include <ucontext.h>
#include <iostream>
int main()
{
   ucontext ucxt;
   ::getcontext (&ucxt);
   std::cout << ucxt.uc_flags << std::endl;
   return 0;
}

But IntelliSense will not know about the functions getcontext and setcontext or the associated data structures. So you will get little red squiggles under the names and no completion assistance.
You can take a copy of the first ucontext.h and put it in C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\Linux\include\usr\include on your Windows host. Then everything will work as it should. And you could raise an issue for the missing header on the VCLinux GitHub site.
Note: Windows paths are for Visual Studio 2015. They will be different for 2017.
Applies to VCLinux 1.0.6.
==============
Update 10-Apr-18
Microsoft have addressed the issue of differences in standard include file locations between Linux systems. As explained in this Visual C++ blog post, the headers specific to the GCC setup are copied from the Linux remote and stored on the Windows host on a per-connection basis.


text:
Q: How to apply comparator to get the TOP 5 cities from a List sorted by population? I have a class City
public final class City {
private final String name;
private final String state;
private final int    population;

public City(String name, String state, int population) {
    this.name       = name;
    this.state      = state;
    this.population = population;
}
public String getName() {
    return name;
}
public String getState() {
    return state;
}
public int getPopulation() {
    return population;
}
@Override
public String toString() {
    return "City [name=" + name + ", state=" + state + ", population=" + population + "]";
}
}

And a class that implements Observable (not needed for this). This observable class holds an arraylist List<City> cityList that has the data for all the cities that have been reported.
My class TopFiveCities is supposed to:

"implement a getter method getTopFive() returning a list with the five
top cities (in terms of population) received. The list is sorted from
higher to lower numbers. The returned list must be a copy of the list
kept by the observer"

Aside from just getting the top 5 list, I also need to know how to make a copy of that list from the observer.
This is what I have:
public class TopFiveCities
implements Observer {

// THIS ALSO DOESN'T WORK UNLESS THE LIST IS STATIC
// SO HOW CAN I MAKE A COPY OF THE LIST FROM OBSERVER?
private List<City> list = new ArrayList<>(CensusOffice.cityList);

public List<City> getTopFive() {
    Collections.sort(list, new Comparator<City>() {

        @Override
        public int compare(City o1, City o2) {
            return Integer.compare(o1.getPopulation(), o2.getPopulation());
        }

    });
    return list;
}

public void update(Observable observable) {
    if (!(observable instanceof Observable)) {
        throw new IllegalArgumentException();
    }
}
}

With this, when one of the sample outputs should be:
City [name=Chicago, state=IL, population=2746388]

I just receive a list of all the cities, sorted by population from LOWEST to HIGHEST. What I'm doing wrong?

A: You can just use a Stream, use a Comparator to sort the stream, limit the number of element and convert the elements to a new list:
List<City> top5citiesByPopulation = cities.stream()
        .sorted(Comparator.comparing(City::getPopulation).reversed())
        .limit(5)
        .collect(Collectors.toList());

A: int order = requestedOrder.equals("asc") ? 1 : -1;

Collections.sort(list, new Comparator<CustomObj>() {
    public int compare(CustomObj first, CustomObj scnd) {
        return first.getComparableParam().compareTo(scnd.getComparableParam()) * order;
    }
});

I just copied and passed this code block from recommended stackover page in the comment. Of you want ascending order simply change it. In your code order will be -1.
Simply you need to multiply by -1.
return Integer.compare(o1.getPopulation(), o2.getPopulation()) * -1;

After this you can sublist it.
You keep the list as global variable it can be reached from update method but it does not change if class is singleton except for update method. Your update method can change it by notifying
In update method you can simply clear and add new list by list.addAll

A: Since this is a schoolwork assignment, I'll describe the pieces but let you assemble them into final code.

I have a class "City"

You could more briefly define that class as a record.
City ( String name, String state, int population ) {}

holds an array list "List cityList"

List < City > cities = new ArrayList<>();

getting the top 5 list

Sort the list by using a reverse comparator. You can make a comparator for sorting by using a method reference for the accessor "getter" method. But be aware that records do not use the word "get" by default as their accessor, they use simply the name of the property.
cities.sort( Comparator.comparing( City :: population ).reversed() ) ;

For an unmodifiable list, call List.of or List.copyOf.
List#subset gives you a list with some of the elements of the original. But beware: the resulting list is based on a view of the original list. The subset is not separate and independent. To get a separate list, pass to List.copyOf or pass to the constructor of another List implementation.
List< City > topFivePop = List.copyOf( subset ) ;

A: This problem doesn't require sorting the whole given list, which will have a time complexity of O(n log n).
Basically, the task is somewhat similar to finding the maximum element in the list that can be done in O(n) time with a single pass through the given list.
The most suitable approach for this problem is a partial sorting, and the  best performance that could be achieved is the middle-ground between O(n) and O(n log n).
In order to find 5 maximum elements in a list, we can maintain a collection that will store in sorted order up to 5 previously encountered elements with maximum values.
Elements that are lover than the smallest element in the collection will be discarded automatically if the collection is already of size 5. Only new elements with a value higher than the smallest element's value will trigger reordering of this tiny collection. I.e. the data will be sorted partially instead of sorting the whole data set.
In the implementation below for as collection that will store 5 max elements, I've chosen a PriorityQueue.
According to the documentation it's methods have the following time complexity.

this implementation provides O(log(n)) time for the enqueuing and dequeuing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size).

I.e. adding of a new element and removing the first element both will perform in logarithmic time, and accessing the smallest value in the queue with the method element() with done in O(1) time (almost immediately).
The PriorityQueue is encapsulated inside a generic class, which constructor expects as parameters a Comparator<T> and a desired maximum size of the queue (i.e. a number of max elements that needs to be found).
The queue itself doesn't exposed to the outside classes. Method addItem() processing the given element and getFirstN returns a sorted immutable list.
Comparator in the code below is implemented using the static method comparingInt(). You could also implement Comparator in a "classical way" (pre-Java 8) by providing the behavior for it's abstract method compare() either by using a lambda expression or within an anonymous inner class.
public class FirstN<T> {
    private final Queue<T> queue;
    private final Comparator<T> comparator;
    private final int capacity;

    public FirstN(Comparator<T> comparator, int capacity) {
        this.queue = new PriorityQueue<>(comparator);
        this.comparator = comparator;
        this.capacity = capacity;
    }

    public boolean addItem(T item) {
        if (capacity == queue.size() && comparator.compare(item, queue.element()) <= 0) {
            return false; // queue is full and the given item is smaller than the lowerest element in the queue
        }

        if (capacity == queue.size() && comparator.compare(item, queue.element()) > 0) {
            queue.remove(); // removing the first element if it's smaller than the given item
        }
        return queue.add(item); // adding the given item
    }

    public List<T> getFirstN() {
        List<T> result = new ArrayList<>(queue); // creating a list based on a queue
        result.sort(comparator);
        return List.copyOf(result); // making a copy of the list (returned list is immutable)
    }
}

main()
public static void main(String[] args) {
    List<City> cities = List.of(
            new City("Austin", "Texas", 1028225),
            new City("Los Angeles", "California", 3985516),
            new City("San Diego", "California", 1429653),
            new City("Houston", "Texas", 2325353),
            new City("Phoenix", "Arizona", 1759943),
            new City("New York City", "New York", 8177025),
            new City("San Antonio", "Texas", 1598964),
            new City("Philadelphia", "Pennsylvania", 1585480),
            new City("San Diego", "California", 1429653),
            new City("Chicago", "Illinois", 2671635),
            new City("Dallas", "Texas", 1348886));

    FirstN<City> top5Cities =
            new FirstN<>(Comparator.comparingInt(City::getPopulation), 5);

    for (City next: cities) {
        top5Cities.addItem(next);
    }

    List<City> result = top5Cities.getFirstN(); // contains 5 biggest US cities

    result.forEach(System.out::println); // printing the result
}

Output (order from lowest to highest)
City [name=Phoenix, state=Arizona, population=1759943]
City [name=Houston, state=Texas, population=2325353]
City [name=Chicago, state=Illinois, population=2671635]
City [name=Los Angeles, state=California, population=3985516]
City [name=New York City, state=New York, population=8177025]


text:
Q: What ARIMA model best fits these graphs? I have so far concluded that the ACF and PACF show a potential ARIMA (1, 2, 1). Are there any other possibilities of ARIMA models that could also fit this data?

A: When deciding between an AR model and an MA model one looks for dominance between the ACF and the PACF:

*

*If the ACF dominates then choose an AR model with the order dictated by the PACF.

*If the PACF dominates then choose an MA model with the order dictated by the ACF.

*If there is ambiguity then there might be a combined model BUT I would proceed slowly by selecting one and then reviewing the model residuals to suggest further augmentation.
Recall that the above advice is a rule of thumb and is probably worthless when you have any of the following:

*

*outliers/pulses/step shifts/local time trends

*parameters that are changing over time

*a model error variance that is non-constant.


text:
Q: bash: ping: command not found My shell can't find ping.
$ ping
-bash: ping: command not found
$ uname -r
14.5.0
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/Users/alex/.cabal/bin
$ which ping
$

However, man ping works and displays the manual page for ping.
Is it named something different on OSX?  Or is there an alternative I should use?


text:
Q: Avoid TextField validation when the field is not focused - React Hook form I am new to React Hook forms. I'm using material UI TextField in my form.
I was able to display the error messages when I type in the Textfield.
But Once I clear the value inside the Textfield and click somewhere else on the page, the error still exists. I do not want it. I only want the errors to be displayed when user is typing in the textfield(example:- email regex check till the valid email is typed) or user submit a form without values.
I do not want the errors to be shown when Textfield is not focused. Can this be achieved by react hook forms?
import { useForm, Controller } from "react-hook-form";

function FormTest(props) {
  const {
    handleSubmit,
    control,
    reset,
    formState: { isSubmitSuccessful },
  } = useForm({  mode: "all" });

  const onSubmit = (data) => {
    console.log(data);
  };

  useEffect(() => {
    if (isSubmitSuccessful) {
      reset();
    }
  }, [isSubmitSuccessful, reset]);

<form onSubmit={handleSubmit(onSubmit)} noValidate>
                  <Controller
                    name="email"
                    control={control}
                    defaultValue=''
                    render={({
                      field: { onChange, onBlur, value },
                      fieldState: { error},
                    }) => (
                       <TextField
                         label="Email"
                         variant="standard"
                         type="email"
                         color="warning"
                         value={value}
                         onChange={onChange}
                         onBlur={onBlur}
                         error={!!error}
                         helperText ={!!error ? error?.message : ""}
                       />
                    )}
                    rules={{
                      required: "Required!",
                      pattern: {
                        value: emailPattern,
                        message: "Invalid Email Address",
                      },
                    }}

                  />
                  <Button type="submit">Submit</Button>
      </form>

When I click on the TextField and start typing the relevant error is displayed. But once I clear the field and click on a different place in the page the required error still exists. I do not want to show the required error when the text field is not focused. Only if it is focused and submit button is clicked without any values.


text:
Q: How to play video in ios swift I am new to ios programming, actually I need to stream video URL but i am unable to stream video URL using avplayer, but using avplayer downloaded file i am able to play.Actual problem is my file format is different
for example my file name is like this  song.apa but it is song.mp4
code:
let avplayerController = AVPlayerViewController()
var avPlayer:AVPlayer?

override func viewDidLoad()
{
    super.viewDidLoad()
    let movieUrl = URL.init(string: "http://techslides.com/demos/sample-videos/small.3gp")
    self.avPlayer = AVPlayer.init(url: movieUrl!)
    self.avplayerController.player = self.avPlayer
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func playVideo(_ sender: Any)
{
    self.present(self.avplayerController, animated: true) {
     self.avplayerController.player?.play()
    }
}

A: In Swift 3
import Foundation
import AVFoundation
import MediaPlayer
import AVKit

func play()
    {
        let player = AVPlayer(url: "Your Url")
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true)
        {
            playerViewController.player!.play()
        }

    }

A: You cant play this particular link (http://techslides.com/demos/sample-videos/small.3gp) using AVPlayer or AVPlayerViewController because that file is in AMR (Adaptive Multi-Rate, a format for speech) - which is not supported since iOS 4.3
Some of 3gp files can be played but only ones that have video and audio streams supported by Apple.

A: In Swift 3, try this code for playing video in project
import UIKit
import AVKit
import AVFoundation
import MediaPlayer
import MobileCoreServices

class VideoPlayerViewController: UIViewController,AVPlayerViewControllerDelegate {

    //MARK: - Outlet -
    @IBOutlet weak var viewVidioPlayer: UIView!
    //MARK: - Variable

    //MARK: - View Life Cycle -
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    //MARK: - Action -
    //for Playing Video
    @IBAction func btnvideoPlayClicked(_ sender: UIButton) {
         self.videoPlay()
    }

    func videoPlay()
    {
        let playerController = AVPlayerViewController()
        playerController.delegate = self

        let bundle = Bundle.main
        let moviePath: String? = "http://techslides.com/demos/sample-videos/small.3gp"
        let movieURL = URL(fileURLWithPath: moviePath!)

        let player = AVPlayer(url: movieURL)
        playerController.player = player
        self.addChildViewController(playerController)
        self.view.addSubview(playerController.view)
        playerController.view.frame = self.view.frame

        player.play()

    }
    //MARK: - other Function -

    func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController){
        print("playerViewControllerWillStartPictureInPicture")
    }

    func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController)
    {
        print("playerViewControllerDidStartPictureInPicture")

    }
    func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error)
    {
        print("failedToStartPictureInPictureWithError")
    }
    func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController)
    {
        print("playerViewControllerWillStopPictureInPicture")
    }
    func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController)
    {
        print("playerViewControllerDidStopPictureInPicture")
    }
    func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool
    {
        print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
        return true
    }
}

I hope it's work for you,
thank you

A: heres an example of streaming video..
override func viewDidLoad() {
        super.viewDidLoad()
        let player = AVPlayer(url: URL(string: "http://techslides.com/demos/sample-videos/small.mp4")!)
        let controller = AVPlayerViewController()
        present(controller, animated: true) { _ in }
        controller.player = player
        addChildViewController(controller)
        view.addSubview(controller.view)
        controller.view.frame = CGRect(x: 50, y: 50, width: 300, height: 300)
        controller.player = player
        controller.showsPlaybackControls = true
        player.isClosedCaptionDisplayEnabled = false
        player.play()
    }

A: you can use YoutubePlayerView for playing youtube videos, and for else formats you can use UIWebView. For doing so, simply use if-else block,
if movieUrl.contains("youtube.com/") {
    var videoId: String = extractYoutubeId(fromLink: movieUrl)
    youtubePlayerView.load(withVideoId: videoId)
} else {
    webView = UIWebView(frame: CGRect(x: 0, y: 0, width: 288, height: 277))
    webView.delegate = self
    webView.backgroundColor = UIColor.black
    webView?.loadRequest(movieUrl)
}

A: For Swift 3 play video from URL
//AVPlayerViewControllerDelegate // example : class TestAudioVideoVC: UIViewController,AVPlayerViewControllerDelegate

func videoPlay()
    {
        let playerController = AVPlayerViewController()
        playerController.delegate = self

        let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")

        let player = AVPlayer(url: videoURL! as URL)
        playerController.player = player
        self.addChildViewController(playerController)
        self.view.addSubview(playerController.view)
        playerController.view.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64)
        playerController.showsPlaybackControls = true
        player.play()
    }

//MARK: - AVPlayerViewController Delegate -

    func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController){
        print("playerViewControllerWillStartPictureInPicture")
    }

    func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController)
    {
        print("playerViewControllerDidStartPictureInPicture")

    }
    func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error)
    {
        print("failedToStartPictureInPictureWithError")
    }
    func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController)
    {
        print("playerViewControllerWillStopPictureInPicture")
    }
    func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController)
    {
        print("playerViewControllerDidStopPictureInPicture")
    }
    func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool
    {
        print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
        return true
    }

A: Play video in swift 5
class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func playVideoUsingURL(_ sender: Any) {
    playGlobalVideo()
}

@IBAction func playVideoFromLocalDrive(_ sender: Any) {
    playLocalVideo()
}

func playGlobalVideo() {
    guard let videoURL = URL(string: "http://static.videokart.ir/clip/100/480.mp4") else {
        return
    }
    let player = AVPlayer(url: videoURL)
    let vc = AVPlayerViewController()
    vc.player = player
    present(vc, animated: true) {
        player.play()
    }
}

func playLocalVideo() {
    guard let videoPath = Bundle.main.path(forResource: "movie", ofType: "mov") else {
        return
    }
    let player = AVPlayer(url: URL.init(fileURLWithPath: videoPath))
    let playCtr = AVPlayerViewController()
    playCtr.player = player
    present(playCtr, animated: true) {
        player.play()
    }
}

}


text:
Q: Ajax Call Trouble with Accents I have tried the following line in my ajax call as it was suggested all over internet:

contentType: "application/json; charset=ISO-8859-1"

but it did not change anything. Whenever I make a call from ajax with a string parameter which has an accent for example società, at my controller(I'm using Java, spring framework), i receive it as SocietÃ. I have tried first UTF-8 which is the default (as far as I know) but nothing. Here is my full function:
function foo(customer, society) {
    $.ajax({
        url: 'notMappedAcoStaffing.do',
        type: "GET",
        contentType: "application/json; charset=ISO-8859-1",
        data: { customer: customer, society: society},
        success: function(data) {   $('#content').html(data);    },
        error: function(error) { alert("error" + error); }
    });
}

And I take the values on my backend as
@RequestMapping(method = RequestMethod.GET)
public ModelAndView fooController(@RequestParam("customer") final String customerParam, @RequestParam(value="society",required=false) Integer societyParam) {...}

Is there a way to resolve this issue?
Thanks for your help in advance.
UPDATE: I have still no idea why I receive it distorted as parameter at my controller. But however when I convert it as follows: How do I convert between ISO-8859-1 and UTF-8 in Java? ,it comes out all good. Seeing that it works, I tried it again to set UTF-8 in my ajax call but no success... It resolved my issue but honestly I do not like this way. Please share with me if you have a better solution maybe on the ajax call side. Thanks

A: Part of your problem is that you're using HTTP GET, which basically means that your data will be embedded in the URL itself, in the query string ( http://example.org/?customer=foo&society=bar ). This can lead to problems when using special characters.
Especially, the contentType property concerns the body of the request which you do not have at all so currently it has little impact.
Consider sending the data with HTTP POST (and remove your custom contentType) which gives you more power over the encoding of your data - which is then sent in the request body instead of the URL. It might solve your problem outright, or you might need to configure your server to use the same encoding as the client
 - I suggest UTF-8 for both parties.


text:
Q: Custom message box in JavaScript Im looking at making a custom message box in JavaScript but am wondering how I go about doing it. I have this code below which shows a Yes, No, Cancel message Box:
 msls.showMessageBox("Please choose the appropriate button", {
            title: "This is a message box",

            buttons: msls.MessageBoxButtons.yesNoCancel

        }).then(function(result) {

            if (result === msls.MessageBoxResult.yes) {

                alert("You have selected Morning");

            } else if (result === msls.MessageBoxResult.no) {

                alert("You Have Selected Afternoon");

            } else if (result === msls.MessageBoxResult.cancel) {

                alert("You have closed this message box");

            }

        });
}

my goal is to rename the button text but im not sure how to do it, here is an example of what I mean:

*

*Yes to be Morning

*No to be Afternoon

*cancel to be cancel
I know how to change what each button does, its just the small part of editing the text inside the button to say what i want, thanks for any help
im using Lightswitch HTML and the message box is referenced in jquery.mobile.structure-1.3.0.css file

A: You cannot change the text of the buttons if you are using the msls.ShowMessageBox API.  The recommended approach in LightSwitch would be to use a Popup.
Creating a Popup Screen in LightSwitch

A: to further add to the above answer, this is how it is done:
create a button on screen, then add this in the execute code:
if (screen.Table.Variable == true) {
    screen.showPopup("PopupTest");
    } else {
myapp.commitChanges();

from this code you can then add multiple popups with an unknown amount of variables or in my case buttons, each button can be coded to do a certain task.


text:
Q: Is it possible to perform two different "+=" and "-=" operations in one line of code? I have just started teaching myself java and I was wondering if there is an operation (maybe an "and then" operation) that will allow me to perform two mathematical calculations on the same line.  It is important to keep the updated total for the "balance". This is my code:
public static void main(String[] args) {
  double balance = 5400d;
  double withdrawalAmount = 2100d;
  double depositAmount = 1100d;

  //Total Balance after primary transactions
  // (This line of code works but I want to update "balance" after every calculation
  System.out.println(balance - withdrawalAmount + depositAmount);

  //This updates the balance after withdrawing money
  System.out.println(balance -= withdrawalAmount);

  //This updates balance after depositing money
  System.out.println(balance += depositAmount);

  //Here is where I was trying to combine both operations but it did not like this very much
  System.out.println(balance -= withdrawalAmount && balance += depositAmount);
  }

A: You can simply do it in one line:
System.out.println(balance = balance - withdrawalAmount + depositAmount);

A: There is no Java syntax to do that, but you can still do it, using plain simple math.
You want to do:
X = X  - y + z

You don't need two assignments here. You simply subtract one value and add another one before you do a single assignment back to X.


text:
Q: Using the "AND" operator in with linq I'm trying to do an expression some like this:
from a in objcxt.tableA
join b in objcxt.tableB
on a.fld1 equals b.fld1 and a.fld2 equals b.fld2
into b_join from b in b_join.DefaultIfEmpty()

edit: b.fld2 can be null.
I tryed "and", "&&", but no success.
Some help?

A: You need to write it to work with the equals operator, which can only be used once after an on statement.  So, something like this is needed.
from a in objcxt.tableA
join b in objcxt.tableB
on new { a.fld1, a.fld2 } equals new { b.fld1, b.fld2 }
into b_join from b in b_join.DefaultIfEmpty()

A: You need to use an anonymous type in your join to specify multiple fields in the join.
on new {a.fld1, a.fld2} equals new {b.fld1, b.fld2}

A: You could try:
from a in objcxt.tableA
join b in objcxt.tableB
on
    new { a.fld1, a.fld2 }
equals
    new { b.fld1, b.fld2 }
into b_join from b in b_join.DefaultIfEmpty()


text:
Q: Avoid Braintree recurring-billing for a single subscription I need to let users choose to block a monthly recurring-bill.
Default subscription options are:
never_expires: true,
number_of_billing_cycles: nil

Is
never_expires: false,
number_of_billing_cycles: 0

the proper update to a subscription to accomplish that? Is 0 allowed as value for number of billing cycles? I want to update the subscription for a single user so that is not paying on the following month

A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
You should be able to accomplish your goal through creating a discount. You'll need to create a discount associated with a plan via the Control Panel. However, via the API you'll be able to add a discount to the subscription. Specifically, you should create a discount on the subscription that equals the amount of the subscription in order to bypass a month.

A: Braintree doesn't really do this (at least, that I can tell...)
The way I would approach a 'free month' sort of thing is to simply do a refund for that month https://developers.braintreepayments.com/guides/recurring-billing/manage/php#refunding-a-subscription


text:
Q: Docker image error: /bin/sh: 1: python: not found Im running this dockerfile and I get: ERROR Run python -m playwright install
/bin/sh python: not found
FROM mcr.microsoft.com/playwright:focal

RUN apt-get update && apt-get install -y python3-pip
COPY . .
RUN pip3 install TikTokApi
RUN python -m playwright install // Results in error

A: If you want a Playwright image with Python instead of the Playwright image with Node you have currently set,
do
FROM mcr.microsoft.com/playwright/python:v1.23.0-focal

instead. You won't then need to install python3-pip (or playwright!) at all.
Additionally, you'll probably want to explicitly spell out python3 instead of python:
FROM mcr.microsoft.com/playwright/python:v1.23.0-focal
RUN pip3 install TikTokApi
RUN playwright install
COPY . .

A: In the terminal of vscode, type sudo apt install python-is-python3 then restart, it should work.


text:
Q: Can't assign DOM element value to a variable Using JavaScript I obtain an undefined variable error using different code:
HTML form
<form name="someForm" onsubmit = "return submitAnswers()" >
<input type="radio" name"w1" value = 'a' id="wla">a.

Javascript
function submitAnswers(){
    var w1 = document.forms["someForm"]["w1"].value;
 }

The same result is obtained trying to assing an initial value;
function submitAnswers(){
var w1 = 'some'
w1 = document.forms["someForm"]["w1"].value;
}

I then receive the following output:

TypeError: document.forms.someForm.w1 is undefined

A: You forgot the "elements" property.
https://developer.mozilla.org/fr/docs/Web/API/Document/forms
you should have something like : w1 = document.forms["someForm"].elements["w1"].value;
edit: this code works absolutely fine for me :
<form name="someForm" onsubmit="return submitAnswers()"  method="POST" >
    <input type="radio" name="w1" value = 'a' id="wla">a.
    <input type ="submit">Submit</input>
</form>
<script>
    function submitAnswers(){
          var w1 = document.forms["someForm"].elements["w1"].value;
          console.log(w1)
          return false;
    }
</script>

I get a console log :  "a"

A: Fix name"w1" to name="w1". And use elements property of Form as @Who Knows showed.


text:
Q: Posting a message to a web worker while it is still running Say we have a web worker referring to a file called "worker.js". We use the worker to execute a function in "worker.js" that does some lengthy operation. We call post the respective message to the worker and proceed in the main thread. However, before the worker has finished doing its initial work, the main thread posts another message to it.
My question: Will the worker continue with our time-taking function and only process the newly posted message once finished or will it interrupt its current operation until the new one has been completed?

A: I've tried out the following code in Google Chrome's debugger:
worker.js:
var cosine;
self.onmessage = function(e) {
    if (e.data.message == 0) {
        for (var i = 0; i < 10000000; i++) {
            cosine = Math.cos(Math.random());
            if (i % 1000 == 0) console.log("hello world");
        }
    } else if (e.data.message == 1) {
        console.log("xyz");
    }
};

main.js:
var worker;

function main() {
    worker = new Worker("js/worker.js");
    worker.postMessage({message: 0});
    setTimeout(xyz, 10);
}

function xyz() {
    worker.postMessage({message: 1});
}

output:
(10000 times) test.js:11 hello world
test.js:14 xyz

The cosine variable is recalculated with every new iteration to provide the "time-taking" algorithm described in the question.  Apparently, the message is only received as soon as the last operation has finished, as I observed the "xyz" output being printed immediately after the 10000th "hello world" output.

A: A Web Worker is backed by a single thread. This means that while the "onmessage" handler is being executed, it will not be able to receive another "onmessage" event until the previous one has finished.
This is quite inconvenient if we want to implement some background computation process that we want to be able to pause and resume, because there is no way to send a "pause" message to a running worker. We are able to stop a web worker via worker.terminate(), but that completely kills the worker.
The only way I can think of is by slicing worker execution into chunks, then post a message from the worker at the end of each chunk, which then triggers a message to the worker to process the next chunk, and so on.


text:
Q: decoration the title of section
I want to add a line segment of about 3 cm that follows the title of section in my book. How can you modify the following code?  I add \rule{3cm}{.45pt} in but it notices capacity exceeds.
\documentclass[oneside,11pt]{book}

\usepackage{siunitx}
\usepackage{fancybox}
\usepackage{pgf,tikz}
\usepackage[textwidth=16.25cm,textheight=19cm]{geometry} %kho sach 18x23

\usepackage[mathscr]{eucal}
\usepackage{graphics, graphpap}

\begin{document}
\tableofcontents
\chapter{First Chapter}

\pagebreak
\section{Perimeter {\rule{3cm}{.45pt}} }

\begin{enumerate}
\item first item
\item second item

\end{enumerate}
\end{document}

A: Without any packages: Make a quick and dirty redefinition of \@sect, the underlying macro for the \section etc. commands.
The redefinition checks whether section or another subsection etc is used and then applies the \rule.
Change the \ruledistskip length at will...
\documentclass[oneside,11pt]{book}

\usepackage{siunitx}
\usepackage{fancybox}
\usepackage{pgf,tikz}
\usepackage[textwidth=16.25cm,textheight=19cm]{geometry} %kho sach 18x23

\usepackage[mathscr]{eucal}
\usepackage{graphics, graphpap}

\newlength\ruledistskip
\setlength{\ruledistskip}{5em}

\makeatletter
\let\l@tex@sect\@sect
\def\@sect#1#2#3#4#5#6[#7]#8{%
  \l@tex@sect{#1}{#2}{#3}{#4}{#5}{#6}[#7]{#8\ifnum0=\pdfstrcmp{#1}{section}%
    \hskip\ruledistskip\rule{3cm}{.45pt}%
    \fi}%
}
\makeatother
\begin{document}

\tableofcontents
\chapter{First Chapter}

\clearpage
\section{Perimeter}

\subsection{Ruleless}

\begin{enumerate}
\item first item
\item second item

\end{enumerate}
\end{document}


text:
Q: [vue-apollo]:An error has occured for query getTeam I am working vue-apollo, currently I am having issues:
Workspace.vue
<script>
    import { GetTeam } from '../constants/query.gql'
    export default  {
        name: 'Workspace',
        data() {
            return {
                getTeam: {}
            }
        },
        apollo: {
            getTeam: {
                query: GetTeam
            }
        }
   }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

query.gql
query GetTeam {
    getTeam {
       id
       name
    }
}

I am facing the below error

[vue-apollo]:An error has occured for query getTeam

Is there a way to fix the issue?

//resolvers.js
const resolvers = {
  Query: {
        async getTeam(_, args, context) {
            const userId = getUserId(context)
            const user = await User.findById(userId)
            return await Team.findById(user.team)
        }
}

//schema.graphql

type Team {
    id: String!
    name: String!
}

type User {
  ......
}

A: Running:
npm install --no-save apollo-utilities@1.0.22

Solved the issue for me. See https://github.com/apollographql/apollo-client/issues/4125


text:
Q: Let $R$ be a prime ring. Then $ab,a\in Z(R) \implies b\in Z(R)$? Let $R$ a prime ring and $a,b\in R$ such that $ab,a\in Z(R),$ center of the ring $R$. Can we say that $b\in Z(R)?$

A ring $R$ is said to be prime if $aRb=0\implies $ either $a=0$ or $b=0$.

If the ring $R$ has unity and $a^{-1}$ exists then clearly $b\in Z(R)$, but in case when the ring $R$ need not have unity, then what can we say about $b$?

A: To root the conclusion in the definitions, assuming $a\neq 0$:
Consider an arbitrary $c\in R$.  Then
$aR(bc-cb)=R(abc-cba)=R(abc-cab)=R(abc-abc)=\{0\}$
where the first two equalities use the centrality of $a$ and the third one uses centrality of $ab$.
By the definition of a prime ring, $bc-cb=0$. Since $c$ was arbitrary, we have found that $b$ is central.
If $a=0$, then $b$ can be anything and $ab$ is central too, so there's no way to conclude $b$ is central.


text:
Q: Is there a way to parametrize 'Workspace' in Team Build 2010 for different branches? Good morning'
Team Foundation Server 2010 question.
Do I need to create a Build Definition for every branch I have ?
Is there a way to parametrize 'Workspace' in Team Build 2010 for different branches, so we could just queue a new build specifying the workspace paths?
I tried finding out how TFS retrieves the workspace paths from the workspace used in the build, but the xaml got me clueless since there are parameters for everything except the mapped paths.
Thanks in advance!

A:
Do I need to create a Build Definition for every branch I have ?

No, but you may want to in order to have a cleaner implementation.

Is there a way to parametrize 'Workspace' in Team Build 2010 for
  different branches, so we could just queue a new build specifying the
  workspace paths?

Yes- but it isn't as straight forward (unless you are using .proj files still).
If you are using the upgrade template and still using proj files:
Building multiple branches, can I use paramters to identify the target branch.
If you are not using the upgrade template, this answer posted on SO will help point you in the right direction:
How to make build definition in TFS Build 2010 configurable w.r.t input variable values and "items to build"


text:
Q: Monitor JVM CPU/RAM usage by java i use JMX to get JVM utilization (CPU , memory , Threads...) and appear result on Jconsole ,
but i need API to integrate with Java code
and get utilization of tomcat then log the data into file
Is there API technology or service in windows using from command line do that?

A: JMX is a technology designed to be used by Java programs, so yes, this is possible. You'll want to create a JMX Service URL to point to the server (presumably on localhost) and then connect it with a JMX Connector:
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

Once you've got that, you can then get MBeans by name,
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

From there you can get the MBean, including things that are reported in the jconsole. For example, with RuntimeMXBean:
RuntimeMXBean proxy = ManagementFactory.newPlatformMXBeanProxy(
  mbsc,
  ManagementFactory.RUNTIME_MXBEAN_NAME,
  RuntimeMXBean.class);
long uptime = proxy.getUptime();

If you want to inspect memory, you'll need to find out the memory pools available, then iterate through each. You can also set up a listener to look out for changes.
See the tutorial for more: https://docs.oracle.com/javase/8/docs/technotes/guides/jmx/tutorial/tutorialTOC.html