text:
Q: Change Gradle mavenCentral URL to My repo While working with Gradle in my country, download jars from maven central is a very timely-costed work.
I wanna change the mavenCentral to maven-nexus:
which means whenever I use mavenCentral it always points to oschina
------edit------
I have lots of projects with mavenCentral, so I do not want change each file.
Now in new scripts I use maven{ url ...}
Any easy way??
Any one can hlep?
Thanks!

A: Its easy! Instead of this:
repositories {
    mavenCentral()
}

Use this:
repositories {
    maven {
        url "https://..."
    }
}

A: Just set up the repository in build.gradle file in your module's directory, like this:
repositories {
    maven { url "http://maven.oschina.net/content/groups/public" }
}

A: The easiest way to apply this change for all projects is to use an gradle init script that forces the use of the oschina repository instead of mavenCentral. you can put this:
allprojects{
    repositories {
        all { ArtifactRepository repo ->
            println repo.url.toString()
            if ((repo instanceof MavenArtifactRepository) && repo.url.toString().startsWith("https://repo1.maven.org/maven2")) {
                project.logger.warn "Repository ${repo.url} removed. Only $coporateRepoUrl is allowed"
                remove repo
            }
        }
        maven {
            url "http://maven.oschina.net/content/groups/public"
        }
    }
}

into an gradle init file.
Now you can use this by calling "gradle build -I yourInitFile.gradle" or you put this logic into a init.gradle file stored in your gradle home directory in USER_HOME/.gradle/ directory. Now this will be picked up by every gradle invocation without explicitly setting -I
Another option is to create a custom gradle distribution where this file is store in the init.d directory of the distribution.

A: If you have lots of dependencies (i.e. in all build.gradle files) and for repository urls you are using
repositories {
    maven {
        url "https://www.myrepourl.com"
    }
}

but you want to change that url in only one file then do the following:

*

*Create gradle.properties file and there add this line: REPO_URL=https://www.myrepourl.com

*In all other build.gradle files copy the following:
repositories {
    maven {
        url project.REPO_URL
    }
}

You can add & use more properties in this way.
This worked like charm for me. Cheers!


text:
Q: how to restore FlutterError.onError? In my app, I record the flutter onError to crashalytics,
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;

While running the integration test, if some exceptions happens I get the below statement in the console and the test just hangs,

The following exception was thrown running a test: I/flutter (30479):
A test overrode FlutterError.onError but either failed to return it to
its original state, or had unexpected additional errors that it could
not handle. Typically, this is caused by using expect() before
restoring FlutterError.onError.

The above message in console suggests something is wrong with the onError overriding, how do I return FlutterError.onError to its original state as per the recommendation coming up in console.
Please note that I am using the newly recommended way for integration test,

A: This helper function I wrote works for me:

Future<void> restoreFlutterError(Future<void> Function() call) async {
  final originalOnError = FlutterError.onError!;
  await call();
  final overriddenOnError = FlutterError.onError!;

  // restore FlutterError.onError
  FlutterError.onError = (FlutterErrorDetails details) {
    if (overriddenOnError != originalOnError) overriddenOnError(details);
    originalOnError(details);
  };
}

void main(){
  testWidgets("some test", (tester) async {
    await restoreFlutterError(() async {
      app.main();
      await tester.pumpAndSettle();
    });
    // ...
    expect(...);
  });
}

Anything that overrides FlutterError.onError can be wrapped around restoreFlutterError - the function makes sure that both onError handler (your and the one set by the test framework) are called.

A: onError is a public static member of FlutterError, so technically it can be overridden by anyone from anywhere. The testWidgets() function itself overrides the FlutterError.onError with its own error handler as well before running the test body. You can read its source code for more info.
Basically, below is what happened:
testWidgets('', (tester) async { // onError is overridden with the handler of the test framework
  await app.main(); // onError is overridden again with crashlytics error handler
  //...
  expect(); // Flutter yells that you should not have touched its onError
});

The point is the Flutter test framework needs its onError to work properly. So whatever you do, remember to call the error handler of the test framework.
Below is the way I used in my project to "restore" the FlutterError.onError (and do something else):
testWidgets('', (tester) async {
  final originalOnError = FlutterError.onError!;
  FlutterError.onError = (FlutterErrorDetails details) {
    // do something like ignoring an exception
    originalOnError(details); // call test framework's error handler
  };
  // ...
  expect();
});

With some modification, I think your problem is solvable.

A: hmm, Ok.. it seems that we have a couple a issues related to that : link-1, link-2, link-3
Long story short: The integration_test lib seems to be optimized only for "happy paths" for now.
In my case, Firebase was conflicting with integration_test when this line was enabled:
   FirebaseMessaging.onBackgroundMessage(_onBackgroundOrTerminatedHandler);

The error was gone once I've disabled it (when running the integration tests).

A: Try to update to flutter 2.5.0. This seems to be fixed there.
It no longer gets stuck when running the test. So it continues to execute the rest of the tests. Although it still shows the _pendingExceptionDetails != null error

A: I was seeing this error because I forgot to call await tester.pumpAndSettle() after asking the test to tap a button.
This prevented the app from moving to the next screen. When I tried to find a specific TextField, it wasn't visible to the integration test.
The cause of the error in my case had nothing to do with actually needing to restor FlutterError.onError.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento indexes are broken, advanced search can't find all products We have around 20000 products in Magento catalog, most of which are updated by daily from different imports. For some reason Magento suddenly isn't finding all the products it should. For example finding using advanced search and using Brand field with "Brand #1" only 41 products are found though there are over 500 of those.
If I open missing products through admin I see that the correct brand is selected. This can be fixed by changing it to something else, then saving, then changing it back and saving. Product is instantly found through Advanced search.
I've tried reindexing multiple times and from command line, even tried truncating index_* tables and rebuilding the indexes, but still not working.
Does someone has some idea what tables should I get fixed and how in order to get all the products working?
I even tried this:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('*');

foreach ($collection as $_product) {
   echo $_product->getName().":  ";
   echo $_product->getAttributeText('brand')."\n";
}

It only displays correct brand for the products found in advanced search, though others have that selected in admin correctly.


text:
Q: Number of invertible elements in $\mathbb{F}_q[X]/\langle X^p-1\rangle$ with $p=\operatorname{char} \mathbb{F}_q$ I need to find the number of invertible elements in $\mathbb{F}_q[X]/\langle X^p-1\rangle$ with $p=\operatorname{char} \mathbb{F}_q$, which is equal to the number of invertible $p\times p$ circulant matrices over $\mathbb{F}_q$.
If $n$ and $q$ are coprime then the number of $n\times n$ invertible circulant matrices over $\mathbb{F}_q$ is calculated, see here. But what if $n$ and $q$ are not coprime (in particular, $n=p=\operatorname{char}\mathbb{F}_q$)? In this case no extension field of
$\mathbb{F}_p$ contains a primitive $n$-th root of unity.

A: As $X^p-1=(X-1)^p$ in characteristic $p$, then
$\mathbb{F}_q[X]/\langle X^p-1\rangle\cong\mathbb{F}_q[X]/\langle Y^p\rangle$
(set $Y=X-1$). As $Y$ is nilpotent, the invertible elements are
$a_0+a_1Y+\cdots +a_{p-1}Y^{p-1}$ with $a_0\ne0$. There are $(q-1)q^{p-1}$ of them.

A: Hint: We have $X^p-1 = (X-1)^p$ in any field of characteristic $p>0$.
The invertible elements of $F_q[X]/\langle X^p-1\rangle$ are the polynomials (residue classes) $g(X)$ which are relatively prime to $X-1$.


text:
Q: Write to file without zero fill in Linux Let's say that the intent is to create a file with a large hole at the beginning that we will write to later on, on an embedded device running Linux. We open the file, obtain a file descriptor and call lseek on it to seek to a certain, known position. Afterwards, when we want to write to that file at the seeked-to position, we call write on it.
However, on the first write the hole created by seeking gets zero-filled and if the hole is large enough, this operation can take some time. In my application, there is no need for this zero initialization, as the hole is of exact length and I will fill it with my data later.
Is there a way to avoid having the first write call after seek zero-fill the hole (even if it involves modifying the filesystem driver)? Alternatively, is there a way of writing to a file before the beginning of the file (appending to the front of the file)?

