text:
Q: Copy the last element of an array into a different position, and then remove it from the end of the array I'm looking for a neat (single-statement) method for copying the last element of an array into a different position (overriding an existing element), and then removing it from the end of the array.
Another way of looking at it is: swap between the element at a given index and the element at the last index, and then remove the element at the last index.
I can do it like so:
function func(array, index) {
    array[index] = array[array.length - 1];
    array.length--;
    return array;
}

And like so:
function func(array, index) {
    array[index] = array.slice(-1)[0];
    array.pop();
    return array;
}

And of course, any "hybrid" of the two functions above.
Is there a single-statement method for achieving that?
I was thinking of splice, but I'm a little unsure of how to actually make it work.

A: You can try this:

function func(array, index) {
    array[index] = array.pop();
    return array;
}

// Or
// const func = (array, index) => (array[index] = array.pop(), array);

const arr = func([1,2,3,4], 1);

console.log(arr);

To always remove the last element:

function func(array, index) {
    if(index < array.length -1) array[index] = array.pop()
    else array.pop();
    return array;
}

// Or
// const func = (array, index) => (index < array.length -1 ? array[index] = array.pop() : array.pop(), array);

console.log(func([1,2,3,4], 1));

console.log(func([1,2,3,4], 3));

A: You can use pop() and then assign it to the index requied. Because pop() returns the last element of array. You don't need to return array from function because it modifies the array.

const func = (array, index) => array[index] = array.pop();
let arr = [0,1,2,3,4, 'last'];
func(arr, 2);
console.log(arr)

If you want the function to return the array too. You can use the , operator.

const func = (array, index) => index === arr.length - 1 ? arr.slice(0, -1) : ((array[index] = array.pop()), array);
let arr = [0,1,2,3,4, 'last'];
console.log(func(arr, 5));


text:
Q: Stop Mathematica from giving imaginary solutions I have the following equation:
$$D=\frac{1}{64} \pi  A ^3 B \sin \left(C\right)-\frac{1}{2} \pi  A  B \sin \left(C\right)$$
which I want to solve for $A$. The equation is cubic in $A$ so this should give me 3 answers and, potentially, imaginary parts to the answers. I know, from the physical meaning of the parameters, that all parameters ($A$,$B$,$C$ and $D$) are positive and real.
My question is: how can I use Solve on this equation and make sure that there will be no imaginary parts popping up in the solution?
I have used the suggestion by Chris and tried:
Solve[d == 1/64 π a^3 b Sin[c] - 1/2 π a b Sin[c], a, Reals]

but I still see that there is a $\imath\sqrt{3}$ term in the answer. Why does this still appear?

A: You can use the Reals Domain option in Solve as in
 Solve[x^3 + 2 a x^2 + 4 == 0, x, Reals] // ToRadicals // First // First

For the example above, calling d=2D/Pi/B/Sin[C]
 Solve[d == 1/32  A^3  -  A , A, Reals] // ToRadicals // First //First // FullSimplify

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to real-time move the range type input's slider using javascript without refreshing page? <input type="range" value="0" min="0" max="100">

I did try the following, but the slider no response.
var i = 0;
setInterval(function(){
    document.querySelector('input[type=range]').value = i++;
}, 1000);

or impossible?

A: you can do it with stepUp and stepDown functions
document.getElementById("myslider").stepUp(1);
document.getElementById("myslider").stepDown(1);

working demo : http://jsfiddle.net/dp6cwoom/

A: works fine in Chrome http://jsfiddle.net/gCSFV/

A: <input type="range" value="0" min="0" max="100">
<script type="text/javascript"><!--
document.querySelector('input[type=range]').value = 30;
--></script>

Works ok in Safari4 (Win).
Ensure, your code is after input element or is called inside onload or similar function.

A: It should work.

As per the MDC doc on document.querySelector
Its dsupported by IE8, FF3.5, Chrome1, Safari3.2 and so is input type=range

Syntax
element = document.querySelector(selectors);

Returns null if no matches are found;
  otherwise, it returns the first
  matching element.

Be careful that querySelector returns only first element of the matched ones.
So, document.querySelector('input[type=range]') wont be as desirable as something like document.querySelector('#myrange')

A: I found a way but not very good: to modify the style of input dynamically.
var i = 0,
    oRange = document.querySelector('input[type=range]');

setInterval(function(){
    oRage.value = i;
    oRage.style.fontSize = i + 'px';
    i++;
}, 1000);


text:
Q: How to make a JavaScript singleton with a constructor without using return? I currently know two ways to construct singletons in JavaScript. First:
var singleton = {
 publicVariable: "I'm public",
 publicMethod: function() {}
};

It is perfect except that it does not have a constructor where I could run initialization code.
Second:
(function() {

var privateVariable = "I'm private";
var privateFunction = function() {}

return {
 publicVariable: "I'm public",
 publicMethod: function () {}
}

})();

The first version does not have private properties nor does it have a constructor, but it is faster and simpler. The second version is more complex, ugly, but has a constructor and private properties.
I'm not in a need for private properties, I just want to have a constructor. Is there something I am missing or are the two approaches above the only ones I've got?

A: function Singleton() {
  if ( Singleton.instance )
    return Singleton.instance;
  Singleton.instance = this;
  this.prop1 = 5;
  this.method = function() {};
}

A: Here is my solution with closures:
function Singleton() {

    Singleton.getInstance = (function(_this) {
        return function() { return _this; };
    })(this);
}

Test:
var foo = new Singleton();
var bar = Singleton.getInstance();
foo === bar; // true

A: If you are just looking for a place to initialise your singleton, how about this?
var singleton = {
    'pubvar': null,
    'init': function() {
        this.pubvar = 'I am public!';
        return this;
    }
}.init();

console.assert(singleton.pubvar === 'I am public!');

Simple and elegant.

A: var singleton = new function() {  // <<----Notice the new here
  //constructorcode....

  this.publicproperty ="blabla";
}

This is basically the same as creating a function, then instantly assiging a new instace of it to the variable singleton. Like var singleton = new SingletonObject();
I highly advice against using singletons this way in javscript though because of the execution order is based on where in the file you place the object and not on your own logic.

A: What about this?
var Singleton = (function() {
    var instance;

    // this is actual constructor with params
    return function(cfg) {
        if (typeof instance == 'undefined') {
            instance = this;
            this.cfg = cfg;
        }
        return instance;
    };
})();

var a = new Singleton('a');
var b = new Singleton('b');

//a === b; <-- true
//a.cfg <-- 'a'
//b.cfg <-- 'a'

A: I make it an actual Singleton with static functions and no this like so:
class S {
    //"constructor"
    static init() {
        //Note: Since it's a singleton, there's no "this" instance.
        //Instead, you store variables directly on the class.
        S.myVar = 7;
    }

    static myOtherFunc() {
        alert(S.myVar);
    }
}
//Immediately call init() to make it the "constructor".
//Alternatively, you can call init() elsewhere if you'd
//like to initialize it at a particular time.
S.init();

//Later:
S.myOtherFunc();
S.myVar = 10;


text:
Q: Mock standalone directive in a standalone component I'm trying to write a unit test for a standalone component and mock its dependency. This standalone component has the following content:
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DemoDirectiveDirective } from './demo-directive.directive';

@Component({
  selector: 'app-demo-cmp',
  standalone: true,
  imports: [CommonModule,DemoDirectiveDirective],
  templateUrl: './demo-cmp.component.html',
})
export class DemoCmpComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
}

and DemoDirectiveDirective has this content:
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appDemoDirective]',
  standalone: true,
})
export class DemoDirectiveDirective {
  constructor(private hostElement: ElementRef) {
    this.hostElement.nativeElement.innerHTML += 'Update from directive! ';
  }
}

I want to test DemoCmpComponent like this:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { DemoCmpComponent } from './demo-cmp.component';

describe('DemoCmpComponent', () => {

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [DemoCmpComponent],
    }).compileComponents();
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DemoCmpComponent);
    fixture.detectChanges();

    expect(fixture.nativeElement.querySelector('p').innerHTML).toBe(
      'demo-cmp works!'
    );
  });
});

This test will fail as the the content of the p tag will be Update from directive! demo-cmp works!.
What I'm missing here is the step in which I mock DemoDirectiveDirective which I don't know how to and I don't find any resources for this on Angular page.
Note this is just a demo test, a proof of concept. Please ignore the component names and the  superfluous test.
Here is the GitHub repo with the code.

A: One of the easiest ways to mock an angular declaration is to use a mocking library, for example ng-mocks.
ng-mocks supports standalone component, and its MockBuilder does know how to mock imports of standalone declarations.
In your case, the test can be like:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MockBuilder } from "ng-mocks";

import { DemoCmpComponent } from './demo-cmp.component';

describe('DemoCmpComponent', () => {

  beforeEach(() => {
    return MockBuilder(DemoCmpComponent);
    // it will mock DemoDirectiveDirective automatically,
    // because it's a dependency of DemoCmpComponent.
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DemoCmpComponent);
    fixture.detectChanges();

    expect(fixture.nativeElement.querySelector('p').innerHTML).toBe(
      'demo-cmp works!'
    );
  });
});

Here is a live example: https://codesandbox.io/s/bold-kate-1gkymd?file=/src/test.spec.ts:770-812

A: // define a mock directive
@Directive({standalone: true, selector: "[appDemoDirective]"})
class MockDemoDirectiveDirective {
  // define whatever mock inputs/methods etc you need here
}

// override imports in TestBed to use the mock directive
TestBed.overrideComponent(DemoCmpComponent, {
  remove: {imports: [DemoDirectiveDirective] },
  add: {imports: [MockDemoDirectiveDirective]}
})


text:
Q: Setup libGDX project using MOE plugin How to setup the libGDX project using MOE plugin.
If i try to select ios-moe at the setup of libGDX project then my build fails with following error.

Generating app in
  /Users/USERNAME/Desktop/PaxPlay/libGDXProjects/SampleGame Executing
  '/Users/USERNAME/Desktop/PaxPlay/libGDXProjects/SampleGame/gradlew
  clean --no-daemon' To honour the JVM settings for this build a new JVM
  will be forked. Please consider using the daemon:
  https://docs.gradle.org/2.10/userguide/gradle_daemon.html.
  Configuration on demand is an incubating feature.
FAILURE: Build failed with an exception.
What went wrong: A problem occurred configuring root project
  'SampleGame'.
Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.intel.gradle:moeGradlePlugin:1.1.0.final-1.
  Searched in the following locations:
  file:/Users/USERNAME/.m2/repository/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.pom
  file:/Users/USERNAME/.m2/repository/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.jar
  https://repo1.maven.org/maven2/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.pom
https://repo1.maven.org/maven2/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.jar
https://oss.sonatype.org/content/repositories/snapshots/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.pom
https://oss.sonatype.org/content/repositories/snapshots/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.jar
  file:/Applications/Intel/multi_os_engine/gradle/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.pom
  file:/Applications/Intel/multi_os_engine/gradle/com/intel/gradle/moeGradlePlugin/1.1.0.final-1/moeGradlePlugin-1.1.0.final-1.jar
  Required by: :SampleGame:unspecified
  Try:
  Run with --stacktrace option to get the stack trace. Run with --info
  or --debug option to get more log output.
BUILD FAILED
Total time: 8.492 secs Done! To import in Eclipse: File -> Import ->
  Gradle -> Gradle Project To import to Intellij IDEA: File -> Open ->
  build.gradle To import to NetBeans: File -> Open Project...

A: I had the same problem from time to time. Use the newest version of the multi os engine, which requires no local installation.
Multi-OS Engine Release 1.1.0
Samples Repository on GitHub


text:
Q: Passing self arguments to callback function in separate method I'm trying to refactor my code and break things to learn and I broke something, hope you can help me learn.
I got a working scraper that runs over multiple pages as follows:
class someSpider(scrapy.Spider):
    name = 'spider_name'
    allowed_domains = ['www.example.com']
    start_urls = ['https://www.example.com&page=1']

    def parse(self, response):
        result_parsed = json.loads(result)
        results = result_parsed.get('results') #yield actual results
        current_page_number = result_parsed.get('currentPage') #gets the page from the link as part of the API response

        for result in results:
            count += 1

           yield{

            ... #gives me the results as desired

            }

        go_to_nextpage(self, current_page_number) #### THIS DOES NOT WORK, not error, just stops at one page ####

        #### THIS WORKS ####
        # next_page_number = result_parsed.get('currentPage') +1
        # yield scrapy.Request(
        #     url=f'https://www.immoweb.be/en/search-results/house-and-apartment/for-sale/brussels/district?countries=BE&hasRecommendationActivated=true&page={next_page_number}&orderBy=relevance&searchType=similar',
        #     callback=self.parse
        # )

With next_page_number() defined as:
def go_to_nextpage(self, current_page_number):
    next_page_number = current_page_number +1
    yield scrapy.Request(
        url=f'https://www.example.com&page={next_page_number}',
        callback=self.parse
    )

I'm guessing I don't properly understand 2 things:

*

*the working of the self keyword

*the way the callback method and the parse method work / interact

any help is appreciated

A: There are a couple of issues that I can hopefully help clarify.

*

*You are not using the self parameter correctly.

*

*In python, when you call a class method like this: myclass.method(); myclass is the variable for the an instance of the class.

*When the same method is called from inside another instance method the self variable, which is automatically injected as the first parameter, is used instead: self.method().

*In the context of your code it should look like this self.go_to_nextpage(current_page_number)

*Scrapy can only process requests that are returned/yielded from the it's parser callback.

*

*You correctly yield the first items as you indicated, but request that is yielded by the go_to_nextpage method because your current code doesn't do anything with the return value.

*Another issue is that you are yielding a single result in go_to_nextpage which automatically turns that method into a generator

*The easiest solution to this is to simply return the request instead of yielding it.

Here is an example of what it should look like:
class someSpider(scrapy.Spider):
    name = 'spider_name'
    allowed_domains = ['www.example.com']
    start_urls = ['https://www.example.com&page=1']

    def parse(self, response):
        result_parsed = json.loads(result)
        results = result_parsed.get('results')
        current_page_number = result_parsed.get('currentPage')
        for result in results:
            count += 1
            yield{ something }
        # go_to_nextpage(self, current_page_number) <- this line is the issue
        # because you don't handle the return value.
        yield self.go_to_nextpage(current_page_number)

    def go_to_nextpage(self, current_page_number):
        next_page_number = current_page_number +1
        return scrapy.Request(url=(f'https://www.immoweb.be/en/search-results/house-and-apartment/for-sale/brussels/district?countries=                 BE&hasRecommendationActivated=true&page={next_page_number}&orderBy=relevance&searchType=similar',
                              callback=self.parse)

If you wanted to use yield in your go_to_nextpage method you could write it like this.
class someSpider(scrapy.Spider):
    def parse(self, request):
        ...
        # because you don't handle the return value.
        for i in self.go_to_nextpage(current_page_number):
            yield

    def go_to_nextpage(self, current_page_number):
        next_page_number = current_page_number +1
        yield scrapy.Request(url=(f'https://www.immoweb.be/en/search-results/house-and-apartment/for-sale/brussels/district?countries=                 BE&hasRecommendationActivated=true&page={next_page_number}&orderBy=relevance&searchType=similar',
                              callback=self.parse)


text:
Q: EF Migrations - There is already an object named '' in the database I am having trouble adding a new table to my database. these are the commands I entered when trying to add the new migration:
Add-Migration AdminSett

Scaffolding migration 'AdminSett'. The Designer Code for this
  migration file includes a snapshot of your current Code First model.
  This snapshot is used to calculate the changes to your model when you
  scaffold the next migration. If you make additional changes to your
  model that you want to include in this migration, then you can
  re-scaffold it by running 'Add-Migration AdminSett' again.

Update-Database AdminSett

Specify the '-Verbose' flag to view the SQL statements being applied
  to the target database. Applying explicit migrations:
  [201607011035464_AdminSett]. Applying explicit migration:
  201607011035464_AdminSett. System.Data.SqlClient.SqlException
  (0x80131904): There is already an object named 'AdminSettings' in the
  database.    at
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
  Boolean breakConnection, Action1 wrapCloseInAction)    at
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection, Action1 wrapCloseInAction)    at
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
  stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)    at
  System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
  SqlCommand cmdHandler, SqlDataReader dataStream,
  BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
  stateObj, Boolean& dataReady)    at
  System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
  methodName, Boolean async, Int32 timeout, Boolean asyncWrite)    at
  System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
  completion, String methodName, Boolean sendToPipe, Int32 timeout,
  Boolean asyncWrite)    at
  System.Data.SqlClient.SqlCommand.ExecuteNonQuery()    at
  System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand
  t, DbCommandInterceptionContext1 c)    at
  System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget
  target, Func3 operation, TInterceptionContext interceptionContext,
  Action3 executing, Action3 executed)    at
  System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand
  command, DbCommandInterceptionContext interceptionContext)    at
  System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
  at
  System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement
  migrationStatement, DbConnection connection, DbTransaction
  transaction, DbInterceptionContext interceptionContext)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement
  migrationStatement, DbConnection connection, DbTransaction
  transaction, DbInterceptionContext interceptionContext)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1
  migrationStatements, DbConnection connection, DbTransaction
  transaction, DbInterceptionContext interceptionContext)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable1
  migrationStatements, DbTransaction transaction, DbInterceptionContext
  interceptionContext)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable1
  migrationStatements, DbConnection connection, DbInterceptionContext
  interceptionContext)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1
  migrationStatements, DbConnection connection, DbInterceptionContext
  interceptionContext)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1
  migrationStatements, DbConnection connection)    at
  System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
  at
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
  at
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
  operation)    at
  System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action
  operation)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1
  migrationStatements, DbTransaction existingTransaction)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1
  migrationStatements)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable1
  migrationStatements)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String
  migrationId, VersionedModel targetModel, IEnumerable1 operations,
  IEnumerable1 systemOperations, Boolean downgrading, Boolean auto)
  at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration
  migration, DbMigration lastMigration)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration
  migration, DbMigration lastMigration)    at
  System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1
  pendingMigrations, String targetMigrationId, String lastMigrationId)
  at
  System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1
  pendingMigrations, String targetMigrationId, String lastMigrationId)
  at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String
  targetMigration)    at
  System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.b__b()
  at
  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
  mustSucceedToKeepDatabase)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action
  mustSucceedToKeepDatabase)    at
  System.Data.Entity.Migrations.DbMigrator.Update(String
  targetMigration)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String
  targetMigration)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
  at System.AppDomain.DoCallBack(CrossAppDomainDelegate
  callBackDelegate)    at
  System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
  at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
  runner)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.Update(String
  targetMigration, Boolean force)    at
  System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
  at
  System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
  command) ClientConnectionId:dec63212-4546-48a9-bf8e-9e2b8548fcf3 Error
  Number:2714,State:6,Class:16 There is already an object named
  'AdminSettings' in the database.

Also in the _Migrations table in the database I there is no row for the migration with the name: AdminSett