A: This is likely related to your filesystem. On ext2/3/4, reiser, btrfs, xfs, and the like, doing what you describe should not take a long time, because they support what are called "sparse files" (files which take up less space in the underlying storage than the size of the file, because runs of zeroes aren't physically stored).
You might try an experiment with dd to make sure this is the case:
$ dd if=/dev/zero of=whatever bs=1k seek=1073741824 count=1
1+0 records in
1+0 records out
1024 bytes (1.0 kB) copied, 9.1878e-05 s, 11.1 MB/s
$ ls -al whatever
-rw-r--r-- 1 xxxx xxxx 1099511628800 Jan 31 18:04 whatever
$ du -h whatever
16K whatever

On your filesystem, that probably fails. If so, and what you need is to create a sparse file, determine whether you can use a different filesystem.

A:
However, on the first write the hole created by seeking gets zero-filled and if the hole is large enough, this operation can take some time.

No it can't. It will just write the data you provided to write(). The zeros in the unwritten portion aren't physically there: they are an artefact of the file system.

A: This may not be a feasible solution for your use case for various reasons, but I can imagine splitting the large file into serially numbered chunks. A missing or zero-sized chunk is supposed to contain zeroes (or some other fixed value). Choose the chunk size to fit the space you want to reserve and to get a good compromise between file size and number of chunks.
Or make it a bit more complicated and use variable chunk sizes, with the "virtual" size of the individual chunk stored somewhere else. Given a complex enough numbering system you can even insert new chunks without renaming the subsequent chunk files...
Of course you'll need an additional access layer to do the de-chunking, either in your application code if that's sufficient, or worst-case as kernel driver hooking into the file handling.

A: Have you tried to use the flag MAP_UNINITIALIZED ?


text:
Q: How do you pass thread safe data between the methods of a System.Web.Http.Filters.ActionFilterAttribute? I have a custom attribute extension of System.Web.Http.Filters.ActionFilterAttribute that I am using for logging with Web API controllers. I am experiencing an issue that indicates that the attribute object is being reused call to call. Data in my public properties from an initial call will appear in the logged information for a subsequent call and so on.
I read in this post that I "should never store instance state in an action filter that will be reused between the different methods." He goes on to say,"This basically means that the same instance of the action filter can be reused for different actions and if you have stored instance state in it it will probably break."
My custom attribute is apparently "break" ing. Thus began my search to answer the question …
How do you pass thread safe data between the methods of a System.Web.Http.Filters.ActionFilterAttribute?
An example is given in the post I referenced above of how data should be passed method to method using the HttpContext.Items dictionary. That's great and I can see how that would help but I'm not using ASP.net MVC'sSystem.Web.Http.Mvc.ActionFilterAttribute – which the poster uses in his answer. I'm doing Web API and the context object passed into the OnActionExecuting method is of type HttpActionContext and not of type ActionExecutingContext. I do not have access to the HttpContext.Items dictionary through the passed context, however, I believe that it is safe to access the HttpContext like this:
HttpContext.Current.Items[key]

Is that safe?
I do not have access to that dictionary in the constructor however and since that is where I receive my parameterized message string as a positional parameter, I am seemingly dependent on stored instance state.
So what to do?
In this post – also dependent on ASP.net MVC's System.Web.Http.Mvc.ActionFilterAttributeand its ActionExecutingContext– the poster uses the ActionParameters property of that context object to get at the parameters passed to the attribute, but I cannot find any equivalent in Web API's HttpActionContext. If I could, this would seem to be the answer! But alas…
How can I safely get to the positional parameter value passed into my constructor and the named parameter value passed in through a public property within the OnActionExecuting method?
Posts I have researched:

*

*Are ActionFilterAttributes reused across threads? How does that work?

*MVC Action Filter and Multiple Threads

*passing action method parameter to ActionFilterAttribute in asp.net mvc

*Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not firing?

*System.Web.Mvc.ActionFilterAttribute vs System.Web.Http.Filters.ActionFilterAttribute

*Web Api 2 HttpContext or HttpActionContext
Background: In the constructor, I pass a parameterized message string that includes placeholders for the values of arguments passed to the method the attribute is applied to. I also have an optional LogAllResponses property that is set through a named parameter to the attribute that I use to decide how much information I will log. The public properties that receive these values are set through the constructor and attribute invocation like this:
[LogAction("Retrieve information for all ad week items with storeId: {storeId}.", LogAllResponses = false)]

The important parts of the implementation of my action filter appear below:
public class LogActionAttribute : ActionFilterAttribute
{
    private static readonly Logger Log = LogManager.GetCurrentClassLogger();

    public string ParameterizedMessage { get; set; }
    public bool LogAllResponses { get; set; } = true;

    public LogActionAttribute(string parameterizedMessage)
    {
        ParameterizedMessage = parameterizedMessage;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        HttpContext.Current.Items["__Parameterized_Message__"] = ParameterizedMessage;
        HttpContext.Current.Items["__Log_All_Responses__"] = LogAllResponses.ToString();

        base.OnActionExecuting(actionContext);
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var contextualizedMessage = HttpContext.Current.Items["__Parameterized_Message__"] as string ?? "";
        var logAllResponsesAsString = HttpContext.Current.Items["__Log_All_Responses__"] as string ?? "";
        var logAllResponses = logAllResponsesAsString.CompareIgnoreCase("true") == 0;

        // convert argument values with ID suffixes to identifiable names
        var arguments = actionExecutedContext.ActionContext.ActionArguments;
        //foreach (var arg in arguments)
            // ...

        // replace the placeholders in the parameterized message string with actual values

        // log the contextualized message
        //Log.Debug(...

        base.OnActionExecuted(actionExecutedContext);
    }
}


text:
Q: change PATH permanently on Ubuntu I'd like to add to PATH the value ":/home/me/play/"
for the installation of Play! framework.
so I ran this command:
PATH=$PATH:/home/me/play

it worked. but in the next time I checked, the value changed back to the old one.
so I guess I didn't "saved" the new value, right?
how do you do that?

A: Add
export PATH=$PATH:/home/me/play

to your ~/.profile and execute
source ~/.profile

in order to immediately reflect changes to your current terminal instance.

A: Try to add export PATH=$PATH:/home/me/play in ~/.bashrc file.

A: Add the following line in your .profile file in your home directory (using vi ~/.profile):
PATH=$PATH:/home/me/play
export PATH

Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile

A: Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh (and possibly play.csh, etc):
PATH=$PATH:/home/me/play
export PATH


text:
Q: Docker-Compose Network Issue on Ubuntu 22.04 LTS I've been developing my python application using Django with PostgreSQL and Nginx and Docker, driven by Docker-Compose on my Macbook M1. And recently, decided to deploy it on the remote server, which has Ubuntu 22.04 LTS, but encountered really weird issue.
My web application says, that it cannot resolve host postgresql (service at docker-compose file, which you can find down below), however, it works fine on my machine, can it be related to the Docker?
It might be because I installed imcompatible versions of Docker and Docker-compose on this remote server or apparently used wrong commands, but not really sure about that, as I haven't gained enough experience of working with Ubuntu yet.
My Macbook's M1 Docker & Docker-compose Versions:
~ Docker - 20.10.12
~ Docker-Compose - 1.29.2
My Remote's Server Ubuntu Docker & Docker-compose Versions:
~ Docker - 20.10.23
~ Docker-compose - 1.29.2
My docker-compose.yaml file

version: "3.9"
services:

  nginx_server:
    container_name: "nginx_web_server"
    image: crazycoderrr/vdnh_nginx_server:latest # образ nginx для нашего проекта
    ports:
      - "8010:80"
    depends_on:
      - application_service
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
    networks:
      - private_network

  application_service:
    container_name: "application_server"
    image: crazycoderrr/vdnh_application:latest # образ backend сервиса нашего приложения
    ports:
      - "8000:8000"
    depends_on:
      - postgresql
    env_file: ./env/application.env
    networks:
      - private_network

  postgresql:
    container_name: "postgresql_database"
    image: crazycoderrr/vdnh_postgres_db:latest # образ для postgres нашего проекта
    environment:
      POSTGRES_USER: "postgres_user"
      POSTGRES_PASSWORD: "postgres_password"
      POSTGRES_DB: "vdnh_db"
    ports:
      - "5436:5436"
    command:
      - -p 5436
    networks:
      - private_network

networks:
  private_network:
    external: True
    name: private-project-network # приватная сеть, соединяющая все компоненты проекта
      # должна быть создана вручную!!!! <docker network create private-project-network -d bridge>

application.env file, that is used in my project
DATABASE_NAME="vdnh_db"
DATABASE_HOST="postgresql"
DATABASE_PORT=5436
DATABASE_USER="postgres_user"
DATABASE_PASSWORD="postgres_password"

If you are familiar with Django, this log message might be useful
File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect
application_server     |     self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner
application_server     |     return func(*args, **kwargs)
nginx_web_server       | exec /docker-entrypoint.sh: exec format error
postgresql_database    | exec /usr/local/bin/docker-entrypoint.sh: exec format error
application_server     |   File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
application_server     |     connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not translate host name "postgresql" to address: Name or service not known

What I did on the remote server:

*

*Installed Docker using this command from the official website:

$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

*Then, I installed Docker-Compose using the following command from the official website:

$ sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

$ sudo chmod +x /usr/local/bin/docker-compose

*Created private network for my project

$ docker network create private-project-network -d bridge

*Then cloned gitlab repository with the project and run docker-compose up -d command

*Then I decided to check logs using docker-compose logs and figured out, that it broken
If you have any thoughts on that, please, write out down in the comment section :)


text:
Q: как распараллелить работу с массивом данных есть цикл for, который пробегается по огромному массиву. время работы не радует, но имею идею, как упростить это всё. как можно реализовать чтобы параллельно выполнялся цикл for до середины массива, а вместе с ним, цикл с середины и до конца, чтобы сократить время

A: Есть два общих случая (для примера взял функцию возведения числа в квадрат):

*

*Ваша функция обрабатывает массив.

from threading import Thread

long_array = list(range(10**3))

def calculate_array(array): # ваша функция для обработки массива
    for element in array:
        print(f'{element}**2={element**2}')