A: I stumbled on this question when trying to figure out why my online azure database would not accept my update command complaining about the same issue.
Upon inspecting the _EFMigrationHistory table I found that the online database was missing several entries for migrations which had already happened to the online database (not sure why this is, possibly I uploaded the datapac to the database and that didn't include the _EFMigrationHistory table?).
At any rate I solved the problem by copying all the relevant migrations from myu local to the online database so that EF knew which migration it should start running from.

A: There is a table in the database with name of Admin Setting, you should drop it manually from the database, after that run update-database command to update the database.


text:
Q: Disable double tap to zoom Reasking because the solutions here aren't working for me.
Can the double-tap-to-zoom be disabled in the latest Safaris? I'm writing a game with a keyboard; people will hit the same key twice while typing fast. Obviously zooming is not appropriate in such a situation.
I've got
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

I've got
html, body, * { touch-action: manipulation }

I've got style="touch-action: manipulation" on the keys themselves.
Safari still zooms in iOS 15.
Is this fixable?


text:
Q: How to stop errors from showing on web pages, show on pop up instead? i am developing this app which is going to be a template in my organization, but there is a problem i need to solve. I want to show errors on an AjaxControlTookit's modalpop and never let it show that ugly yellow text on the browser with stacktrace.
WHERE should i intercept and WHAT should i intercept for this to work?
Is there an lifecycle event i can use that happens before rendering but after the page is itself contructed (and thus the error has happened?) at that event, will i have the page controls ready? Assuming i have a masterpage and the modalpopup will be there, could i do this general error handling in the masterpage?
Is this something i need to use global.asax? (i have never used it, but with a name like that and the events it has, i can figure what it does)
Is this something doable even? could i catch every exception, even browser errors that happened related to my pages?
Edit:
My problem isn't really with what the user sees, is that i don't want the browser to display the stack trace and the yellow error page, destroying anything the user has done so far.
I want to create a nice and clean user experience and if the user can recover from whatever issue is causing the exception i want them to have the option, which include not destroying the page they had before the post-back. Is that understandable or i am unable to explain this any better?

A: You could easily do this using javaScript:
window.onerror = function(msg, url, linenumber) {
    alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
    return true;
}

http://www.javascriptkit.com/javatutors/error2.shtml

A: Generally speaking, here is a link on how to handle errors (including global errors) in ASP.NET:
How to: Display Safe Error Messages
Then with regards to the modalpopup, in the samples mentioned in the link, the user was redirected to some other error page. You can pass the error messages to that error page and then display the modelpopup on that error page.


text:
Q: Why does my While loop Exit? My comments illustrate my line of reasoning but clearly I've got something wrong. My code just jumps straight to "Your total debt is..."
# Dictionary of Bills

expenses = {'mortgage':[], 'personal':[], 'power':[], 'insurance':[], 'water':[], 'food':[], 'savings':[], 'fuel':[], 'phone':[], 'internet':[], 'credit':[], 'emergencies':[]}
totalDebt = 0
switch = "A"

while switch == switch.isalpha(): # Condition is true, switch is a letter
for each in expenses: # Iterates through each bill
    debt = input("%s: "%each) # User input
    if debt.isdigit(): # checks to make sure they only enter numbers
        debt = int(debt) # Converts debt to its integer value
        totalDebt = totalDebt + debt # adds debt to keep a running total.

    else: # User entered something other than a number
        print("Only enter digits!")

print("Your total Debt is: $%i" %totalDebt)

input("Press Enter to continue: ")

print("What is this fortnights Income?")

A: Your condition doesn't make any sense here:
while switch == switch.isalpha(): # Condition is true, switch is a letter

switch.isalpha() returns either True or False. switch itself will not be equal to either of those two values, so the whole expression is always going to be False. Remove the equality test:
while switch.isalpha():  # Condition is true, switch is a letter

Note that your code never actually changes switch, so now your loop is going to continue forever.

A: The While is False
>>> switch
'A'
>>> switch.isalpha()
True
>>> switch == switch.isalpha()
False

You must use switch.isalpha() allown


text:
Q: What is the difference between case object defined in scala repl and sbt console? When I declare case object in SBT Console, it creates module
scala> case object A
defined module A

And when I define it in Scala REPL,  it creates object
scala> case object A
defined object A

Thanks in advance!

A: There is no difference in using the Scala REPL or SBT Console.
The difference you are seeing is probably because of Scala Version.
Cross check the Scala Version on Scala REPL and SBT Console it will be different as in Scala with version 10 series case object is defined as module but after Scala version 11 series they show object.
You can check the Scala version when you are opening the SBT Console or Scala REPL
You can also refer to this.
Hope this clears your doubt.
Thanks


text:
Q: How to adjust speed of nunit test cases in C# or in nunit interface? I have used selenium IDE and created test cases. I have converted them to Nunit with C# and I started running testcases. How can I adjust speed of running test cases using either nunit interface or C# code. (In selenium ide interface, I could able to adjust speed so as to run test case slowly.)

A: You could add a TestFixtureSetup to each TestFixture.  The example below should run before each test and cause a 5 second wait:
[TestFixture]
public MyTests()
{
    [TestFixtureSetUp]
    public void Init()
    {
        System.Thread.Sleep(5000);
    }

    ...
}

A: One of these links ought to work:
similar SO question:
selenium webdriver manage speed?
Forum result for selenium (http://seleniumforum.forumotion.net/t376-to-control-of-speed-execute-in-selenium-rc):
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", URL");
selenium.Start();
selenium.SetSpeed("1000");

}

A: I've been looking into this quite a lot over the past few days. By far the simplest way to solve this is to create a driver property, rather than a variable and add a wait to the get.
  private IWebDriver _driver;
    public IWebDriver driver
    {
        get{ Thread.Sleep(500);
            return _driver;
        }

        set
        { _driver = value; }
    }

This means that anytime your driver is requested, which is anytime you do anything in the browser, it will slow it down by the specified amount.


text:
Q: How to render checkbox on the  (React Native) I want to put checkbox on the Image. Here is current Screen.

It's simple FlatList. Here is renderItem() for FlatList
   <TouchableWithoutFeedback
      onPress={() => this._handleImagePress(item.id)}>
      <Image
        key={item.id}
        source={{uri: item.outfit_img}}
        style={styles.rowImage}
        resizeMode="cover"
      />
    </TouchableWithoutFeedback>

What I want to implement is like this screen below

I have <CheckBox on={true}> component to render checked checkbox.
Requested
handleImagePress = (id) => {
    if(_.includes(this.state.selectedIds, id)) {
        let newSelectedIds = _.filter(this.state.selectedIds, (curObject) => {
            return curObject !== id;
        });
        this.setState({selectedIds : newSelectedIds});
      } else {
        let newSelectedIds = [...this.state.selectedIds, id];
        this.setState({selectedIds : newSelectedIds});
      }
}

A: You just need to do this in your renderItem():
renderItem({item}) => {
 const isSelected = this.state.selectedIds.includes(item.id)
 return (
    <TouchableWithoutFeedback
      onPress={() => this._handleImagePress(item.id)}
    >
       <Image
         key={item.id}
         source={{uri: item.outfit_img}}
         style={styles.rowImage}
         resizeMode="cover"
       />
       { isSelected && <CheckBox on={true}> }
    </TouchableWithoutFeedback>
 )
}

Here Checkbox should have absolute positioning, and you can provide your desired styles. Also, you need to add an extraData prop with value this.state.selectedphotos to your Flatlist.


text:
Q: I forget how to do this. (Right angle triangles with barely any available measurements) So I'm designing a roof in Sketchup for school, and I came across this and can't seem to figure it out. The angle between both sides of the roof has to be a 90° angle (see picture). This particular angle has to be situated along line y, which is 48 inches from the right and 240 from the left side. Line x, which runs from point A to B, is what I need to find out. I brute forced it and got something around 107, but it's not precise enough. Please explain how to find the length of x. This is the picture, it won't let me post it because I don't have 10 rep yet... https://i.stack.imgur.com/MjQoL.jpg
Edit: yes, all angles touching point B are right angles. Forgot to add those...

A: Use the Geometric mean theorem to compute
$$ \sqrt{240 \cdot 48} = 107.33 \enspace. $$

A: Let call the left most point of your diagram $X$ and the right most point $Y$. Now notice that the angle at $X$ is the same as the angle $BAY$ ; lets call this angle $\phi$ & the perpendicular distance required $\lambda$
\begin{eqnarray*}
tan \phi =\frac{\lambda}{240} =\frac{48}{\lambda}
\end{eqnarray*}
so $\lambda^2=48 \times 240 $. Which gives $\lambda=48 \sqrt{5}$ which is about $107.33$


text:
Q: How to cache a page via a Chrome Extension service worker? I would like to cache the contents of a website I visit using a Chrome extension, but I am unable to figure out how to save the response of the page into chrome.storage. I would then like get the cache to load the cached page at a different date. Is this possible?

A: MyCache automatically stores saved copies of the pages you visit.


text:
Q: How do I set an HTTP Request Default based on a URL rather than host, port, scheme? I'm just starting with JMeter and porting my Postman API.  I was wondering is there a way to have the user defined variable as
baseUrl=http://localhost:28082

And have HTTP request defaults or equivalent using that value so we don't have to break up the components?

A: Theoretically you can put the full URL into Path field of HTTP Request sampler (or HTTP Request Defaults)

but in that case it might cause malfunction of other test elements like HTTP Cookie Manager or HTTP Cache Manager so it's better to split it into protocol, host and port and manipulate the path.
Also HTTP Request Defaults assume "default" values which will be populate if you leave this field empty in the HTTP Request sampler so this "baseURL" won't act as a "prefix"

A: I added a parser BeanShell Sampler (since I have JDK17 in my PC and Groovy is causing issues)
import java.net.URI;
SampleResult.setIgnore();
var baseUri = URI.create(vars.get("baseUri"));
var httpProtocol = baseUri.getScheme();
var httpHost = baseUri.getHost();
var port = baseUri.getPort();
if (port == 0 && httpProtocol.equals("https")) {
    port = 443;
} else if (port == 0) {
    port = 80;
}
var httpPrefix = baseUri.getPath();
vars.put("httpProtocol", httpProtocol);
vars.put("httpPort", String.valueOf(port));
vars.put("httpHost", httpHost);
vars.put("httpPrefix", httpPrefix);

Then put the variables in.

I added support for prefix though I never really use it in my JMeter files at the moment


text:
Q: Firestore rules work in simulator but failed when reading documents from angular app All rules are working fine in simulator but not through app. I have been following youtube channel Fireship's video on google signin  with custom data angluar here.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

My authservice
@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private ngAuth: AngularFireAuth,
    private firestore: AngularFirestore,
  ) {
    this.user$ = this.ngAuth.authState.pipe(
      switchMap(user => user ? this.userRef(user).valueChanges() : of(null)),
    );
  }

  private userRef({ uid }): AngularFirestoreDocument {
    return this.firestore.doc<User>(`users/${uid}`);
  }
}

Using in html
<img *ngIf="auth.user$ | async as user" [src]="user.photoURL" alt="user">

A: You are passing user object to userRef. Try modifying the argument.
              :
      switchMap(user => user ? this.userRef(user.uid).valueChanges() :
              :

  private userRef(uid: string): AngularFirestoreDocument {
    return this.firestore.doc<User>(`users/${uid}`);
  }

A: For anyone coming to this question, the error was in firebase SDK.
At 1 jul, 2021, firebase team released new firebase sdk v8.7.0 that fixes the issue
see the release notes


text:
Q: NET::ERR_CERT_DATE_INVALID error in Chrome when browsing python.org or github.com Since one of the latest chrome updates, I'm getting this error that does not allow me to access some webs such as python.org or github.com. I've googled the problem but they say that it is generated when the system clock is out of sync. I've checked it and it is perfectly in sync ( i've even used different NTP servers apple, windows, ntp.org, etc...)
I don't have this problem with other browsers in the same computer, neither with the same chrome version in other computers in the same network.
I've even tried to reinstall chrome from scratch without success.
There are no proxies , nor firewalls in the computer.
Any ideas?

A: See Can AVG 2015's Online Shield be used Chrome (and not give NET::ERR_CERT_DATE_INVALID)? for a possible solution: disable Online Shield on your AVG firewall (or the equivalent component - that scans files before they're downloaded - on the anti-virus you use).


text:
Q: Exclude duplicates by a certain field I have the following situation:
   id     ||   attribute_1 | attribute_2 | attribute_3
    1     ||       3             2            null
    2     ||       2             2            null
    3     ||       1             4            null
    4     ||       3             2             44
    5     ||       2             2             55

Rows 1 and 4, 2 and 5 are almost identical save upon value of attribute number 3.
How can I get all rows that have duplicates by values in attribute_1 and attribute_2 but attribute_3 is null?
The result should be next:
     id  ||   attribute_1 | attribute_2 | attribute_3
      1  ||       3             2            null
      2  ||       2             2            null

A: You can try use COUNT window function.
SELECT *
FROM (
    SELECT *,COUNT(*) OVER(PARTITION BY attribute_1 ,attribute_2) cnt
    FROM T
) t1
WHERE cnt > 1 AND attribute_3 IS NULL

sqlfiddle

A: One method is using exists
select *
from tbl t
where attribute_3 is null
    and exists ( select 1
                 from tbl t2
                 where t1.attribute_1 = t2.attribute_1
                   and t1.attribute_2 = t2.attribute_2
                   and t2.attribute_3 is not null)


text:
Q: Can you know which picture was sent from your icloud by someone else? I was using my gf's laptop (apple), logged in my own facebook, sent a picture to myself on my facebook from her icloud. Can she notice it?

A: Maybe

*

*If you left the downloaded photo from iCloud somewhere on her Mac, she may find out.

*If you do something with that photo (post it online etc) she will get suspicious.

*If she checks her logs and finds a photo downloaded, when she wasn't using her Mac. She could figure it out.


text:
Q: Java InputStreamReader from URL does not encode "Umlaute" I try to read the html content from an URL. When I wan't to print the content to the console "Umlaute" like ä, ö, ü are displayed wrong.
URL url = new URL("http://www.lauftreff.de/laeufe/halbmarathon-1-2017.html");
URLConnection conn = url.openConnection();
InputStreamReader input = new InputStreamReader(conn.getInputStream(),StandardCharsets.ISO_8859_1);
BufferedReader bi = new BufferedReader(input);
String inputLine;
while((inputLine = bi.readLine()) != null){
    System.out.println(inputLine);
}

In the header of the html the information of the charset says ISO_8859_1. Also UTF-8 does not work.
Has anyone an Idea what to do?

A: In the website the Umlaute are decoded as HTML entities. So you would need to decode those. The code below should work, but it is untested.
URL url = new URL("http://www.lauftreff.de/laeufe/halbmarathon-1-2017.html");
URLConnection conn = url.openConnection();
InputStreamReader input = new InputStreamReader(conn.getInputStream(),StandardCharsets.ISO_8859_1);
BufferedReader bi = new BufferedReader(input);
String inputLine;
while((inputLine = bi.readLine()) != null){
    inputLine = StringEscapeUtils.unescapeHtml4(inputLine);
    System.out.println(inputLine);
}


text:
Q: Handling response from form submit that runs in new browser tab I have this form which run service on my BE and result is displayed on new tab. It works fine but BE Service is running more than 10 minutes so currently I am refactoring it to use polling instead of 1 long time running request. Backend is done and it is now returning 202 code with ID of background job. I need to find a way how to handle 202 response in new tab and run new request to poll BE for a result.
Any ideas how to "send polling code" to new tab or how to handle it in original tab?
Form is triggered with button. Now it only display 202 response on new tab. Need to find a way how to catch that response and run new request...
....
var form$ = $("<form>", {id:"myID", method :"post", action :serviceUrl, target :"_blank"});
$("body").append(form$);
form$.submit();
form$.remove();
...


text:
Q: What model to classify a discretized continuous variable Consider a variable $y$ (typically, $y_i$ is something like number of inhabitants of city $i$) and some given features $X$. Let us assume that these features are continuous (eg. total city area, number of shops, roads). We want to use features $X$ to explain $y$.
Although the variable $y$ should naturally be seen as a continuous one, it has been discretized in my training set to five classes: $0 \leq y < 300$, then $300 \leq y < 1.000$, and so on. Thus, even for my training set, I do not know the continuous value of $y$, only its discrete class $C(y)$.
I need to use this training data to predict $C(y)$ for the other cities (ie. cities that are not part of my training set). Please note that I only wish to predict to which discrete class each other city belongs (I am not seeking for an accurate prediction of $y$ itself).
I am wandering what could be a theoretically satisfying approach to this kind of problem. Should I handle this as a classification problem even though there is an underlying hidden continuous variable? Can I identify borderline data points and give them less weight? Should I convert $C(y)$ to a continuous variable using the middle of the class as an estimate?
I would appreciate any idea or reference on this topic. Thanks to all.


text:
Q: Accessing the public response version of a Google Form Does the Apps Script Form Service only allow access to forms that the user has been given edit access to? I'm trying to read the question data for end users who only have access to the public (response) version of the form.
It works as expected for forms that I have edit access to but for others I get this error message on openById():
Exception: No item with the given ID could be found. Possibly because you have not edited this item or you do not have permission to access it.

A: Yes. You need edit access to access the form.
Relevant documentation:

Throws an exception if the ID is invalid or the user does not have permission to open the form.

Google docs like  Google sheets can be published. Google forms is published by default. No one with the published link of any type of Google document like Google sheets can access the actual file through openById(). It's a similar case here.

A: We need access.
Why ?
There is a difference between open form by going to https://xyz url. And accessing it via script (i.e. FormApp.openById(formId))
Both are different things.
When we go to form url, we are actually not accessing the form object it self. We're just accessing the web interface of same.
Whereas, Form.openById(formId) fetches the form object itself.


text:
Q: change master page i have this on my master.page

        Create a New Entry

when i go to content page ("NewEntry.aspx") i want the link name to be changed to "Update Entry"

         Update Entry

any feedback?

A: Make the link an asp:Hyperlink. Then have the master page expose a function or property:
public void SetLink(string href, string text)
{
    A1.NavigateURL = href;
    A1.Text = text;
}

Call the function from the main page.

A: You can use a hyperlink control <asp:hyperlink> and set the url as well as the text values.

A: I would recommend handling this as a HyperLink control as others have mentioned. If for some reason you must handle this as a server-side HTML anchor, you can access it using the following code from your webform code-behind:
HtmlAnchor link = (HtmlAnchor)(this.Master).FindControl("A1");
link.InnerText = "Update Entry";

A: You can also define a content place holder where you have "Create a New Entry". Leave that as the default inside that place holder, and only in the content page set content for it to Update Entry.


text:
Q: Не могу автоматически обновить данные из xml файла в DataGrid WPF После сохранения данных в xml DataGrid не обновляется.
Подскажите, как автоматически обновить DataGrid.
Код xaml:
        <Window x:Class="TestWPF.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:TestWPF"
            mc:Ignorable="d"
            Title="MainWindow" Height="600" Width="750" Name ="Window" >
        <Grid Margin="-16,-34,-8,-96">
            <TextBox x:Name="Tbx_Email" HorizontalAlignment="Left" Height="25" Margin="100,50,0,0"                  TextWrapping="Wrap" Text="E-mail" VerticalAlignment="Top" Width="250" AutomationProperties.Name="Email"/>
            <TextBox x:Name="Tbx_Position" HorizontalAlignment="Left" Height="25" Margin="100,80,0,0" TextWrapping="Wrap" Text="Position" VerticalAlignment="Top" Width="250" AutomationProperties.Name="Email"/>
            <TextBox x:Name="Tbx_Company_Name" HorizontalAlignment="Left" Height="25" Margin="500,50,0,0" TextWrapping="Wrap" Text="Company Name" VerticalAlignment="Top" Width="250" AutomationProperties.Name="Email"/>
            <TextBox x:Name="Tbx_Address" HorizontalAlignment="Left" Height="25" Margin="500,80,0,0" TextWrapping="Wrap" Text="Address  " VerticalAlignment="Top" Width="250" AutomationProperties.Name="Email"/>
            <TextBox x:Name="Tbx_PLZOrt" HorizontalAlignment="Left" Height="25" Margin="500,110,0,0" TextWrapping="Wrap" Text="PLZ Ort" VerticalAlignment="Top" Width="250" AutomationProperties.Name="Email"/>
            <TextBox x:Name="Tbx_Person" HorizontalAlignment="Left" Height="25" Margin="500,140,0,0" TextWrapping="Wrap" Text="Person" VerticalAlignment="Top" Width="250" AutomationProperties.Name="Email" MouseDoubleClick="Tbx_Person_MouseDoubleClick"/>

            <Label x:Name ="Lbl_Email" Content="E-mail" HorizontalAlignment="Left" Height="25" Margin="20,50,0,0" VerticalAlignment="Top" Width="75"/>
            <Label x:Name ="Lbl_Position" Content="Position" HorizontalAlignment="Left" Height="25" Margin="20,80,0,0" VerticalAlignment="Top" Width="75"/>
            <Label x:Name ="Lbl_CompanyName" Content="Company Name" HorizontalAlignment="Left" Height="25" Margin="375,50,0,0" VerticalAlignment="Top" Width="100"/>
            <Label x:Name ="Lbl_Address" Content="Address" HorizontalAlignment="Left" Height="25" Margin="375,80,0,0" VerticalAlignment="Top" Width="100"/>
            <Label x:Name ="Lbl_PLZOrt" Content="PLZ Ort" HorizontalAlignment="Left" Height="25" Margin="375,110,0,0" VerticalAlignment="Top" Width="100"/>
            <Label x:Name ="Lbl_Person" Content="Person" HorizontalAlignment="Left" Height="25" Margin="375,140,0,0" VerticalAlignment="Top" Width="50"/>
            <Button x:Name ="BtnSE" HorizontalAlignment="Left" Height="40" Margin="25,110,0,0" VerticalAlignment="Top" Width="85" Click="BtnSE_Click">
                <TextBlock x:Name="BtnSECaption" Text="Send Email" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="8"/>
            </Button>
            <Button x:Name ="BtnCB" HorizontalAlignment="Left" Height="40" Margin="145,110,0,0" VerticalAlignment="Top" Width="85" Click="BtnCB_Click">
                <TextBlock x:Name="BtnCBCaption" Text="Create Bewerbung Anschrieben" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="8"/>
            </Button>
            <Button x:Name ="BtnFC" HorizontalAlignment="Left" Height="40" Margin="265,110,0,0" VerticalAlignment="Top" Width="85" Click="BtnFC_Click">
                <TextBlock x:Name="BtnFCCaption" Text="Form Clear" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="8"/>
            </Button>
            <TextBlock x:Name="Tbl_Message" HorizontalAlignment="Left" Height="175" Margin="25,200,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="725" ScrollViewer.VerticalScrollBarVisibility="Auto" >
                <TextBlock Text="Sehr"/> <TextBlock Text="{Binding Isman, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
                <TextBlock Text="{Binding ElementName=Tbx_Person, Path=Text, UpdateSourceTrigger=PropertyChanged}"/>

                <TextBlock Text=","/><LineBreak/>
                <TextBlock Text="anbei erhalten Sie meine Bewerbung für die von Ihnen ausgeschriebene Stelle als "/>
                <TextBlock Text="{Binding ElementName=Tbx_Position, Path=Text, UpdateSourceTrigger=PropertyChanged}"/><TextBlock Text=" ."/><LineBreak/>
                <TextBlock Text="Warum ich genau der richtige Kandidat für diese Stelle bin und warum ich Sie mit meiner langjährigen Berufserfahrung optimal unterstützen kann, entnehmen Sie bitte meinen ausführlichen Bewerbungsunterlagen." TextWrapping="Wrap"/><LineBreak/>
                <TextBlock Text="Ich freue mich darauf, Sie in einem persönlichen Vorstellungsgespräch kennenzulernen." TextWrapping="Wrap"/><LineBreak/>
                <TextBlock Text="Mit freundlichen Grussen," TextWrapping="Wrap"/><LineBreak/>
                <TextBlock Text="Andrei Filatov" TextWrapping="Wrap"/><LineBreak/><LineBreak/>
                <TextBlock Text="E-mail: andrew_filatoff@mail.ru" TextWrapping="Wrap"/><LineBreak/>
                <TextBlock Text="Tel: +41-76-273-43-39" TextWrapping="Wrap"/><LineBreak/>

            </TextBlock>
            <DataGrid x:Name="Dgr_Archive" HorizontalAlignment="Left" Height="215" Margin="25,375,0,0" VerticalAlignment="Top" Width="725"
                      ItemsSource="{Binding}"  AutoGenerateColumns="False" >
                <DataGrid.DataContext>
                    <XmlDataProvider Source="C:\Users\1\source\repos\TestWPF\TestWPF\Archive.xml" XPath="/Companies/Company" />
                </DataGrid.DataContext>

                <DataGrid.Columns >
                    <DataGridTextColumn Width="25" Header="Position" Binding="{Binding XPath=@id}"/>
                    <DataGridTextColumn Width="116" Header="Position" Binding="{Binding XPath=@name}"/>
                    <DataGridTextColumn Width="116" Header="Position" Binding="{Binding XPath=Position}"/>
                    <DataGridTextColumn Width="116" Header="Address" Binding="{Binding XPath=Address}"/>
                    <DataGridTextColumn Width="116" Header="E-mail" Binding="{Binding XPath=E_mail}"/>
                    <DataGridTextColumn Width="116" Header="Contact Person" Binding="{Binding XPath=Contact_person}"/>
                    <DataGridTextColumn Width="117" Header="Record_Timestamp" Binding="{Binding XPath=Record_Timestamp}"/>

                </DataGrid.Columns>
            </DataGrid>
            <CheckBox x:Name="Chb_IM" Content="IsMan" HorizontalAlignment="Left" Margin="425,145,0,0" VerticalAlignment="Top" Checked="Chb_IM_Checked" Unchecked="Chb_IM_Unchecked"/>

        </Grid>
    </Window>