threads = [
    Thread(target=calculate_array, args=(long_array[:len(long_array)//2], )),
    Thread(target=calculate_array, args=(long_array[len(long_array)//2:], ))
]

for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

*Ваша функция обрабатывает отдельный элемент.

from threading import Thread

long_array = list(range(10**3))

def calculate_element(element): # ваша функция обработки элемента
    print(f'{element}**2={element**2}')

def calculate_array(array): # пишем обертку для возможности разделения на потоки
    for element in array:
        calculate_element(element)

threads = [
    Thread(target=calculate_array, args=(long_array[:len(long_array)//2], )),
    Thread(target=calculate_array, args=(long_array[len(long_array)//2:], ))
]

for thread in threads:
    thread.start()
for thread in threads:
    thread.join()


text:
Q: how to call the function once at a time? I'm working on my PHP script to call the function once at a time when I click the link on my site.
When I click the link on my site to connect to the get-listing.php script, it will call to both function of tvguidecom and skyuk at the same time which it will output one of those webpage.
I think the problem are on this line:
while ($row = mysql_fetch_array($result1))
{
   tvguidecom($row);
   skyuk($row);
}

Here is the full code:
<?php
$errmsg_arr = array();
$errflag = false;
$link;
include ('simple_html_dom.php');

function db_connect()
{
  define('DB_HOST', 'localhost');
  define('DB_USER', 'mydbname');
  define('DB_PASSWORD', 'mydbpassword');
  define('DB_DATABASE', 'mydbname');

  $errmsg_arr = array();
  $errflag = false;
  $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

  if(!$link)
  {
    die('Failed to connect to server: ' . mysql_error());
  }

  $db = mysql_select_db(DB_DATABASE);
  if(!$db)
  {
    die("Unable to select database");
  }
}

function tvguidecom($row)
{
  include ('tvguide.get-listing.php');
}
function tvguide2($row)
{
  include ('skyuk.php');
}
db_connect();

function clean($var)
{
  return mysql_real_escape_string(strip_tags($var));
}

$channels = "";
$id = "";

if(isset($_GET['channels']))
{
  $channels = $_GET['channels'];
}
if(isset($_GET['id']))
{
  $id = $_GET['id'];
}

if($errflag)
{
  $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
  echo implode('
',$errmsg_arr);
}
else
{
  $insert = array();

  if(isset($_GET['channels']))
  {
    $insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
  }
  if(isset($_GET['id']))
  {
    $insert[] = 'id = \'' . clean($_GET['id']) . '\'';
  }

  if($channels && $id)
  {
    $qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
    $result1=mysql_query($qrytable1) or die('Error:
' . $qry . '
' . mysql_error());

    while ($row = mysql_fetch_array($result1))
    {
      tvguidecom($row);
      skyuk($row);
    }
    mysql_close();
    exit;
  }
  else if(!$channels && ! $id)
  {
    $qrytable1="SELECT id, channels, links, streams FROM tvguide";
    $result1=mysql_query($qrytable1) or die('Error:
' . $qry . '
' . mysql_error());

    while ($row = mysql_fetch_array($result1))
    {
      echo "
".$row["id"]. " " . $row["channels"]. "
";
      echo 'http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '

';

      //echo "
";

      //echo 'http://example.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'>test
';
      //echo '<a id="link1" href="http://example.com/get-listing.php?channels=';

      echo 'Stream 1

';
    }
  }
}
?>

I want to call either of function once at a time when I click the link on my site. Example: I want to call tvguidecom function to see if it will output the data in my get-listing script or else move on to the next function and call the skyuk function.
Can you please show me an example of how I can call the function once at a time when I click the link on my site?

A: The best thing you can do is having your functions returning a boolean so you can check if you should continue the process.
I guess the function tvguidecom looks like:
function tvguidecom() {
    // do something without return value
}

Add a return value in it:
function tvguidecom() {
    // do something
    return $status;
}

So in your code you can test for the return value
while ($row = mysql_fetch_array($result1))
{
    if (tvguidecom($row)) {
        skyuk($row);
    }
}

Note: on a different topic, you shouldn't use anymore mysql extension because it is deprecated. You should use instead mysqli or pdo.

A: TL;DR
while ($row = mysql_fetch_array($result1))
{
   // this ensures that `tvguidecom()` does its stuff, and `skyuk()`
   // waits for results returned by the function.
   skyuk(tvguidecom($row));
}

function tvguidecom($row) {
  // do stuffs, returns original input $row;
  return $row;
}

** Another approach, callbacks.**
while ($row = mysql_fetch_array($result1))
{
   tvguidecom($row, callback);
}

and fn:
tvguidecom(a, callback) {
  // dostuffs and when complete
  callback( result );
}

** syntax may be incorrect, refer to link supplied. Hope this helps.


text:
Q: Does maven-shade-plugin allow for packed dependency jars to be included? maven-shade-plugin includes the dependencies unpacked within the uber jar, which makes sense because of the shading that is involved.
Is there a way to allow for a specific 'safe' dependency to be included as a whole jar (not unpacked into classes)? I could not see such a thing in the docs.


text:
Q: Will switching Ubuntu clocksource from xen to tsc impact php/Laravel application? Background
We started using new relic on our laravel app server (hosted on ubuntu ec2) but then immediately noticed a jump in latency in our aws cloudwatch:

New relic tech support immediately suggested that we switch our clock source from xen to tsc:

It appears that the clocksource on your system isn't supporting vDSO.
  Since the PHP Agent heavily relies on the gettimeofday() system call
  to determine the length of time of segments and transactions,
  clocksource plays a big role in preventing system calls from hitting
  the system itself which greatly speeds things up.
In this particular scenario we recommend using the tsc clocksource. We
  have seen big performance gains with tsc clocksource enabled and I
  wanted to ask if it would be possible for you to temporarily enable
  the tsc clocksource to see if the overhead reduces.
If New Relic is the only application for which accurate timing is
  required, or if you're only concerned with accurately measuring
  shorter durations, tsc is a good choice for clocksource.

I did a quick search on the difference between the two clocksources, and didn't find any giant red flags (there were these issues that were mentioned here:
TSC, however, has its own issues, including:

*

*Its frequency is unknown, and it needs to be measured with PIT, CMOS,
  or ACPI timer.

*The register is writable and the reading can differ on
  different CPUs.

*TSC can stop in some low-power C states of the
  processor. This doesn't usually happen on modern hardware.

*TSC getting
  out-of-sync on some big NUMA systems was observed in the past.
  Luckily, the number of such systems was limited.

*SMI handlers may reset the counter.

All of this sounds foreign to me, but it seems that they are only relevant for micro- time keeping needs (such as profilers etc) and I don't think its' really relevant for a php/laravel app where we can tolerate inaccuracy in time with a threshold up to 3 seconds (but not more, as our application relies on real time notifications to users).
Am I right with my assumption?
appendix I: instructions from new relic support team on how to switch from xen to tsc:

To set the current clock source to a different value
Run bash as a super user to override the current_clocksource:
sudo bash -c 'echo tsc >
  /sys/devices/system/clocksource/clocksource0/current_clocksource' Run
  the dmesg command to view the kernel messages:
dmesg | less If the override was successful, the following message
  appears:
clocksource: Switched to clocksource tsc

A: I made a lot of research on this topic this week. My stack is quite similar to yours, the only difference is that I'm running on an ECS Optimized AMI.
If your application doesn't need mile-seconds precision, it should be okay for you to switch to TSC. Make sure that you are running on a new generation, with an updated kernel. This is the impact that I saw, with basically half of the instances: https://imgur.com/TllxFXs
AWS recommended to use their own service to keep time in sync: https://aws.amazon.com/blogs/aws/keeping-time-with-amazon-time-sync-service/
I'm still organizing my references, let me know if you need more info.


text:
Q: VB.NET JSON Deserialization javascriptserializer Hello how can I deserialize the following JSON structure with VB.NET?
{
    "ok": true,
    "license": "CC BY 4.0",
    "data": "TEST",
    "stations": {
        "station1": {
            "status": "open",
            "price1": 1.234,
            "price2": 1.234,
            "price3": 1.234
        },
        "station2": {
            "status": "open",
            "price1": 1.234,
            "price2": 1.234,
            "price3": 1.234
        }
    }
}

Important the number of stations could be different. Here in this example are two stations.
Thank you very much.

A: Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. Using either Newtonsoft.Json or System.Text.Json, you can tidy the classes up a little bit using decorators so that you can conform to .NET standard naming conventions while still serializing the JSON to the expected values.
This is how the class definitions would look tidied up a bit:
Public Class Response
    <JsonProperty("ok")>
    Public Property Ok As Boolean

    <JsonProperty("license")>
    Public Property License As String

    <JsonProperty("data")>
    Public Property Data As String

    <JsonProperty("stations")>
    Public Property Stations As IEnumerable(Of Station)
End Class

Public Class Station
    <JsonProperty("status")>
    Public Property Status As String

    <JsonProperty("price1")>
    Public Property Price1 As Single

    <JsonProperty("price2")>
    Public Property Price2 As Single

    <JsonProperty("price3")>
    Public Property Price3 As Single
End Class

Now all you need to do is call the DeserializeObject method, using your Response class as the type and passing your JSON literal. For example:
Dim literal = "{
  ""ok"": true,
  ""license"": ""CC BY 4.0"",
  ""data"": ""TEST"",
  ""stations"": {
    ""station1"": {
      ""status"": ""open"",
      ""price1"": 1.234,
      ""price2"": 1.234,
      ""price3"": 1.234
    },
    ""station2"": {
      ""status"": ""open"",
      ""price1"": 1.234,
      ""price2"": 1.234,
      ""price3"": 1.234
    }
  }
}"
Dim conversion = JsonConvert.DeserializeObject(Of Response)(literal)


text:
Q: Copying formula for dynamic range I have a Macro to place a division formula in a cell in row "d", and replicates the same formula all the way in row "d" till the last cell.
I am trying to replicate the same formula across other columns "E:L" without having to rewrite the entire code for each column seperately
With wbk4.Sheets("USD")
Set clDest = .Range("D2")
Set clLookup = .Range("AA2")
End With

If clLookup.Offset(1, 0) <> vbNullString Then
rws = Range(clLookup, clLookup.End(xlDown)).Rows.Count
Set clDest = clDest.Resize(rws, 1)
End If
clDest.Formula = "=(" & clLookup.Address(False, False) & " / 3.68)"

This does the correct formula for the mentioned column "D" till the last cell.
What i need is this to be replicated across the following columns "E" to "L"
only from the 2nd cell till the last row.
I tried to do it through the below logic, but its a bit too complicated and does not work, Im sure there is another way around :)
With wbk4.Sheets("USD")
lrow = .Range("D" & .Rows.Count).End(xlUp).Row
.Range("D2" & lrow).Copy
wbk4.Sheets("USD").Range("E2").PasteSpecial Paste:=xlPasteFormulas
End With

A: For a quick and dirty solution simply replace
Set clDest = clDest.Resize(rws, 1)

with
Set clDest = clDest.Resize(rws, x)

where x is the number of columns you want to fill.


text:
Q: OSGi service and MVC pattern best practice Let's suppose I have two osgi bundles. There is mvc pattern in each bundle. View - swing JFrame. What is the best practice to communicate between these two components? As I see there are two ways:
1) In service we do service function and inside this function we call controller function. Something like that
Class MyService {
    public void readSomething(){
      controller.readAction();
    }
}

2) Or service may return controller and the other component will use this foreign controller. Something like that:
Class MyService {
    public Controller getController(){
      return controller;
    }
}

I'd like to know what other people use and think.

A: In general, it depends :-).
I assume you have two components A and B, and component A needs to notify component B of something, or, in other words, component B is interested in something that happens in component A.
One way for the components to cooperate is to use the EventAdmin service; component A emits events for all possible cases, and component B has registered an EventHandler with an appropriate filter for these events. Bonus: component A can specify sync/async handler execution, and there may be multiple components that will be notified without any extra overhead. Both A and B need not be services or even objects, if the bundle activators handle all the wiring.
Another way is to use Declarative Services: components A and B are objects, and you have defined an interface IB that specifies the valid operations on B, and which B implements. A is marked as needing at least one IB, and the DS service will instantiate both and invoke methods on A with the proper IB references. A can then normally call methods of IB.
As a simplification of DS, you can use normal services: A isn't a service, but it finds instances of IB everytime it needs to invoke methods on IB.
Last but not least, there's the Blueprint Service that can instantiate complex object graphs using dependency injection, including service proxies, which I have never used and don't feel that I can comment on...


text:
Q: Alternative definition of Legendre transform as an integral Let $f(x)$ be a convex function. Define $g(y)$ via the integral:
$$\mathrm{e}^{-g(y)} =  \int_{-\infty}^\infty \mathrm{d}x \, \mathrm{e}^{yx-f(x)}$$
assuming that the integral converges. The domain of $f(x)$ and $g(y)$ is the entire real line.
Is $g(y)$ the Legendre transform of $f(x)$?
Some context. I found this formula reading a paper, Eq. 13, http://stacks.iop.org/1742-5468/2011/i=03/a=P03008. There it is claimed that an integration of this form yields the Legendre transform. My question is whether this formula can be used in general as an equivalent definition of the Legendre transform (for the standard definition, see https://en.wikipedia.org/wiki/Legendre_transformation).


text:
Q: How do i keep the footer always at the bottom while content resize with different resolutions I made a site for a friend of mine. You can see it here.
The thing is i want the bottom part of the page actually be on the bottom of the site. And the images resizing with another resolution.
Example:
Watching the site on a 1366x768 resolution the page is always in view like here:
But when i switch on a higher resolution with a bigger height(1280x1024) it looks like this
As you can see there is many space between the bottom of the page and the bottom of the site itself.
I want it to keep it like the 1366x768 resolution always "fullsite" the images getting bigger at a higher height and the "footer" is always at the bottom of the page. Like a dynamic fullscreen page.
I hope you can help me i thought about media queries but i am not sure if this is the best solution and if so how it would be the best to actually query them.
Thanks for your time i appreciate your help !

A: I don't think it's a good practice to fix the footer to the bottom, because it would hide content and worst case would be no space for any content if the window height is smaller than nav height + footer height.
In this case if you really want to move the footer to bottom, I'd rather use some javascript to add padding-bottom to the content (slider in this case), if the window height is bigger than your website height:
var windowHeight  = window.innerHeight;
var websiteHeight = parseInt(window.getComputedStyle(document.body).height);

if (windowHeight > websiteHeight) {
    var diff = windowHeight - websiteHeight;
    document.getElementById('slider').style.paddingBottom = diff+'px';
}

Put this inside a function and call it in body onload. Notice that if you hover over the shoe, the content height will increase and move the footer down further. Thats why in responsive design you usually don't fix things vertically, but instead let the content height be a flexible variable...
Another approach would be CSS min-height property on the content to make it take up a minimum amount of the browser height.


text:
Q: Nested GridView Row Event Pandemonium I have come across odd behavior involving nested gridview controls and row events.  Basically the nested gridview row event will not fire unless it is in the last row of the outer grid.
If you explicitly add the row event property to the markup (e.g. OnRowDeleted="gvInner_RowDeleted") then the row event fires for all nested gridviews however it fires twice for the nested gridview in the last row of the outer gridview
EDIT: I should note that I am using the SqlDataSource for the outer gridview as it is also editable. This isn't clear in the example.
Markup:
<asp:GridView ID="gvOuter" DataSourceID="sdsOuter" runat="server" OnRowDatabound="DynamicControlAdder" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" ReadOnly="true" />
        <asp:TemplateField>
            <ItemTemplate>

                        <asp:UpdatePanel ID="upInner" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:GridView ID="gvInner" DataSourceId="sdsInner" runat="server" DataKeyNames="Id"  AutoGenerateColumns="false">
                                    <Columns>
                                        <asp:CommandField ShowDeleteButton="true" />
                                        <asp:BoundField DataField="Id" />
                                    </Columns>
                                </asp:GridView>
                                <asp:SqlDataSource ID="sdsInner" runat="server"
                                    ProviderName="<%$ ConnectionStrings:YourString.ProviderName %>"
                                    ConnectionString="<%$ ConnectionStrings:YourString %>"
                                    SelectCommand="SELECT * FROM tblInner WHERE OuterTableKey = @OuterTableKey"
                                    DeleteCommand="DELETE FROM tblInner WHERE Id = @Id">
                                    <SelectParameters>
                                        <asp:Parameter Name="OuterTableKey" DefaultValue="0" Type="Int32" />
                                    </SelectParameters>
                                    <DeleteParameters>
                                        <asp:Parameter Name="Id" DefaultValue="0" Type="Int32" />
                                    </DeleteParameters>
                                </asp:SqlDataSource>
                            </ContentTemplate>
                        </asp:UpdatePanel>

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsOuter" runat="server"
   ProviderName="<%$ ConnectionStrings:YourString.ProviderName %>"
   ConnectionString="<%$ ConnectionStrings:YourString %>"
   SelectCommand="SELECT * FROM tblOuter">
</asp:SqlDataSource>

Code:
Partial Class Testing
Inherits System.Web.UI.UserControl

Protected Sub DynamicControlAdder(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

    If e.Row.RowType <> DataControlRowType.DataRow Then
        Exit Sub
    End If

    Dim s As SqlDataSource = CType(e.Row.FindControl("sdsInner"), SqlDataSource)
    s.SelectParameters("OuterTableKey").DefaultValue = e.Row.DataItem("Id").ToString()

End Sub

Protected Sub gvInner_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvInner.RowDeleted
    //'This never fires unless it is the last row in the outer gridview
    //'also, if this event is declared in the OnRowDeleted property of the inner gridview, this event fires twice if it is in the last row of the outer grid
    Dim strFoo As String = "Foo"
End Sub
End Class

Can anybody reproduce this, and how do you work around it?

A: I don't think you should doing what you're doing the way you're doing it.
Here's how I would do what you're attempting:

*

*Use a repeater for your outer databound control as it renders more efficiently and it will have the same effect you're trying to achieve with the outer gridview control.

*In your code behind, retrieve your data for your outer gridview (which is now a repeater) and load it into a datatable and add it to a dataset, do the same for data in the inner gridview.

*Then create a relation between the datatables within the dataset using DataSet.Relations.Add

*Once you create the relationship between both datatables in the dataset, you can access the fields (columns) in your second datatable which will be used to populate the data for the nested (inner) gridview control.

Markup
<asp:Repeater ID="rpt1" runat="server">
    <ItemTemplate>
        <asp:GridView ID="gv1" runat="server" DataSource='<%# Container.DataItem.Row.GetChildRows("relation1") %>' GridLines="None" AutoGenerateColumns="false">
            <columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="txt1" runat="server" Text='<%# Container.DataItem("<column>") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </columns>
        </asp:GridView>
    </ItemTemplate>
</asp:Repeater>

Code Behind
Dim ds As New DataSet
Dim dt1 As DataTable = obj.<method> 'Outer data
Dim dt2 As DataTable = obj.<method> 'Inner data

ds.Tables.Add(dt1)
ds.Tables.Add(dt2)

ds.Relations.Add("relation1", ds.Tables(0).Columns("<unique identifier column name>"), ds.Tables(1).Columns("<unique id column name>"), False)

rpt1.DataSource = dt1
rpt1.DataBind()

A: And the answer is......
Remove the handles clause from the RowDeleted Event and set the OnRowDeleted Property to the gvInner_RowDeleted event.
Updated code below.  I just wish i had the last 4 hours of my life back.
Markup:
<asp:GridView ID="gvOuter" DataSourceID="sdsOuter" runat="server" OnRowDatabound="DynamicControlAdder" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" ReadOnly="true" />
        <asp:TemplateField>
            <ItemTemplate>

                        <asp:UpdatePanel ID="upInner" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:GridView ID="gvInner" DataSourceId="sdsInner" runat="server" DataKeyNames="Id" OnRowDeleted="gvInner_RowDeleted"  AutoGenerateColumns="false">
                                    <Columns>
                                        <asp:CommandField ShowDeleteButton="true" />
                                        <asp:BoundField DataField="Id" />
                                    </Columns>
                                </asp:GridView>
                                <asp:SqlDataSource ID="sdsInner" runat="server"
                                    ProviderName="<%$ ConnectionStrings:YourString.ProviderName %>"
                                    ConnectionString="<%$ ConnectionStrings:YourString %>"
                                    SelectCommand="SELECT * FROM tblInner WHERE OuterTableKey = @OuterTableKey"
                                    DeleteCommand="DELETE FROM tblInner WHERE Id = @Id">
                                    <SelectParameters>
                                        <asp:Parameter Name="OuterTableKey" DefaultValue="0" Type="Int32" />
                                    </SelectParameters>
                                    <DeleteParameters>
                                        <asp:Parameter Name="Id" DefaultValue="0" Type="Int32" />
                                    </DeleteParameters>
                                </asp:SqlDataSource>
                            </ContentTemplate>
                        </asp:UpdatePanel>

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsOuter" runat="server"
   ProviderName="<%$ ConnectionStrings:YourString.ProviderName %>"
   ConnectionString="<%$ ConnectionStrings:YourString %>"
   SelectCommand="SELECT * FROM tblOuter">
</asp:SqlDataSource>

Code:
Partial Class Testing
Inherits System.Web.UI.UserControl

Protected Sub DynamicControlAdder(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

    If e.Row.RowType <> DataControlRowType.DataRow Then
        Exit Sub
    End If

    Dim s As SqlDataSource = CType(e.Row.FindControl("sdsInner"), SqlDataSource)
    s.SelectParameters("OuterTableKey").DefaultValue = e.Row.DataItem("Id").ToString()

End Sub

Protected Sub gvInner_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs)
    //' Now we're talking
    Dim strFoo As String = "Foo"
End Sub
End Class


text:
Q: Can't find UIWebView in a TableView I'm trying to show webview in a table cell.
The error Unexpectedly found nil while unwrapping optional pops up at "let webView = cell.viewWithTag(12) as! UIWebView". The tag of webView is 12(cross checked it many times). dateLabel and captionLabel are working fine.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell : UITableViewCell!
    cell = tableView.dequeueReusableCellWithIdentifier("idCellPost", forIndexPath: indexPath)
    let dateLabel = cell.viewWithTag(10) as! UILabel
    let captionLabel = cell.viewWithTag(11) as! UILabel
    let webView = cell.viewWithTag(12) as! UIWebView
    dateLabel.text = "8/18/2015"
    captionLabel.text = "Dummy text."
    webView.loadRequest(getRequest())
    webView.scalesPageToFit = true
    return cell
}

A: You have created a custom cell. You do not need to access it's subview with tag. You can directly access them as properties.
    if let customCellObject = tableView.dequeueReusableCellWithIdentifier("idCellPost", forIndexPath: indexPath) as? CustomCell  {
        customCellObject.dateLabel?.text = "8/18/2015"
        customCellObject.captionLabel?.text = "Dummy text."
        customCellObject.webView?.loadRequest(getRequest())
        return customCellObject
    }

Of course outside the if block you need to handle the case if you custom cell is not dequeued.

A: let dateLabel: UILabel = UILabel()
let captionLabel:UILabel = UILabel()
let webView : UIWebView = UIWebView(frame: cell.frame)

dateLabel.text = "8/18/2015"
captionLabel.text = "Dummy text."
webView.loadRequest(getRequest())
webView.scalesPageToFit = true
[cell.addSubview(webView)];

//you should have viewWithTag 10 and 11.
func getRequest()-> NSURLRequest!{
let urlPath: String = "http://www.google.com"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
return request1
}

A: Uncheck "Use size classes" under file inspector in Utility tab. It is working fine now. For some reason ViewWithTag returns nil when size classes is checked.


text:
Q: Switch não está preenchendo todos os dados Olá, tenho um Grid e estou fazendo algumas alterações de dados para exibição, explicando melhor, no meu banco de dados eu salvo os dados com apenas um valor: "V", "A", "O", e quero fazer alterações para exibição, como mostra o switch.
function criador_linhas(s, e) {
    if (s.rowType == "data") {
        switch (s.data.CatVen_Tipo) {
            case "V":
                s.data.CatVen_Tipo1 = "Venda Avulsa";
                break;
            case "A":
                s.data.CatVen_Tipo1 = "Ambos";
                break;
            case "O":
                s.data.CatVen_Tipo1 = "Orçamento/Projeto";
                break;
            default:
                s.data.CatVen_Tipo1 = "Erro";
                break;
        }
    }
}

Meu banco de dados:

O problema é o seguinte, ele preenche alguns valores, mas outros ele deixa vazio, como mostra a imagem:

Meu DataGrid:
@(Html.DevExtreme().DataGrid()
                                            .ShowBorders(true)
                                            .Height(355)
                                            .Selection(s => s.Mode(SelectionMode.Single))
                                            .DataSource(Model, new string[] { "CatVen_Codigo" })
                                            .Columns(columns =>
                                            {
                                                columns.Add().DataField("CatVen_Codigo").Width(100).Caption("Código");
                                                columns.Add().DataField("CatVen_Descricao").Caption("Descrição");
                                                columns.Add().DataField("CatVen_Tipo1").Width(120).Caption("Tipo");
                                                columns.Add().DataField("CatVen_Ativo").Width(120).Caption("Situação");
                                            }).OnSelectionChanged("selection_changed")
                                            .Paging(p => p.PageSize(10))
                                            .FilterRow(f => f.Visible(true))
                                            .HeaderFilter(f => f.Visible(true))
                                            .OnRowPrepared("criador_linhas")
                                            .GroupPanel(p => p.Visible(true))
                                            .GroupPanel(p => p.EmptyPanelText("Arraste uma coluna até aqui para agrupar por essa coluna"))
                                            .NoDataText("Nada encontrado")
                                            .Grouping(g => g.AutoExpandAll(false))
                                            .RemoteOperations(true)
                                            .LoadPanel(loadPanel => loadPanel.Enabled(false))
                                            .Scrolling(scrolling => scrolling.Mode(GridScrollingMode.Infinite))
)


text:
Q: Second chern class and length of a zero dimensional sheaf on surface Let, $\mathcal T$ be a $0$ dimensional sheaf on a $K3$ surface.
Then is it true that $c_2(\mathcal T) = - h^0(\mathcal T)$?
If we consider $Z =Supp(\mathcal T)$,then $Z$ is a zero dimensional subscheme and we know that $c_2(\mathcal I_Z) = h^0(\mathcal O_Z)$. Can the desired relation be deduced from here?
Any help from anyone is  welcome.


text:
Q: Add hint to function after declaring Here is the screenshot of $.each() hint:

I'm using Visual Studio, is there a way to add hint to a function after declaring?
jQuery.fn.extend({
    Each: function () {

    }
});

I wanna add some text to Each() function to explain how to use this function.
Is it possible? And how?

A: Use JSDoc comments.
jQuery.fn.extend({
    /**
     * @description Enter your description here
     * @param {type} arg  Use this for arguments
     * @param {type} arg2 Multiple if using multiple args
     * @return {type} Return type
     */
    Each: function(arg, arg2) {
    }
});


text:
Q: Is there a notion of a smooth point on a surface? I know that an entire surface can be smooth, but can a single point on a surface be considered smooth? Even if there is no smooth neighborhood about that point?
If so, can you say that a surface is smooth iff all the points on the surface are smooth? Is there a notion of almost everywhere smooth?


text:
Q: Azure Media Services Resource under resource group was not found I trying this article about azure media services, but I got this error

az ams account sp create --account-name amsaccount --resource-group amsgroup

Error from the console

PS C:\Users\Herman> az ams account sp create -a amsaccount -g amsgroup -n ams --password amssecret --role Owner
  Command group 'ams' is in preview. It may be changed/removed in a future release.
  (ResourceNotFound) The Resource 'Microsoft.Media/mediaservices/amsaccount' under resource group 'amsgroup' was not found.

A: The command you are running is to create a service principal to access an existing AMS account.  But it looks like you don't have an AMS account in your subscription in the resource group amsgroup with account name amsaccount.  Did you already create that AMS account by following the instructions in https://learn.microsoft.com/en-us/azure/media-services/latest/create-account-cli-how-to?
You could also run this command to list all of the AMS accounts you have created in your subscription:
az ams account list


text:
Q: Bounded functions and infimum/supremum Question from my homework:

A function $f \colon S \to \mathbb{R}$ is said to be decreasing on the domain $S \subset \mathbb{R}$ if for every $x, y \in S$ with $y > x$, we have $f(y) < f(x)$.
  Show that if $f \colon \mathbb{R} \to \mathbb{R}$ is decreasing and bounded on $\mathbb{R}$, then the limits $\lim_{x \to \infty} f(x)$ and $\lim_{x \to -\infty} f(x)$ both exist.
Caution: While this claim is clearly related to the theorem that bounded monotone sequences always converge, it is not an immediate corollary of it.
  You will have to use the definition of the limit directly.
(Original picture of the problem here.)

My proof:
Let $ S = \{f(x) | x \in \mathbb{R} \} $, since $f$ is bounded this set has both an infimum and supremum. (Is this true? I tried to prove it, but have no idea as it seems fairly obvious.) Now, I claim that $\lim_{x\to \infty} f(x) = \inf(S) = L$.
By definition, given $\epsilon > 0$, there exists $K \in \mathbb{R}$ such that $x>K \implies |f(x) - L| < \epsilon$.
Now since $f(x) \geq L$ by definition of the infimum, choose $x_1$ such that $f(x_1) < L + \epsilon$ for $x_1 > K$. But since $f$ is a decreasing function we have $f(x) \leq f(x_1)$, and thus
$$
  L - \epsilon < L \leq f(x) \leq f(x_1) < L + \epsilon
$$
which proves our claim.
I use a similar argument for the supremum. Could anyone help me out on making this more rigorous as I feel as though I've skipped some steps.

A: I think you are almost there. I would proceed like this:
For $\epsilon > 0$ be a given, there exists an $x^{*}$ such that $f(x^{*}) < L + \epsilon $. So let $K = |x^{*}| + 1 > 0$, then for all $x$'s such that $x > K$ we have: $f(x) < f(K) < f(x^{*}) < L + \epsilon$. But $L < f(x)$ since it is $\text{inf}\{f(x): x \in \mathbb{R}\}$. So
$L - \epsilon < L < f(x) < L + \epsilon$. This means $|f(x) - L| < \epsilon$ and we're done.


text:
Q: What is distance multiplied by time? From grade 6th we have been taught that if we find the area of the velocity-time graph is distance covered or in other words if velocity is constant then distance= velocity* time as velocity = distance/ time and time cancels out.
So what would be distance* time?

A: The integral of distance with respect to time is known as absement. It is one of the family of derivatives and integrals of position, and can be integrated further to get absity, abseleration and abserk.

Absement appears when considering situations where a quantity depends on both how far something has moved or extended and how long the movement is maintained for. For example, it's been used in the study of memristors, artificial muscles and human posture.

A: As far as I know, distance $s$ multiplied by time $t$ or (as the differential analogue) the integral $$^{(*)}: \int_{t_0}^{t}s(\tilde{t})\text{d}\tilde{t}\   $$  are not used in the context of physics. Nonetheless, this does not mean that it cannot interpreted physically. If an object travels uniformly along a straight line, $^{(*)}$ will obviously be larger compared to an object accelerated uniformly along the same distance and within the same period of time. In general, $^{(*)}$ increases if an object is displaced farther away from its initial position for longer periods of time.
In a way, $^{(*)}$ measures for how long an object is displaced at which distance from its inital position. I can think only of a few "usecases" for $^{(*)}$. For example, if you were to stretch an elastic band and keep it stretched, you (at least ideally) do not do any work after you have reached the maximal displacement, but after some time you will obviously get tired and will have to relax the band.
In this context, $^{(*)}$ might be used to measure ones physical ability to do such things.
However, I have never heard of anybody actually using $^{(*)}$ as a benchmark.


text:
Q: Passing args from Razor Page to a Razor Component The scenario
I've created a Razor Pages project and added server side blazor rendering so that I can add Razor Components. I am having an issue where _Layout.cshtml renders a razor component on the page and passes an argument to it, yet at runtime, the razor component appears to not receive an argument for this parameter.
Example with actual output
_Layout.cshtml
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor

<!DOCTYPE html>
<html lang="en">

<body>
    IP ON GET WAS: @HttpContextAccessor.HttpContext.Connection.RemoteIpAddress
    <component type="typeof(MyFormComponent)" IPAddress="@HttpContextAccessor.HttpContext.Connection.RemoteIpAddress" render-mode="ServerPrerendered"/>

</body>
</html>

When the website renders, the visitor's IP address is displayed directly above the component. (I'm doing this purely to prove to myself that _Layout.cshtml, the page rendering the razor component, does indeed have access to a concrete working child of IHttpContextAccessor.)
MyFormComponent.razor
@using System

<button type="button" @onclick="doStuff">
    Click Me
</button>

@code
{

    [Parameter]
    public string IPAddress { get; set; }

    private void doStuff()
    {
        Console.WriteLine("We've got the IP! -> " + this.IPAddress);
        // prints: "We've got the IP! -> "
    }
}

When the above button is clicked on the component, this.IPAddress is null. I've checked this value on a breakpoint while debugging and I've observed that the IP address is not printed to the console.
The expected output
I expected that my razor component would receive the argument value passed to it and print it to the console whenever the button is clicked. I expected that _Layout.cshtml would be able to pass this value to the razor component because it has proven that it does indeed have access to the desired value I want to pass by displaying the value on the page.
Closing notes

*

*This was initially a Razor Pages project, created via dotnet new webapp.

*Server side blazor was introduced to the project and has been working with great success, with this issue being the only exception so far. So, the project does have a _Host.cshtml and _Imports.razor file, along with the AddServerSideBlazor() call in Startup.ConfigureServices(), and the MapBlazorHub() endpoint added in Startup.Configure(). I didn't think it would be necessary to share the contents of these files for this specific problem. If I'm wrong about this, please, let me know!

*You might notice that this issue specifically involves a reference to IHttpContextAccessor. If you were not aware, this specific class is NOT to be accessed directly from within a razor component for the reasons described here.

A: It appears that the solution to this problem is simply an alternate syntax being used to render the razor component in the _Layout.cshtml file.
By replacing (the current code)
<component type="typeof(MyFormComponent)" IPAddress="@HttpContextAccessor.HttpContext.Connection.RemoteIpAddress" render-mode="ServerPrerendered"/>

with the following (a new snippet):
@(await Html.RenderComponentAsync<MyFormComponent>(RenderMode.ServerPrerendered, new { IPAddress=HttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()}))

I was able to resolve this issue.


text:
Q: Cannot add migration with ASP.net Core 2 I'm building a new project using ASP.net Core 2 and EntityFrameWorkCore 2.1.0 and I began to build the database structure. Now I have to make my first Migration to get my database ready and when I execute 'Add-Migration Init' into the Package Manager Console I got this error:
The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding'. Configure your services to use one that can.

Also I tried this documentation https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations and the message I got is:
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

I also followed this article without any success.
If I try without Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.0.2 and with a simple 2 tables structure I'm able to make it work.
So now I need your help...

A: I found some reasons why we can get hard time to use migration with the latest version of ASP.net Core 2 at this time.
First of all, if you just migrate from an old project which is not built from ASP.net Core at all, you will have to add a Context Factory to make Migrations work. Here my own Context Factory:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
        builder.UseSqlServer("Server=(local)\\SQLEXPRESS;Database=yourdatabase;User ID=user;Password=password;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name));

        return new ApplicationDbContext(builder.Options);
    }
}

If you divided your project into layers for architecture purpose, add the Context Factory inside the Repository Layer or in the same library where your DbContext is.
Secondly, before any attempt to add a migration, you must set the selection of "set as startup project" on the repository library or where your DbContext is.
Then, those are the packages you need to use for migration:

*

*Microsoft.AspNetCore.Identity.EntityFrameworkCore

*Microsoft.EntityFrameworkCore.Design

*Microsoft.EntityFrameworkCore.SqlServer

That's all!
Be careful when you add other packages because they can break the Migration system. As an example, if you use a Unit of Work & Repositories Framework like URF and install URF.Core.EF.Trackable -Version 1.0.0-rc2, you will no longer be able to add migration. Instead use URF.Core.EF.Trackable -Version 1.0.0-rc1. I guess this can happen with many other packages as well.
Finally, read this article will be helpful. It's a little outdate but it can help people out there.
Cheers

A: Make sure that you have the required NuGet packages installed:

*

*Microsoft.EntityFrameworkCore.SqlServer

*Microsoft.EntityFrameworkCore.Design

A: How do you arrange the main method in "Program.cs"?
This error can be amenable to a old initialization pattern.
From the Asp Net migrations guidelines:

The adoption of this new 2.0 pattern is highly recommended and is
  required for product features like Entity Framework (EF) Core
  Migrations to work. For example, running Update-Database from the
  Package Manager Console window or dotnet ef database update from the
  command line (on projects converted to ASP.NET Core 2.0) generates the
  following error:

Unable to create an object of type ''. Add an implementation of 'IDesignTimeDbContextFactory' to the
    project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
    additional patterns supported at design time.

Check at this link of the correct implementation

A: In my case, the dbcontext was different in Startup within ApplicationDbContext class.
services.AddDbContext<DbContext>

to
services.AddDbContext<ApplicationDbContext>


text:
Q: Sem idéias para lógica de Load Pedi ajuda recentemente neste tópico> Separar todos os itens de uma string
O problema é que, o meu jogo é um Card-Game offline que tem um "inventário" de cartas, só que eu não faço a minima ideia de como eu faço pra de fato "colocar as cartas no inventário".
Eu pensei inicialmente em guardar as cartas através de números, como eu mostro no tópico acima.
Só que como eu "guardo" as cartas in-game pra eu usar?
Eu tenho uma form aonde eu chamo de "Meu Time" que ficam os 5 slots das cartas e eu seleciono (em cada slot) uma carta através de uma combo-box, são divididas em:
Top
JG
Mid
Adc
Sup
Cada um é uma combobox.
Até agora eu tenho um código que carrega um save que divide as cartas através de números, agora, como eu faço pra transformar os números em dados para as combobox?
O código de load é esse:
  Dim bar() As String
    Dim foo() As String
    Dim i As Byte

    bar = Split("Nome|1,2,3,4,5,6,7,8,9|59000|50%", "|")

    foo = Split(bar(1), ",")

    For i = LBound(foo) To UBound(foo)
      Dim cartaAtual as string = foo(i)
    Next i

Como eu faço pra dividir número por número e colocar eles na Combobox?
Preciso de ajuda pra achar uma lógica.


text:
Q: wrap inherited classes in Python Let's say I have a number of inherited classes
class Bird:
    def __init__(self):
        pass
    def identify(self):
        print("I am a generic bird!")

class Falcon(Bird):
    def __init__(self):
        super(Eagle, self).__init__()
    def identify(self):
        print("I am a Falcon!")

class Eagle(Bird):
    def __init__(self):
        super(Eagle, self).__init__()
    def identify(self):
        print("I am an Eagle!")

This allows me to create, e.g., a Falcon using
A = Falcon()
A.identify

I am a Falcon

What I would like to have now is something like a wrapper class, which allows me to choose the kind of bird using a flag. Specifically, I want this behavior
A = BirdSelector(which="Falcon")
A.identify
B = BirdSelector(which="Eagle")
B.identify

I am a Falcon!
I am a Eagle!

In short, A = BirdSelector(which="Eagle") is supposed to create an instance of Falcons just as if I had called A = Falcon(). What is the most pythonic way to do this? Can someone give a hint how to implement BirdSelector?


text:
Q: Long-running tasks in AKKA actors What is the best way to implement long running tasks in AKKA actors?
Examples for long-running tasks:
1) File IO
2) Multimedia (Video/Audio) IO
If I let an Actor record from a microphone or play a sound/song to the speakers it has to block a thread. But - as far as I understand AKKA Actors - this blocked Actor does not react from any messages from outside. Thus I don't have the possibility to interrupt (or pause) my long running task.
Is there a standard way to achieve my goal? Or are Actors the wrong model for this certain kind of tasks?

A: Use the new Akka IO (coming in 2.2.0, now in RC1), it offers non-blocking message-driven TCP & UDP for Actors.
http://doc.akka.io/docs/akka/2.2.0-RC1/scala/index-network.html
What you will generally do is to put things into chunks and handing one chunk at a time, not blocking for the next chunk.


text:
Q: Installing IIS on Windows from Ansible My ansible is configured on my host machine - Linux 16.06 LTS and i am successfully able to ping my server using the ansible windows -m win_ping command.
Now im trying to install IIS on my server. I have created a YAML file in my group_vars folder called installIIS.yml.
---
- name: Install IIS
  hosts: windows
  gather_facts: true
  tasks:
   - win_feature:
     name: "windows"
     state: present
     restart: yes
     include_sub_features: yes
     include_management_tools: yes

and im running the yml file by: root@SAUPRDSVR01:/etc/ansible# ansible-playbook group_vars/installIIS.yml
and the error i received is
ERROR! 'include_sub_features' is not a valid attribute for a Task

The error appears to have been in '/etc/ansible/group_vars/installIIS.yml': line 6, column 6, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
   - win_feature:
     ^ here

Any help regarding this. I would also like to install antivirus, tripwire and also check for windows updates from ansible.
/etc/ansible# tree
.
├── ansible.cfg
├── group_vars
│   ├── installIIS.yml
│   ├── linux.yml
│   └── windows.yml
├── hosts
└── roles

Any help or links for this. Thank you in advance.

A: I think the issue is the indent level where you are specifying the options for win_feature. The options should be indented under the win_feature module, as opposed to on the same level.
example:
---
- name: Install IIS
  hosts: windows
  gather_facts: true
  tasks:
   - win_feature:
       name: "web-server"
       state: present
       restart: yes
       include_sub_features: yes
       include_management_tools: yes

win_feature documentation for the reference

A: if you are installing IIS then name of win_feature should be correct:

*

*name: Install IIS
hosts: windows
gather_facts: true
tasks:

*

*win_feature:
name: Web-Server
state: present
restart: yes
include_sub_features: yes
include_management_tools: yes


text:
Q: Ace Editor Custom Syntax This is my last attempt before I completely give up. I am trying to use the Ace Editor; so far it has worked really well for existing languages but I do not find the documentation good enough to guide me on how to create a custom syntax highlighter.
I know this is a very broad question, but can anybody point me in the right direction of a decent tutorial or some pointers on how the hell to get this custom highlighter working!?
The Ace Editor tutorial just mentions two files, doesn't really explain the content very well, where to put the files (as the lib/ace/mode folder doesn't exist in the pre-packaged version), or how to change the formatting etc.
Appreciate any help.

A: If you want to write your mode in packed mode, then you need to copy one of existing mode files, rename it to mode-mymode.js and use define("ace/mode/mymode", define("ace/mode/mymode_highlight_rules" instead of using several files


text:
Q: BigQuery multiple rows update in a single job I have two arrays one is for values I want to update and one is for where statement.
This is a list of usernames:
[
  '4feathersandfur',       '4flyman',
  '4iisx',                 '4lergico_',
  '4mygal',                '4mygal',
  '4mygal',                '4mygal',
  '4mygal',                '4mygal',
  '4mygal',                '4ringzryan',
  '4summeror4ever',        '5.by',
  '5.by',                  '5.by',
  '5.by',                  '5.by',
  '5.vt',                  '5.vt',
  '5.vt',                  '5.vt',
  '5.vt',                  '5.vt',
  '5.vt',                  '5.vt',
  '501_f',                 '502_nesha',
  '5050_therealvito',      '50_shades_of_dramatic',
  '50_shades_of_dramatic', '50tonsdesono_',
  '526ha',                 '5588fatima',
  '5588fatima',            '559ac',
  '55sommy55',             '55sommy55',
  '58_q8',                 '5_alsheh7i.94'
]

This is a list of new_ig_followers_count
[
  '1001', '1000', '1001', '1000',
  '1000', '1000', '1000', '1000',
  '1000', '1000', '1000', '1001',
  '1001', '1000', '1000', '1000',
  '1000', '1000', '1001', '1001',
  '1001', '1001', '1001', '1001',
  '1001', '1001', '1000', '1000',
  '1001', '1001', '1001', '1001',
  '1001', '1001', '1001', '1000',
  '1001', '1001', '1000', '1001'
]

I want a single job to update all the rows with those usernames with their corresponding follower's count is it possible to do it in a single job.
Schema of the table is
Field name  Type    Mode    Description
username    STRING  NULLABLE
website STRING  NULLABLE
description STRING  NULLABLE
url STRING  NULLABLE
followed_by INTEGER NULLABLE
email   STRING  NULLABLE
new_ig_followers_count  INTEGER NULLABLE
updated_at  TIMESTAMP   NULLABLE
IG_alive    BOOLEAN NULLABLE

A: Below is for BigQuery Standard SQL
UPDATE `instagramdata.instagram.40_50_followers`
SET
  new_ig_followers_count = followersCount,
  updated_at = CURRENT_TIMESTAMP(),
  IG_alive = TRUE
FROM (
  SELECT [
    '4feathersandfur',       '4flyman',
    '4iisx',                 '4lergico_',
    '4mygal',                '4mygal',
    '4mygal',                '4mygal',
    '4mygal',                '4mygal',
    '4mygal',                '4ringzryan'
  ] AS usernameArray,
  [
    '1001', '1000', '1001', '1000',
    '1000', '1000', '1000', '1000',
    '1000', '1000', '1000', '1001'
  ] AS followersCountArray
),
UNNEST(usernameArray) AS Name WITH OFFSET
JOIN UNNEST(followersCountArray) AS followersCount WITH OFFSET
USING(OFFSET)
WHERE username = Name

A: As I have not got a way to do this not in a single job
function currentTimeStamp() {
  var dateTime = new Date().toUTCString();
  dateTime = "'" + moment(dateTime).format("YYYY-MM-DD HH:mm:ss") + "'";
  return dateTime;
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function query(usernameArray, followersCountArray) {
  for (let i = 0; i < usernameArray.length; i++) {
    await sleep(10000)
    console.log("usernameArray, followersCountArray", usernameArray[i], followersCountArray[i])
    const query = `UPDATE \`instagramdata.instagram.40_50_followers\`
          SET new_ig_followers_count = ${followersCountArray[i]}, updated_at = ${currentTimeStamp()}, IG_alive = true
          WHERE username = ${usernameArray[i]}`;
    const options = {
      query: query,
    };
    const [job] = await bigquery.createQueryJob(options);
    console.log(`Job ${job.id} started.`);
    const [rows] = await job.getQueryResults();
    console.log('Rows:');
    rows.forEach(row => console.log(row));
  }
}

I am able to update rows using this function query for all the usernames in the usernameArray. I am open to know a solution to update all rows in a single job


text:
Q: Selecting PCA components which separate groups I frequently used to diagnose my multivariate data using PCA (omics data with hundreds of thousands of variables and dozens or hundreds of samples). The data often come from experiments with several categorical independent variables defining some groups, and I often have to go through a few components before I can find the ones that show a separation between the groups of interest. I have came up with a rather primitive way of finding such discriminating components, and I wonder

*

*to what extent this is reasonable / justifiable, and

*whether there are better ways of achieving the same.

Note that this is exploratory. Before I convince anyone else, I want to convince myself. If I see that there are components that clearly distinguish the groups of interest (e.g. control vs treatment), even if they are responsible for a minor portion of the variance of the responses, I trust it more than a result from, say, supervised machine learning.
Here is my approach. I will use the "metabo" example data set from pca3d in R.
The idea is to assess how much variance of each of the component can be explained by the independent variable. For this, I calculate a simple model for each component and use $R^2$ as a metric to order the components from "most interesting" to "least interesting".
require( pca3d )
# data on metabolic profiles of TB patients and controls
data( metabo )
# first column is the independent variable
pca <- prcomp( metabo[,-1], scale.= T )

# create a model for each component
lm.m <- lm( pca$x ~ metabo[,1] )
lm.s <- summary( lm.m )
lm.r2 <- sapply( lm.s, function( x ) x$r.squared )
plot( lm.r2, type= "l" )
text( 1:length( lm.r2 ), lm.r2, 1:length( lm.r2 ), pos= 3 )

Here is the result. The plot shows the percentage in variance of each component explained by the independent variable in metabo[,1].

We can sort the components by $r^2$ to find out which ones to display with order( lm.r2, decreasing= TRUE ); the first three components are 2, 1 and 7.
pca3d( pca, components= c( 1, 2, 7 ), group= metabo[,1] )

Here is the plot:

(The red and green categories are two groups of subjects who are not patients, and it is to be expected that they cannot be distinguished.)
To reformulate my questions,

*

*Does this approach make sense to you? My problem is that it looks too much like data dredging. Also, intuitively I think maybe I should turn the table and ask what part of the variance in the independent variable is explained by each variable? Finally, I'm (almost) sure that I am reinventing the wheel, poorly, so my second question is

*Is there anything better?

Note that I do not want to switch to partial least squares or anything similar at this stage; I just want to diagnose the PCA in the context of my classification.

A: The answer to your question #1 is yes, your solution amounts to data dredging. The answer to your question #2 is yes, there are superior methods in the literature.
The central problem with your approach is that you are not addressing the high-dimensional data problem, i.e. problems that arise when $n << p$. Your solution is quite arbitrary and lacks any sort of theoretical justification: I will point you to some literature that can help you find adequate methods below.
You are running an analysis that resembles principal components regression, except that you have swapped your independent and dependent variables, resulting in a large multivariate (as opposed to multiple) regression analysis. Multivariate regression requires that your sample size be larger than the number of dependent variables, a requirement which you are thoroughly violating in your example.
If you are truly committed to running PCA on your data and then using multivariate regression, you must use an appropriate method. For example, look into MRCE and related methods [1].
However, despite a few puzzling comments you have made, everything in your analysis as currently presented suggests that your ultimate goal is to identify relationships between a large set of continuous variables (metabo[,-1]) and a single categorical variable (metabo[,1]). PCA is a poor way of accomplishing this. There are two general classes of solutions to this problem in the high-dimensional case: first, solutions that assume sparsity, and solutions that assume a factor structure.
Sparsity-based solutions typically assume that only a very small proportion of variables are in fact related to the categorical variable of interest, and attempt to find this small subset; for example see DALASS [2]. Factor-structure-based methods assume that your discriminator variables are manifestations of underlying latent variables with a true relationship to the categorical variable. An example of this class of methods is DLDA [3].
Note that I am not necessarily recommending any methods I have mentioned for your data; you must carefully consider your goals and a priori knowledge of the problem in selecting an appropriate method.
[1] Rothman, Levina, Zhu (2010). Sparse Multivariate Regression With Covariance Estimation. Journal of Computational and Graphical Statistics, Volume 19, Number 4, Pages 947–962.
[2] Nickolay T. Trendafilov, Ian T. Jolliffe, DALASS: Variable selection in discriminant analysis via the LASSO, Computational Statistics & Data Analysis, Volume 51, Issue 8, 1 May 2007, Pages 3718-3736.
[3] Yu, Yang (2001). A direct LDA algorithm for high-dimensional data with
application to face recognition. Pattern Recognition 34, 2067-2070.

A: @ahfoss already pointed you to LDA as the classification analogon to PCA. Actually, these two methods are related to each other and also to PLS:
nature of dependent variable (for supervised)     unsupervised    supervised
or structure of data (unsupervised)
continuous                                        PCA             PLS
factor/groups/classes                                             LDA

The relation is in the projection: PCA projects data so that the variance-covariance matrix of the scores will be $\mathbf I$. LDA does a similar projection, but instead of the variance-covariance matrix of the whole data set, the pooled within-class variance-covariance matrix becomes $\mathbf I$.
As @ahfoss also said, the usual LDA is not feasible for $n \ll p$. But PLS-LDA is a feasible way of dealing with that, see e.g.  Barker, M. & Rayens, W.: Partial least squares for discrimination, J Chemom, 17, 166-173 (2003). DOI: 10.1002/cem.785 (this paper also discusses the relation between PLS and LDA).
PLS can be seen as a regularization like the LASSO, and also sparse PLS is available (though I haven't used it: my data is more suitable to normal PLS, which doesn't assume sparsity). For a nice discussion of different regularization methods, see e.g. the Elements of Statistical Learning.
One nice property of doing PLS-LDA is that you can write the final model in bilinear form if you take care to use the same centering for both steps. This allows to interpret the model just the same way you'd interpret the LDA model that you could calculate if you had more cases and $n \gg p$. (In case you're forced to do PCA, this applies for PCA-LDA as well).
Say, PLS scores $\mathbf T = $ data matrix $\mathbf X \times$ PLS weights $\mathbf W$ and
for a usual LDA, the scores $\mathbf L = $ data matrix $\mathbf X\times$ LDA coefficients $\mathbf B$.
Then doing the LDA in PLS (X-)score space, we get:
$\mathbf L'^{(n \times k - 1)} = \mathbf T^{(n \times m)} \mathbf B'^{(m \times k - 1)}$
$\phantom{\mathbf L^{(n \times k - 1)}} =  \mathbf X^{(n \times p)} \mathbf W^{(p \times m)} \mathbf B'^{(m \times k - 1)}$
$\phantom{\mathbf L^{(n \times k - 1)}} =  \mathbf X^{(n \times p)} \mathbf B''^{(p \times k - 1)}$
The dashes mark that these LDA scores ($\mathbf L'$) may be (slightly) different from LDA scores you'd obtain without regularization, and so are the coefficients $\mathbf B''$. $\mathbf B'$ will be very different from $\mathbf B$ as they apply to PLS score space and not to the original data space.
Practical note: in case you work in R, I have a package under development that provides PLS-LDA and PCA-LDA models. Let me know if you'd like to give it a try.

In order to avoid data dredging, you need to validate your final model (= measure its performance) with independent data.
Independent here means that this case (patient?) did not contribute to the model fitting in any way. In particular,

*

*did not enter any kind of preprocessing that involves multiple cases, such as centering or standardization

*did not enter the PCA/PLS/... calculation.

*was not used for hyperparameter estimation.

As you have only few cases, a resampling strategy would be appropriate. In this situation, it is probably best to fix any hyperparameters (like number of PCs or PLS latent variables, or the LASSO bound) by external knowledge in order to avoid a second, inner split of your training data for the optimization of the hyperparameter.


text:
Q: measure the total transmitted byte sent/received in the HttpRequest/Response in servlets I want to measure the total transmitted bytes for request and response in servlets.
In addition, bytes sent for response and bytes received for request(http get and post methods).
What will be the elegant way to achieve this?
assume, i'm writing to a HTML content output from servlet.In that output, css styles and JavaScript files get involved. How do I get the exact size of bytes sent in the response?
StringBuilder htmlcontent = new StringBuilder("");
.append("<!DOCTYPE html>")
                    .append("")
                    .append("")
                    .append("<title>Sample Page</title>")
                    .append("<link rel=\"stylesheet\" href=\"css/foundation-5.4.css\" />")
                    .append("")
                    .append("")
                    .append("")
                    .append("")
                    .append("")
                    .append("");

response.getOutputStream().write(htmlcontent).getBytes("UTF-8");

A: Every container has the support to log web requests. You should be able to log the following:

*

*request url

*HTTP Method

*Response status code

*Response size

*Request size.

For tomcat here is how you can do,
http://www.techstacks.com/howto/configure-access-logging-in-tomcat.html


text:
Q: Lock down PC so only a few programs can be used? I'm interested in locking down my PC so that only a few programs can be used.
For example, when I'm writing a paper I only want to be able to use Word.  No Firefox or DVD player because I will be distracted.
I want to have various modes (one for writing a paper, another for doing taxes) that will prevent me from using any program except for the ones I need to perform a task.
Is there a program that will do that?  Can be free or commercial.

A: Found this:

Clean Slate security goes beyond just clearing unwanted changes. You can also block programs from running. Clean Slate reads and lists all the programs in your start menu. While in the Clean Slate configuration screen, simply select the programs you want blocked. Once configured, the programs can not be accessed. Not only will Clean Slate block the execution of any presently installed programs but also unknown programs from the Internet and removable media (USB drives, CD ROM, network shares, floppy disks, etc.).

http://www.fortresgrand.com/products/cls/cls.htm

A: To avoid distractions from open applications you can remove them from the taskbar and the task switcher (ALT + TAB) by using
Process Manager for Windows.
When it is running you can hide an application by right-clicking in the task bar and select "Hide Me".

A: If you are using Windows XP or Vista you can lock it down using Windows Steady State. It works really well.  It is free.
If you want to have different profiles you could set different users with different privileges.
http://www.microsoft.com/windows/products/winfamily/sharedaccess/default.mspx


text:
Q: Ring Homomorphism unit to unit mapping Fraleigh defines a ring homomorphism $\phi:R \to R'$ as a map $\phi$ such that
$$\phi(x+y) = \phi(x) + \phi(y)$$
and
$$\phi(xy) = \phi(x) \phi(y).$$
As such, it must follow directly from the definition that $\phi(e) = \phi(e \cdot e) = \phi(e) \phi (e) \implies \phi(e) = e'$ and that unity should map to unity. However, under these conditions $\phi: \mathbb{Z}_3 \to \mathbb{Z}_6$ such that $\phi(1) = 4$ is also a viable ring homomorphism. But $4$ is not unity in $\mathbb{Z}_6$ - could someone please explain this apparent contradiction?
I feel like I'm doing something wrong, because some people explicitly write that $f(1_S) = 1_R$ when defining a ring homomorphism, and then why would they do that if it follows directly from another property?


text:
Q: ASP.Net MVC: Session duration? Due to the complex business logic, I had to implement myself the authentication. I'm storing the authentication with:

FormsAuthentication.SetAuthCookie(identifier,false);

The False is to indicate that we don't want to have persistent cookie
I've to also store in session some informations(one information that the user has to enter to login, indicating for which set of data he wants to access).
I'm storing those data through model binder.
It's working fine most of the time. But sometime after an inactivity period, we are still logged but we don't have any data in session.
I would like that the duration of my session is the same than the login session, to avoid this kind of "I'm logged but I've lost some data in the session".
I don't need/want to have a persistent connection.
How should I proceed to have this system?

A: I believe the FormsAuthentication uses its own timeout. You can configure your web.config accordingly:
<system.web>
    <authentication mode="Forms">
          <forms timeout="50"/>
    </authentication>

    <sessionState timeout="50"  />
</system.web>

A: In fact, There was a Session timeout by default in the IIS Application pool, so, to avoid this problem:

*

*Go on IIS Manager

*Go on the ServerName/Application Pools tab

*Right click on the concerned application pool

*Click on Advanced Settings,

*In the section "Process Model", put an higher value in the "Idle Time-out"(this is in minutes

*Click on OK

*Restart the application pool

For me, this + the Yannis config(setting the same value for the form timeout+session state timeout) worked.


text:
Q: Post to facebook page from facebook page tab app I want to post activities from page tab app to my own facebook page. I referred many documents to post message to app.
My php code :
    $GLOBALS["facebook"] = new \Facebook_Facebook(array('appId'  => $facebook_app_id, 'secret' => $facebook_secret,));

    $page_info = $GLOBALS["facebook"]->api("/pageid?fields=access_token");
    print_r($page_info);die;
    if (!empty($page_info['access_token'])) {
        $args = array(
                'access_token' => $page_info['access_token'],
                'message' => 'TEST'
        );

        $postId = $facebook->api("/pageid/feed", "post", $args);

But pageinfo variable has only id. I'm not getting access_token. Any idea what else need to be done?

A: We need manage_pages permission which we can get it using https://www.facebook.com/dialog/oauth?client_id=client_app_id&client_secret=9ea3e2eff7c65b1fcf1a633da&redirect_uri=YOUR_REDIRECT_URL&scope=read_stream,publish_stream,offline_access,manage_pages.
After that using above code we will get access token which can be used to publish to our page


text:
Q: Rails select options tag - generating options from associations I have a view that allows the user to add list_items to one of their shopping_lists. I want the options for select to be the names of their lists, but I need those names mapped to respective list_id in order to have the correct associations. Here's my current select tag:

  <% item.inventory_items.each do |product| %>

      <%= form_tag("/list_items", method: "post") do %>
      <%= hidden_field_tag(:item_id, item.id) %>
      <%= hidden_field_tag(:inventory_item_id, product.id) %>
      <%= select_tag(:shopping_list_id, options_for_select(current_user.shopping_lists)) %>
      <%= submit_tag("$#{product.price}", class: "btn btn-primary") %>
      <% end %>

  <% end %>

How can I display the names of a user's shopping_lists as the options, but return the relative shopping_list_id as the value for that option?
ShoppingList belongs_to :user
User has_many :shopping_lists
Currently my select tag renders a dropdown selection of a user's shopping lists, but the options are listed in the form, '#. Clicking the submit button doesn't actually add the the item to the list either.
Thanks in advance!

A: As you can see in Rails Api documentation:
options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
# => <option value="$">Dollar</option>
# => <option value="DKK">Kroner</option>

options_for_select receives an Array of Arrays. Inner Arrays are only two elements: ["name", "value"].
You can create a class method in your ShoppingList model as follows:
def self.options_for_list(shopping_lists)
  shopping_lists.map do |sl|
    [ sl.name, sl.id ]
  end
end

It returns the Array you need, then:
<%= select_tag :shopping_list_id, options_for_select(ShoppingList.options_for_list(current_user.shopping_lists)) %>

EDIT:
Or use a helper method:
def shopping_list_select_tag(shopping_lists, options = {})
  select_options = shopping_lists.map do |sl|
                     [ sl.name, sl.id ]
                   end
  select_tag :shopping_list_id, options_for_select(select_options), options
end

Then,
<%= shopping_list_select_tag current_user.shopping_lists %>


text:
Q: Why page number in libre writer shown as grey-background text "page numbers"? After I clicked Insert->Fileds-> Page Numbers, I get a grey-background literal "page numbers" instead of a number. (Environment: LibreOffice 3.5.7.2, Ubuntu 14 LTS.)

When I double clicked that grey text "page numbers", Edit Fields: Document dialog is opened. I tried style Arablic(1 2 3) and As Page Style, the problem still exist.
How can I have the real number (e.g, arabic number)?

A: There's an option to toggle between the field value and the field name - in your case, it seems that LO is displaying the field name instead of the field value. You can change it on different, alternative  ways:

*

*CTRL+F9;

*Menu "View" -> "Field Names";

*Menu "Tools" -> "Options" -> "LibreOffice Writer" -> "View" -> disable "Field Codes".

(tested with LO 4.2.6.3 and Ubuntu 14.04 LTS)

A: The gray background is simply there to denote a field. This background is not printed. Choose View > Field Shadings (or press Ctrl+F8) to turn this feature off.


text:
Q: Convert parent/child php array to html table I have the following PHP array.
Array
(
 [168] => Array
    (
        [link] => asdfasdf
        [children] => Array
            (
                [239] => Array
                    (
                        [link] => tascatestlalal
                        [children] => Array
                            (
                            )
                    )
                [240] => Array
                    (
                        [link] => otrotestttt
                        [children] => Array
                            (
                            )
                    )
            )
    )
[229] => Array
    (
        [link] => Sub-task ex
        [children] => Array
            (
            )
    )

[230] => Array
    (
        [link] => Sub-task test
        [children] => Array
            (
                [231] => Array
                    (
                        [link] => tasktest1
                        [children] => Array
                            (
                            )
                    )
                [232] => Array
                    (
                        [link] => tasktest 2
                        [children] => Array
                            (
                                [233] => Array
                                    (
                                        [link] => tasktest 5
                                        [children] => Array
                                            (
                                                [235] => Array
                                                    (
                                                        [link] => tasca235
                                                        [children] => Array
                                                            (
                                                            )
                                                    )
                                            )
                                    )
                            )
                    )
                [234] => Array
                    (
                        [link] => tasca234
                        [children] => Array
                            (
                            )
                    )
            )
    )
 )

and I need to convert it into this

 Sub-task

 --Tasktest1

  --tasktest 2

  ---tasktest 5

  ----tasca235

  --tasca234

this I already know how to do it with a list with this function, but cant seen to modify  this function to transform it into the table example above :( . some help will be greatly appreciated
function ArrayToHTMLList($arr) {
$str = "
";
foreach($arr as $key => $value) {

        if((!empty($value))){

          $str .="
";

            if(is_array($value))
                  $str .= ArrayToHTMLList($value);
            else
                $str .= $value;

          $str .= "
";
        }

}

$str .= "
";
return $str;
}

A: function nestedArrayToFlatList($node, $indent) {
  $str = '';

  if (isset($node['link'])) {
    $str .= '
' . $indent . $node['link'] . '
';
  }

  if (isset($node['children']) && count($node['children']) > 0) {
    foreach ($node['children'] as $child) {
      $str .= nestedArrayToFlatList($child, '--' . $indent);
    }
  }

  return $str;
}

$myList = '
' . nestedArrayToFlatList($myMassiveArray, '') . '
';