Код C#
private void Add_record(XDocument doc)
        {
            XElement n = doc.Root.LastNode as XElement;
            Int32.TryParse(n.Attribute("id").Value, out int LastElementID);

            doc.Root.Add(new XElement("Company",
                       new XElement("Position", Tbx_Position.Text),
                       new XElement("Address", Tbx_Address.Text + "  " + Tbx_PLZOrt.Text),
                       new XElement("E_mail", Tbx_Email.Text),
                       new XElement("Contact_person", Tbx_Person.Text),
                       new XElement("Record_Timestamp", DateTime.Now.ToString()),
                       new XAttribute("name", Tbx_Company_Name.Text.Replace(" ", "_")),
                       new XAttribute("id", (LastElementID + 1))));
            doc.Save(archpath);

        }


text:
Q: running an if statement within a foreach PDO When I added the if statement that compares the value of times stored in a table with current time, PHP will throw an error. Could not find solution anywhere. Your help is appreciated. here is the code:
<?php
//All database times that are 1 hour before stating will be locked in browser not able to reserve any more
$currtime= date("h:i");

foreach ($pdo->query($sql) as $row ) {
    echo '
';
    if ( $row['time']-$currtime=<-1) {
        echo ''.$row['time']='passed'.'	'
    };
    else {
        echo ''. $row['time'] . '	';
    }
    //the following part is just so you know what follows in my code within the loop

    if($row[$selected_day]=='available') {
        echo ''. 'available';
    } else {
        echo ''. $row[$selected_day] . '	';
    }
}
?>

A: @ Sougata Bose, Thanks man, that misplaced ; after the ending brace was the cause of the page not loading together with that equal sign. Now everything works just fine. Thanks.
The following code just worked fine for me:
<?php
//All database times that are 1 hour before stating will be locked in browser not able to reserve any more
$currtime= date("h:i");

foreach ($pdo->query($sql) as $row ) {
    echo '
';
    if ( $row['time']-$currtime<=-1) {
        echo ''.$row['time']='passed'.'	'
    ;}
    else {
        echo ''. $row['time'] . '	';
    }
    //the following part is just so you know what follows in my code within the loop

    if($row[$selected_day]=='available') {
        echo ''. 'available';
    } else {
        echo ''. $row[$selected_day] . '	';
    }
}
?>


text:
Q: Split batch of messages to be sent to Azure Service Bus Let's say I have a collection List<BrokeredMessage> of messages that I want to batch-send to Azure Service Bus.
The collection size is arbitrary, so the total size of all messages combined might be over the limit of 256k imposed by Service Bus. How do I split it into smaller chunks that will go through, in the optimal way?
This task seems to be simple, but it appears to be not: the size of each BrokeredMessage is unknown before I try to send it. Size property returns just the size of message body, without headers and other overhead.
If I try to send 1000 messages with body of 250 bytes each, I'll get MessageSizeExceededException. The catch is that now I can't even retry, because messages were already consumed, so I'd have to re-create all the BrokeredMessage's.
So the only way I see for now is to be very conservative about the batch size when lots of small messages are sent, which will probably cost me some throughput.
Are there more reliable and/or clean ways?

A:
So the only way I see for now is to be very conservative about the batch size when lots of small messages are sent, which will probably cost me some throughput.

It will cost not just throughput, but also reliability. When MessageSender.SendBatchAsync() is used, all messages are sent as an atomic operation and either succeed or fail together.

Are there more reliable and/or clean ways

Using TransactionScope to wrap all of the sends would and achieve the same effect, but you won't be sending messages as a batch anymore.
If you still want to send batches and ensure that you don't into size/count problems, just like suggested you could chunk your sends. Unfortunately, the Size property is a no go for size estimates. It reports body before serialization. Unless use Stream and then serialization is not applied. And event then, still your size will be skewed by the standard and custom properties. When documentation for the WindowsAzure.ServiceBus was re-arranged, the following remark got lost from MSDN API documentation for BrokeredMessage:

To get an accurate value for the size of a BrokeredMessage, you should read the Size property after completing the Send/Receive operation on the BrokeredMessage.

I've took an approach of chunking based on estimated size. Estimated size is based on a certain padding percentage to inflate size of the message in anticipation that on average a message will be smaller than padded size. Plus and average assumed size for string based properties. In this blog post I've laid out the idea behind estimating a single message size to be used to calculate a chunk size that could go out as a batch.

A: To complete Sean answer, Paolo Salvatori wrote some extensions methods for the MessageSender Class, you can find it here:

*

*MessageSenderExtensions.cs
Basically, it is gonna iterate through all your messages and batch them so the size won't exceed the max batch size.
I ran into some issues because the BrokeredMessage.Size does not take in account the Properties of the BrokerMessage. I modified his version a little bit to add the Properties size:
/// <summary>
/// This class contains extensions methods for the <see cref="MessageSender"/> class.
/// </summary>
public static class MessageSenderExtensions
{
    private const string BrokeredMessageListCannotBeNullOrEmpty = "The brokeredMessageEnumerable parameter cannot be null or empty.";
    private const string SendPartitionedBatchFormat = "[MessageSender.SendPartitionedBatch] Batch Sent: BatchSizeInBytes=[{0}] MessageCount=[{1}]";
    private const string SendPartitionedBatchAsyncFormat = "[MessageSender.SendPartitionedBatchAsync] Batch Sent: BatchSizeInBytes=[{0}] MessageCount=[{1}]";
    private const int MaxBathSizeInBytes = 262144;

    /// <summary>
    /// Sends a set of brokered messages (for batch processing).
    /// If the batch size is greater than the maximum batch size,
    /// the method partitions the original batch into multiple batches,
    /// each smaller in size than the maximum batch size.
    /// </summary>
    /// <param name="messageSender">The current <see cref="MessageSender"/> object.</param>
    /// <param name="messages">The collection of brokered messages to send.</param>
    /// <param name="trace">true to cause a message to be written; otherwise, false.</param>
    /// <returns>The asynchronous operation.</returns>
    public async static Task SendPartitionedBatchAsync(this MessageSender messageSender, IEnumerable<BrokeredMessage> messages, bool trace = false)
    {
        var brokeredMessageList = messages as IList<BrokeredMessage> ?? messages.ToList();
        if (messages == null || !brokeredMessageList.Any())
        {
            throw new ArgumentNullException(BrokeredMessageListCannotBeNullOrEmpty);
        }

        var batchList = new List<BrokeredMessage>();
        long batchSize = 0;

        foreach (var brokeredMessage in brokeredMessageList)
        {
            // Hack because the size of the brokered message does not take into account the size of the properties
            var messageSize = GetObjectSize(brokeredMessage.Properties) + brokeredMessage.Size;
            if ((batchSize + messageSize) > MaxBathSizeInBytes)
            {
                // Send current batch
                await messageSender.SendBatchAsync(batchList);
                Trace.WriteLineIf(trace, string.Format(SendPartitionedBatchAsyncFormat, batchSize, batchList.Count));

                // Initialize a new batch
                batchList = new List<BrokeredMessage> { brokeredMessage };
                batchSize = messageSize;
            }
            else
            {
                // Add the BrokeredMessage to the current batch
                batchList.Add(brokeredMessage);
                batchSize += messageSize;
            }
        }

        // The final batch is sent outside of the loop
        await messageSender.SendBatchAsync(batchList);
        Trace.WriteLineIf(trace, string.Format(SendPartitionedBatchAsyncFormat, batchSize, batchList.Count));
    }

    /// <summary>
    /// Calculates the lenght in bytes of an object and returns the size.
    /// </summary>
    private static int GetObjectSize(object objectToTest)
    {
        var bf = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            bf.Serialize(ms, objectToTest);
            return ms.ToArray().Length;
        }
    }
}

A: In the current library, the ServiceBusMessageBatch class has a method which allow you to see if adding a message will exceed the batch size, allowing you to write something like this...
public async Task SendBatchAsync<T>(ServiceBusSender sender, IEnumerable<ServiceBusMessage> messages)
{
    // Don't use using - we want to explicitly control batch lifecycle
    var batch = await sender.CreateMessageBatchAsync();

    foreach (var message in messages)
    {
        if (!batch.TryAddMessage(message))
        {
            // Batch is full, so send this batch
            await sender.SendMessagesAsync(batch);
            batch.Dispose();

            // And create a new batch starting with this message
            batch = await sender.CreateMessageBatchAsync();
            batch.TryAddMessage(message);
        }
    }

    // Send the final batch
    await sender.SendMessagesAsync(batch);
    batch.Dispose();
}


text:
Q: Zikula 1.3.9 News module not accepting google async script I am using Zikula 1.3.9 but cannot get async Google ad script to work on News module. The script appears on screen as in HTML.

A: Any script tags inside user content is blocked by default to prevent XSS attacks.
You have at least two options:

*

*Add your ad script to the News template file instead of the content.

*Allow script tags in the security center (only if you trust all your editors).


text:
Q: Importing Matlab object in Matlab Level 2 S-function in Simulink I was wondering if it is possible to import an object in a Matlab Level-2 S-function within Simulink.
In the past, I have applied reinforcement learning to dynamic models in Matlab. As a result, I have created some classes that deal with the generation and update of the policy. Now, I need to move to Simulink because I have a more complex dynamic system. I am familiar with C S-functions, but because I already have the Matlab code in two classes I was thinking about using a Matlab S-function that uses these objects.
My work flow is as follows: the main Matlab function where policy object is initialized calls the Simulink file with the dynamic model. In the S-function, the policy object is call to select an action (which is the output of the control system). The policy object (in fact its weights) is then updated in the main Matlab function after a number of simulations of the Simulink file.
So, what I would need is a way to import the policy object in a Matlab S-function in Simulink. I have tried to import it as parameter, but only numeric values are accepted. I cannot keep the object only within the S-function (hence, initialising it within the initialisation function) because I need to update its weights in the main Matlab script.
Is this possible? Any suggestions would be greatly appreciated!
An example of the policy class is as follows:
classdef Policy
    %% Accessible properties:
    properties
        a;                  % selected action index
        actions;            % actions list
        basis;              % type of basis function
        centres;            % list of centres of the RBFs
        exploration_rate;   % exploration rate
        mu;                 % width of each RBF
        nbasis;             % no. basis functions overall
        states;             % list of discrete states
        weights;            % weights of the linear function approximation
    end

    %% Protected properties:
    properties (Access = protected)
        na;                 % no. actions
        ns;                 % no. discrete states
        nrbf;               % no. radial basis functions per action
        state;              % current state
        Q;                  % Q value for each action-state pair
    end

    %% Accessible methods:
    methods %(Access = protected)
        %% Initialization function:
        function obj = Policy(actions,states,epsilon,basis,mu)
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            % Input:
            % actions: actions list
            % states:  states list or centres of the RBFs
            % epsilon: initial exploration rate
            % delta:   discount factor
            % basis:   type of basis functions
            % mu:      width of each RBF
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            if nargin<4
                basis = 'basis_exact';
            end

            obj.actions = actions;
            obj.states = states;
            obj.exploration_rate = epsilon;

            switch basis
                case 'basis_exact'
                    obj.basis = basis;
                    obj.states = states;
                    obj.ns = size(states,1);
                case 'basis_rbf'
                    obj.basis = basis;
                    obj.centres = states;
                    obj.mu = mu;
                    obj.nrbf = size(states,1);
                otherwise
                    error(['Only exact and radial basis functions',...
                    'supported']);
            end
        end

        %% Setter function for the features' weights:
        function obj = set_weights(obj,weights)
            obj.weights = weights;
        end

        %% Update the exploration rate with the given rate:
        function obj = update_epsilon(obj,rate)
            obj.exploration_rate = obj.exploration_rate*rate;
        end

        %% Select an action:
        function obj = select_action(obj,state)
            % Store the current state:
            obj.state = state;
            % Compute the state-action values for the current state:
            obj = obj.qvalues();
            % Get the current action with an epsilon-greedy policy:
            obj.a = obj.eGreedy();
        end

        %% Evaluate the features:
        function phi = get_features(obj,state,action)
            % Store the current state:
            obj.state = state;
            % Get the features:
            phi = feval(obj.basis,action);
        end
    end

    %% Protected methods:
    methods (Access=protected)
        %% Find the discrete state:
        function s = discretizeState(obj,x)
            % Copy the row vector entries (continuous states) to all rows:
            x = repmat(x,obj.ns,1);
            % Select the row using the minimum Eucledian distance:
            [~,s] = min(sum((obj.states-x).^2,2).^0.5);
        end

        %% Get the Q-value function for current state and action:
        function q = qvalue(obj,action)
            phi = feval(obj.basis,action);
            q = phi' * obj.weights;
        end

        %% Get the Q-value functions for the current state:
        function obj = qvalues(obj)
            % Initialize the Q-values for the current state:
            obj.Q = zeros(obj.na,1);
            % Calculate the state-action values for the current state:
            for a=1:obj.na
                obj.Q(a) = obj.qvalue(a);
            end
        end

        %% Get an action with an epsilon-greedy exploration policy:
        function a = eGreedy(obj)
            % Generate a random number:
            r = rand;

            % Select the action that maximises Q(s)
            if (r>obj.exploration_rate)
                [~,a] = max(obj.Q); % value, action
            % Choose a random action:
            else
                a = randi(obj.na);  % random integer based on a uniform
            end                     % distribution
        end

        %% Find the features for the exact basis functions:
        function phi = basis_exact(obj,action)
            %Initialize the features:
            phi = zeros(obj.nbasis,1);

            % Find the current discrete state:
            s = discretizeState(obj.state);

            % Find the starting position of the block:
            base = (action-1) * obj.ns;

            % Set the indicator:
            phi(base+s) = 1;
        end

        %% Find the features for the radial basis functions:
        function phi = basis_rbf(obj, action)
            %Initialize the features:
            phi = zeros(obj.nbasis,1);

            % Find the starting position:
            base = (action-1) * (obj.nbasis/obj.na);
            % This is because the matrix Theta is converted into a line
            % vector

            % Compute the RBFs:
            for i=1:obj.nrbf
                phi(base+i) = exp(-norm(obj.state-obj.centres(i,:))^2/...
                    (2*obj.mu));
            end
            % ... and the constant:
            phi(base+obj.nrbf+1) = 1;
        end
    end
end

A: Ok, after some trials, I have finally found that the best way is actually to use global variables, i.e. to set the object as global in both the main Matlab script and the Level 2 S-function.
Here you can find a quick example, which I hope will help you save a day of work.
Test.m class:
classdef Test
    properties
        a;
        b;
    end

    methods
        function obj = Test(a,b)
            obj.a = a;
            obj.b = b;
        end

        function obj = change_a(obj,c)
            obj.a = obj.a + c;
        end

        function c = get_c(obj)
            c = obj.a*obj.b;
        end
    end
end

Main Matlab script - trial.m:
clear;
close all;

global test;

test = Test(0,1);

% Simulink file:
sfile = 't1';
% Load the Simulink file:
load_system(sfile);

% Run the simulation:
sout = sim(sfile,'StopTime','5.0');

% Plot data:
t = sout.tout;
c = sout.get('logsout').getElement('c').Values.Data;
figure;
plot(t,c);

t1.slx Simulink file:

test_class.m level 2 Matlab S-function:
function test_class(block)
% rl_control.m      e.anderlini@ucl.ac.uk     23/10/2017
    setup(block);
end

%% Set up the block:
function setup(block)
%   % Register number of dialog parameters:
%   block.NumDialogPrms = 3;

    % Register number of input and output ports:
    block.NumInputPorts  = 1;
    block.NumOutputPorts = 1;

    % Set up functional port properties to dynamically inherited:
    block.SetPreCompInpPortInfoToDynamic;
    block.SetPreCompOutPortInfoToDynamic;

    % Set up the input ports:
    block.InputPort(1).Dimensions        = 1;
    block.InputPort(1).DirectFeedthrough = true;

    % Set up the output port:
    block.OutputPort(1).Dimensions       = 1;

    % Set block sample time to continuous:
    block.SampleTimes = [0 0];

%     % Setup Dwork:
%     block.NumContStates = 1;

    % Set the block simStateCompliance to default:
    block.SimStateCompliance = 'DefaultSimState';

    % Register methods:
%     block.RegBlockMethod('InitializeConditions',    @InitConditions);
    block.RegBlockMethod('Outputs',                 @Output);
%     block.RegBlockMethod('Derivatives',             @Derivative);
end

% %% Initial conditions:
% function InitConditions(block)
%     % Initialize Dwork:
%     block.ContStates.Data = block.DialogPrm(3).Data;
% end

%% Set up the output:
function Output(block)
    global test;
    test = test.change_a(block.InputPort(1).Data);
    c = test.get_c();
    block.OutputPort(1).Data = c;
end

I have tested it and checked that it works. The global variable allows me to use the same object and change it as I wish.


text:
Q: How to set source address when sending using and UDP socket I've two pc using VRRP for redundancy. So every PC (Linux) has a physical and a Virtual IP address.
I've a software (C++) with a client/server architecture with UDP protocol. The software bind the listen socket on "0.0.0.0" and use a new socket every time it needs to send some data to the other party. With wireshark I saw that when it sends data the source IP is the phisycal one...
How can I set the source address of the sending socket to the Virtual one??
NOTE: Whit ifconfig I see only eth0 with the physical address...

A: When the kernel needs to send something through a socket it performs these steps

*

*if the socket is bound, use that source address

*is the socket is not bound, it looks around for interfaces and selects a source address

So you need to bind(2) your socket to your desired address. For more information: "Source Address Selection" in chapter "IP Routing" of "Guide to IP Layer Network Administration with Linux".

A: i'm not sure i understand entirely your question, but in terms of writing C/C++ code on linux at low level, you can import the ip.h header from the linux kernel headers which gives you access to the low level IP packet structure. (UDP works on top of IP)
#include <linux/ip.h>

and then look at struct iphdr which is the header for every IP packet sent and that contains a saddr member which you can set programmatically to be the source address.


text:
Q: Can the product of three complex numbers ever be real? Say I have three numbers, $a,b,c\in\mathbb C$. I know that if $a$ were complex, for $abc$ to be real, $bc=\overline a$. Is it possible for $b,c$ to both be complex, or is it only possible for one to be, the other being a scalar?

A: Your problem is presumably that you are approaching the problem as:

*

*Think of non-real values for $a$, $b$, and $c$. Hope that $abc$ is real.

A much easier way to deal with the problem is

*

*Think of non-real values for $a$, $b$, and think of a real value for $abc$. Hope that $c$ is non-real.

(Note: I assume the form of the problem above is what the OP actually intends to ask)

A: It is definitely, entirely possible.
$$a=i\qquad b=c=1+i\qquad abc=-2$$
This example demonstrates that $bc$ doesn't even have to be $a^*$, merely that the sum of their arguments is a multiple of $\pi$.

A: For example $z^3=1$, where $z\neq1.$
Id est, $$a=b=c=-\frac{1}{2}+\frac{\sqrt3}{2}i.$$

A: I'm not sure I understood your question, but I suppose that the equality$$i\times(1+i)\times(1+i)=-2$$answers it.

A: If you represent a complex number using polar coordinates (angle and a distance from zero), it is known that multiplying the numbers in this trigonometric form is way easier than in the algebraic form - you simply multiply the distance and add the angles:
$$z_1=r_1(\cos(ϕ_1)+i\sin(ϕ_1))$$
$$z_2=r_2(\cos(ϕ_2)+i\sin(ϕ_2))$$
$$z_1z_2=r_1r_2(\cos(ϕ_1+ϕ_2)+i\sin(ϕ_1+ϕ_2))$$
Once you are accustomed to this, the rest is simple. If $ϕ$ is parallel with the x axis (0 or 180°, $\sin ϕ=0$), the number is real, and so your only task is to find three angles that add up to 0 (mod 180°). There is an infinite number of them.

A: Let the numbers be of the form $r_1 \exp(i t_1)$.  Then the product is $r_1 r_2 r_3 \exp (i(t_1+t_2+t_3))$.  The imaginary part of this is $\sin(t_1+t_2+t_3)$.  So any set of $t$'s where this is zero will do the trick.  For example, $t_1+t_2+t_3 = 0$.  You can generalize this proof to any number of complex numbers, not just three.

A: If you represent complex numbers as vectors on the complex plane, then multiplication of two complex numbers produces a result whose angle is the sum of the two multiplicand angles.
It's trivial to note that for one vector with any arbitrary angle, multiplication by another vector with the negative of that angle will produce a result on the real line.

A: Another approach: suppose $a, b$ are complex and not real and $ab$ isn't real. Then let $c=\overline{ab}$.
Note that in a precise sense this is universal: if $abc$ is real (and each is nonzero), then $c$ is a real multiple of $\overline{ab}$.

A: I think the easiest example to come up with is $e^{2i\pi/3}$,
$$e^{2i\pi/3}\cdot e^{2i\pi/3}\cdot e^{2i\pi/3} = e^{2i\pi}=1.$$

A: Polar coordinates.
$a=e^{i\alpha}$, $b= e^{i\beta}$, $c=e^{-i(\alpha+\beta)}$.
Then $abc = e^0=1.$

A: Algebraic approach:
Let the three complex numbers by $z_1=a+bi,z_2=c+di,z_3=e+fi$. Then $$\begin{align}(a+bi)(c+di)(e+fi)&=((ac-bd)+(ad+bc)i)(e+fi)\\&=[e(ac-bd)-f(ad+bc)]+[e(ad+bc)+f(ac-bd)]i\end{align}$$ so for the product to be real we have $$e(ad+bc)+f(ac-bd)=0\implies ac-bd=-\frac{e(ad+bc)}f$$ giving $$(a+bi)(c+di)(e+fi)=-\frac{e^2(ad+bc)}f-f(ad+bc)=-\frac{ad+bc}f(e^2+f^2)$$
So any three complex numbers $z_1,z_2,z_3$ satisfying $$\Re(z_3)(\Re(z_1)\Im(z_2)+\Im(z_1)\Re(z_2))+\Im(z_3)(\Re(z_1)\Re(z_2)-\Im(z_1)\Im(z_2))=0$$ will do. Hence there are infinitely many trios whose product is real.

A: First, $(x + iy) \times (x - iy) = x^2 - i^2 y^2 = x^2 + y^2$ is real.
So you can take any complex numbers $a, b$ where the product $ab$ is not real, write $ab = (x + iy)$, and choose $c = (x - iy)$, or choose $c = t(x - iy)$ for any real $t ≠ 0$, and the product $abc$ is real.

A: Break down the argument into two parts:

*

*Find two complex numbers which when multiplied give you a complex
number

*Find a third complex number which when multiplied with
result from (1) gives a real.

It will be easy to digest.

A: There are lots of what I would call trivial or near trivial answers, those that include only real numbers or include duplicates.
The intention of the problem seems to me that what is sought are distinct and having non-zero complex part.
For motivation, note that multiplication by a complex on the unit circle is like rotating by or adding the angle of it.
For the first part, distinct, any full set of roots of unity will work. For 3,
$$e^{0} \cdot e^{i 2\pi/3} \cdot e^{i 4\pi/3} = e^{i(0+2+4))\pi/3} = e^{i 6\pi/3} = e^{i 2\pi} = 1$$
Or in explicit complex notation,
$$1 \cdot (-1 + i \sqrt{3})/2 \cdot (-1 - i \sqrt{3})/2 = 1 + i 0$$
(this works for all angles plus $2\pi k$).
Again, because multiplication by a complex (on the unit circle) is like rotating or adding by an angle, we can take any distinct triple (like the one above), and adjust a bit so that none are on the real line. Rotating the first by $\pi/6$ and the last back by the same, we get:
$$e^{i \pi/6} \cdot e^{i 2\pi/3} \cdot e^{i 7pi/6} = e^{i(1+4+7)\pi/6} = e^{i 12\pi/6} = e^{i 2\pi} = 1$$
or
$$(\sqrt{3} + i)/2 \cdot (- 1 + i\sqrt{3})/2 \cdot (- \sqrt{3} - i)/2 = 1$$
This is only one example. The entire space of solutions is, for any number of multiplicands on the unit circle, the set of angles that sum to $2\pi k$.

A: It's exceedingly easy to generate any number of complex numbers that satisfy this property. By starting with an arbitrary complex number and generating a new one by swapping the magnitudes of the real and imaginary parts, we can generate pairs of complex numbers that when multiplied together will always produce an imaginary number, either positive or negative.
$$(x+iy)(y+ix)=xy+x^2i+y^2i+xyi^2=(x^2+y^2)i$$
$$(x+iy)(-y-ix)=-xy-x^2-y^2i+xyi^2=(-x^2-y^2)i$$
We can find two such pairs:
$$(1+i)(-1-i)=-1-i-i-i^2=-2i$$
$$(1+2i)(2+i)=2+i+4i+2i^2=5i$$
When multiplied together, they will give $-2i\times5i=10$. This result will always be real because both numbers are imaginary with no real part.
Now take one complex number from each of the original pairs and multiply them together:
$$(1+i)(1+2i)=1+2i+i+2i^2=-1+3i$$
Using this result with the remaining numbers gives:
$$(-1+3i)(-1-i)(2+i)$$
$$=(1+i-3i-3i^2)(2+i)$$
$$=(4-2i)(2+i)$$
$$=8+4i-4i-2i^2$$
$$=10$$
I have now demonstrated that three seemingly unrelated complex numbers: $-1+3i$; $-1-i$; & $2+i$, all with non-zero real and imaginary parts (i.e. not counting imaginary numbers as complex numbers), and all with integer magnitudes, can be multiplied together to produce a real number. You can repeat this process with any starting numbers you feel like to generate more triples that satisfy this condition.


text:
Q: Bounds on the Euler Toitent function While reading I came across a fact that : $$\sqrt{n}/2 ≤ φ(n) ≤ n$$ The upper bound is obvious but how to prove the lower bound on the totient function ?
Thanks

A: In fact you can improve the lower bound to $\sqrt{n/2}$. Consider
$$\frac{\varphi(n)}n=\prod_k\frac{p_k-1}{p_k}\;,$$
where the $p_k$ are the distinct prime factors of $n$. We also have
$$\frac1{\sqrt n}\le\prod_k\frac1{\sqrt{p_k}}\;.$$
For all primes $p$ we have
$$
\frac{p-1}p\ge\frac1{\sqrt{2p}}\;,
$$
with equality only for $p=2$. The lower bound follows.


text:
Q: Java File.listFiles() returns files that do 'not exist' according to `exists()` I noticed this problem in our productive code:
java.lang.IllegalArgumentException: /somePath/�.png does not exist
    at org.apache.commons.io.FileUtils.sizeOf(FileUtils.java:2413)
    at org.apache.commons.io.FileUtils.sizeOfDirectory(FileUtils.java:2479)

The underlying cause is this:
import java.io.File;

public class FileNameTest
{

    public static void main(String[] args)
    {
        File[] files = new File("/somePath").listFiles();
        for (File file : files)
        {
            System.out.println(file + " - " + (file.exists() ? "exists" : "missing!!"));
        }
    }

}

Output:
0.png - exists
7.png - exists
4.png - exists
8.png - exists
1.png - exists
3.png - exists
�.png - missing!!
2.png - exists
5.png - exists
�.png - missing!!
6.png - exists
d.png - exists
$.png - exists
s.png - exists
+.png - exists
9.png - exists

The "missing" files are named with the symbols "µ" (Mu) and "€" (Euro).
It also seems to be the case that these filename use the wrong encoding.
When i list the files in bash they show up wrong as well.
When i convert the output of ls from latin1 to UTF-8 they appear correctly (at least mu).
But nevertheless ...

*

*these files exist

*file.listFiles() lists them

*for the 2 special cases: file.exists() returns false

I believe this is a bug in the JVM. Can anybody confirm this?
Is there already a bug-report? Any ideas how to fix this? (Renaming the files is not an option as they are user generated and might re-appear in any form or shape.)
My System:

*

*Ubuntu 4.2.0

*java version "1.8.0_102"

*Java(TM) SE Runtime Environment (build 1.8.0_102-b14)

*Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

*Apache Commons IO 2.4

A: It is not a bug, it is a consequence of missing encoding information in the filesystem.
Java has no way of representing the file name correctly, because it does not know the encoding. Therefore the file is inaccessible from Java without specifying the correct encoding.
The simplest way to solve this is to set the file.encoding property correctly, and use that encoding in all your file names.
EDIT: i found an article that shows another possible behaviour, maybe changing the file.encoding does not help. Better test it if you want to use something else than UTF-8 . http://jonisalonen.com/2012/java-and-file-names-with-invalid-characters/
i also found maybe a relevant discussion: Setting file name encoding

A: No solution, but how to detect those files without File#exists.
The file name stems from a file name on disk with a wrong encoding (instead of UTF-8). It gives a Unicode placehold U+FFFC � instead of the wrong byte.
You might assume that nobody will name hishers file name with an U+FFFC. So:
String name = file.getName();
if (name.contains("\uFFFC")) {
    String namePattern := name.replace(".", "\\.").replace("\uFFFC", ".");
    ... file is problematic
}

In every case you probably have to correct the file calling ProcessBuilder with a pattern rename.

It just might be that reading the directory as file with encoding CP1252 (Windows Latin-1) just might get the correct file name.

Or who knows, the new Files & Path methods like directory walks might show some improvement. Which I doubt. Though a charset converter could do give the offending byte.


text:
Q: How do I play a sound when the screen is locked on Android in React Native? I have a simple app that upon render plays a sound after a few seconds.
Everything works except that if I lock the screen, the app will not play the sound until I unlock it again.
Here is a simplified version of what I'm working with:
import React, { Component, PropTypes } from 'react';
import { View, Text } from 'react-native';

import Sound from 'react-native-sound'; //for the bell sound

class SoundTest extends Component {

  componenWillMount(){
    setTimeout(this.playSound(), 5000);
  }

  playSound() {
      let s = new Sound('bell.wav','', (e) => {
        if (e) {
          console.log('error', e);
        } else {
          console.log('duration', s.getDuration());
          s.play();
        }
      });
  }

  render() {
    return (
      <View>
        <Text>Hear some sound after a few!</Text>
      </View>
    )
  }
}

AppRegistry.registerComponent('SoundTest', () => SoundTest);

// Works great if the screen is on / not locked

Is there some way to play the sound regardless of whether the screen is locked or not?


text:
Q: Cannot see buttons in Lua I have added a logo and few buttons, such as PLAY and CREDITS.  I do not receive any errors and I'm having a hard time seeing the problem, what am I missing?
--Background
local bg = display.newImage("background.png")
--Buttons
local title
local playBtn
local creditsBtn

--Functions
local Main=('')
local startButtonListeners=('')

--Start of Functions
function Main()
title= display.newImage("logo.png")
playBtn= display.newImage("playbtn.png", 130, 248)
creditsBtn= display.newImage("creditsbtn.png", 125, 316)
titleView= display.newGroup(title, playBtn, creditsBtn)

startButtonListeners("add")
end

A: If that is your code in its entirety, you never called your main function, and in corona, you don't have to call a main function, main.lua is run at the beginning of your project. So try running your code like this
--Background
local bg = display.newImage("background.png")
--Buttons
local title
local playBtn
local creditsBtn

--Functions
local Main
local startButtonListeners, anotherButtonListener

--Start of Functions
Main = function()
   title= display.newImage("logo.png")
   playBtn= display.newImage("playbtn.png", 130, 248)
   creditsBtn= display.newImage("creditsbtn.png", 125, 316)
   titleView= display.newGroup()
   titleView:insert(title)
   titleView:insert(playBtn)
   titleView:insert(creditsBtn)

   playBtn:addEventListener("tap", startButtonListeners)
   --creditsBtn:addEventListener("tap", anotherButtonListener)
end

startButtonListeners = function(event)
   --Do something here
end
anotherButtonListener = function(event)
   --Do something for the credits here
end

Main()  --Remember to actually call Main to make it run

In Lua, there is no declared main function, it just runs everything in a sequence. Remember that you do not need to write a main function like you would in C, but more like Python, it will just run what you write.
EDIT: Why don't you post the errors you get so we can help you better? But scanning the code something definitely got past me. The newGroup line.
Refer above for the edited code.


text:
Q: Play framework 2 : How to pass object between routes, views, and controller? I'm trying to pass a book object from views to routes, and then send it to calculate in a controller. My code is following:
bookList.scala.html
@(books: java.lang.Iterable[Book])

@main("BookList"){

        @for(book <- books.iterator()){

                         ...

Order now!

        }

}

routes
...
GET     /order                      controllers.Application.buy(book: models.Book)
...

However, It gave me an error : No QueryString binder found for type models.Book. Try to implement an implicit QueryStringBindable for this type.
I tried to change the routes as :
    GET     /order                      controllers.Application.buy(book)

It also returned an error :
type mismatch; found : String required: models.Book

A: That's not how Play routing works. The Play router parses variables from the URL or query string, and converts them to native types via the QueryBindable typeclass. You should have something more like this:
routes
GET /order/:bookid           controllers.Application.buy(bookid: String)

And the action should be like:
Application.scala
def buy(bookid: String) = Action { request =>
    // Look up book by id here.
   Ok(views.html.thanks("you bought a book!"))
}

And the template like this:
bookList.scala.html
@for(book <- books.iterator()) {
    ...
    <a href="@routes.Application.buy(book.id)" class="btn btn-primary"
}

Of course if your model's ID is other than String you need to modify the route's param type
Update -- alternative using form/POST
A form with a POST method is a better solution, or the user will buy another book each time they click the URL, and the id will be exposed. Check out the forms documentation. Your template would be like this:
@for(book <- books.iterator()) {
    ...
    <form method="post">

@book.name

      <input type="hidden" value="@book.id"/><button type="submit">buy</button>
    </form>
}

A: You can't simple pass object (bean) as a url query parameter.
Default you can only define simple types as a parameter types. Please read carefully play's rounting documentation -> http://www.playframework.com/documentation/2.2.x/ScalaRouting especially Parameter types
But play framework has possibility to "learn" how to interpret specific url to bean.
You get info about this in error witch you posted. Responsible for this QueryStringBindable -> http://www.playframework.com/documentation/2.2.1/api/java/play/mvc/QueryStringBindable.html
In short like in documentation, when you define class like this:
class Book implements QueryStringBindable<Book> {
     public String title;
     public int numpages;

     public Option<Pager> bind(String key, Map<String, String[]> data) {
         if (data.contains(key + ".title" && data.contains(key + ".numpages") {
             try {
                 title = data.get(key + ".title")[0];
                 numpages = Integer.parseInt(data.get(key + ".numpages")[0]);
                 return Some(this);
             } catch (NumberFormatException e) {
                 return None();
             }
         } else {
             return None();
         }
     }

     public String unbind(String key) {
         return key + ".title=" + title + "&" + key + ".numpages=" + numpages;
     }

     public String javascriptUnbind() {
         return "function(k,v) {\n" +
             "    return encodeURIComponent(k+'.title')+'='+v.title+'&'+encodeURIComponent(k+'.numpages')+'='+v.numpages;\n" +
             "}";
     }
 }

Then you can define route like:
GET  /order     controllers.Application.buy(p: Book)

You can then run in your browser e.g link:
localhost:9000/?p.title=SomeTitle&p.numpages=235

And in buy controller you will get p parameter as a Book class instance.
I did't test this code and this is in java. But you should get the idea.

A: You can define a custom PathBindable to automatically convert an id to a book object and pass it to buy method in controller. See PathBindable, another example
NOTE: I would define the PathBindable in same file as the Book model.

A: Simple example I used to parse in UUID's using PathBindable.
I'd rather not have to parse UUID's and ensure they're well formed in all controller/action code, so I use this at the router level. I used a UUIDP (P for param) to not pollute the UUID namespace.
Case Class and Parser
case class UUIDP(key: String, value: String, uuid: UUID)

object UUIDP {
  implicit def pathBinder(implicit intBinder: PathBindable[String]) = new PathBindable[UUIDP] {

    val uuidRegex = "([0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12})".r

    override def bind(key: String, value: String): Either[String, UUIDP] = {

      value match {
        // sanity check, prevent errors, is this really a UUID?
        case uuidRegex(c) => {
          //error check too, binary value can be invalid
          try { Right(UUIDP(key,value,UUID.fromString(value))) }
          catch {
            case ex : IllegalArgumentException => Left("Unparsable UUID")
          }
        }
        case _ => Left("Invalid UUID Format")
      }
    }

    // in case we need to remove this from the request
    override def unbind(key: String, user: UUIDP): String = {
      intBinder.unbind(key, user.value)
    }
  }
}

conf/routes
GET /items/:id @com.foo.MyController.getItem(id: UUIDP)

Controller
def getItem(sessionId: UUIDP) = Action(parse.text) { request =>
  Ok(s"Fetching item [${sessionId.uuid}]")
}


text:
Q: Why does Windows Explorer halt for a moment whenever I open a folder? I am not sure if it is really Windows Explorer related, but on my Vista Premium every time I open a folder, the system starts doing "something". I can see a sort of green progress indicator in the address bar and during that time the folder is not responding.

I don't have any indexing service running, and my disks are well defragged. I have more than 50% of the disk capacity free. My process explorer doesn't show where the activity is exactly. I don't have any other programs or services running that need to process something on file folders. The system is virus free as well.
This happens on my file folders that contain files on the local disk, nothing is remote, no network files or shared files or anything like that, just regular local files. This behavior is the same for all kinds of file types.
I have the feeling that it is some kind of configuration related issue, but could not pin point the exact config.
Could not find something useful on Microsoft's site.
Has anyone noticed this and could explain it?

A: See this article : How to prevent Windows Vista's 'green ribbon of death'.
It lists 4 reasons for this. Although none of them seems likely in your case, you might still have a look.
I would also suggest that you try this:
Open up Explorer.exe, go to Tools -> Folder Options -> View. Then go to the Advanced Settings and check "Always show icons, never thumbnails."
You might also, just to be sure, do a chkdsk -r.
You can also use Autoruns to see if any funny processes start-up without your knowledge, and you can use Process Monitor to examine the disk activity while the green ribbon is boring you to death.

A: Google for "sysinternals" (free download) and run the programs procmon, filemon and/or regmon. Those will tell you what processes are accessing files and processes, and you may be able to track down a little better what is happening on your system.

A: Windows Vista (and Windows 7) read a folder and its contents every time you open it, or it detects a change. On slower drives (e.g. network, non-indexed), this can take a long time, and you'll see the progress bar.
I don't know how to turn this off - I normally use another file manager where possible. In Windows 7 it's a lot faster, and you can press the stop button at the right of the address bar, but in Vista, this might stop it from listing all the files.