text:
Q: Two confusions about torsion-free coherent sheaves (EDIT: Beware, my definition of torsion-free is incorrect below. The correct one is to say $\mathcal{F}$ is torsion-free if for all $x \in X$, and all $s \in \mathcal{O}_{X,x}-\{0\}$, the multiplication by $s$ map $\mathcal{F}_{x} \to \mathcal{F}_{x}$ is injective.  This resolves the issue.)
Let $X$ be an integral Noetherian scheme, and let $\mathcal{F}$ be a coherent sheaf on $X$.  One can consider the morphism of $\mathcal{O}_{X}$-modules
$$\mathcal{O}_{X} \to \mathcal{H}om_{\mathcal{O}_{X}}(\mathcal{F}, \mathcal{F})$$
mapping a function $f \in \mathcal{O}_{X}(U)$ to the multiplication by $f$ map $\mathcal{F}|_{U} \to \mathcal{F}|_{U}$.  The kernel is called the annihilator ideal sheaf, and the corresponding closed subscheme is $\text{Supp}(\mathcal{F})$.
I want to define $\mathcal{F}$ to be torsion-free when the annihilator ideal sheaf vanishes, and torsion otherwise.  I'm able to show that:

*

*If $\mathcal{F}$ is torsion-free, then $\text{Supp}(\mathcal{F})=X$.

*$\mathcal{F}$ is torsion-free if and only if $\mathcal{F}_{x}$ is a torsion-free $\mathcal{O}_{X,x}$-module for all $x \in X$.

*$\mathcal{F}$ is torsion-free if and only if it has no non-trivial torsion subsheaves.
Now, the converse of (1) is obviously false: if $\mathcal{F} = \mathcal{L} \oplus \mathcal{O}_{p}$ is the direct sum of a line bundle and skyscraper sheaf, then $\text{Supp}(\mathcal{F})=X$, but $\mathcal{F}$ is not torsion-free.  However, since the annihilator ideal sheaf should be the ideal sheaf corresponding to X, it must be zero?  Contradicting that $\mathcal{F}$ isn't torsion-free?  Moreover, in this example above, it seems like the annihilator ideal sheaf should vanish at all stalks except $p \in X$.  Which cannot happen for an ideal sheaf.  Where am I going so badly wrong here?  Is it related to support vs. scheme-theoretic support?
My second confusion is with showing that my definition of torsion-free is equivalent to the rank $rk(\mathcal{F}) = dim_{\mathcal{O}_{X, \eta}}\mathcal{F}_{\eta}$ being larger than zero, where $\eta \in X$ is the generic point.  I think its clear that my definition implies this one.  But conversely, how can one show that $\mathcal{F}_{x}$ is torsion-free for all $x \in X$ just from this data at $\eta \in X$?  I know that all open sets of $X$ contain $\eta$; it must be using that somehow?


text:
Q: Firebase dependencies create errors on runtime Error: Type com.google.android.gms.common.internal.zzf is referenced as an interface from `com.google.android.gms.internal.zzcar`.

Continuously getting same issues whatever I am trying. Nothing work.
Java Compiler:
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /Users/.gradle/caches/transforms-1/files-1.1/play-services-gass-11.0.4.aar/c9497d6850772046db2c4c9a12ec798a/jars/classes.jar

Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.

Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete

Caused by: com.android.tools.r8.utils.AbortException: Error: Type com.google.android.gms.common.internal.zzf is referenced as an interface from `com.google.android.gms.internal.zzcar`.

build.gradle(app):-
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.libraries.places:places:1.0.0'

implementation ('com.google.firebase:firebase-core:16.0.8'){
    exclude group: 'com.google.android.gms'
}

implementation ('com.google.firebase:firebase-messaging:17.5.0'){
    exclude group: 'com.google.android.gms'
}
implementation 'com.firebase:firebase-client-android:2.5.1'

build.gradle(project):-
dependencies {
    classpath 'com.android.tools.build:gradle:3.3.2'
    classpath 'com.google.gms:google-services:4.2.0'
    classpath 'io.fabric.tools:gradle:1.25.4'
}

If anyone know where I am going wrong, please help me to resolve this.
Thanks in Advance!!

A: Just this should work:
dependencies {
 // ...
 implementation 'com.google.firebase:firebase-core:16.0.8'
}

A: For the people who got this issue when trying to use Firebase and AdMob together, check the below link in Ionic Forum.
https://forum.ionicframework.com/t/using-firebase-and-admob-free-together/117650/2?u=vigamage
Issue is caused by the different play services versions used by the plugins.
For example, firebase plugin always use the latest. But AdMob free plugin uses a specific version. (11.0.4)
To fix it, instruct the AdMob plugin to use the latest version by doing below in admob sdk plugin.xml.
<platform name="android">
        <framework src="com.google.android.gms:play-services-base:+" />
        <framework src="com.google.android.gms:play-services-ads:+" />
</platform>

Note that, After doing this, you might have to re-import some classes in Android Studio since the packages might be different in the latest version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Law of attraction Could you please explain that since we know Newton's law of Universal Gravitation says all masses attract each other. Thus, we humans should be attracted as well or any other daily life objects. Why is it that we don't feel that attraction to be prominent?

A: Lets calculate the force between $60$ kg boy and $50$ kg girl separated by $1$m (stricly speaking distance between their center of masses) in space. By Newton's law of gravity,
$$F=G\frac{M_1M_2}{r^2}$$
$$F=6.67X10^{-11}\frac{60X50}{1^2}=0.00000020010N$$
But remember, what Albert Einstein said "Gravitation can not be held responsible for people falling in love" :)
I hope the calculation explained you, why the attraction is not felt prominent.

A: Note that gravitational constant can be measured directly in the laboratory.
For example, the Cavendish experiment detects the force between two heavy metal (lead or gold or what have you) in a torsion balance.
It is only because the force is very small relative to other forces such as the pull of the rest of the earth that you do not notice it.
Note also that shape of the earth, e.g. mountains, also produce variations in earth gravity.

A: The gravitational force is proportional to the mass of each object.  The proportionality constant is incredibly small compared to other forces.  Thus, we only feel (and observe) gravity when the masses are very large (such as the earth, planets, the moon, and the sun).


text:
Q: How to loop through nested JSON data I am trying to loop through json data bellow, to so each element. I need to get down to the details data and then in side that loop through the f1,f2 into a div. I have tried using the index but that didn't work. Also I don't know how many f1,f2 there will be as it is returned from an api
JSON data
{
 "data":[
 {
   "title": "test",
   "image": "assets/imgs/test.png",
   "date": "22/07/2018 - 19.00",
   "location": "test",
   "details": [
     {
       "f1":[
         {
           "FunctioName": "test",
           "Time": "10:00:00"
         }
       ],
       "f2":[
         {
           "FunctioName": "test",
           "Time": "11:00:00"
         }
       ]
     }
   ]
  }
 ]
}

HTML

Date

{{item.date}}

Program

TS
import { Component } from '@angular/core';
import { App } from 'ionic-angular';
import { DataService } from "../../services/data";
import { LoginPage } from "../login/login";
import { AngularFireAuth } from "angularfire2/auth";
import { Storage } from "@ionic/storage";

@Component({
 selector: 'page-card',
 templateUrl: 'card.html',
})
export class CardPage {

 card:any;
 constructor(private dataservice: DataService, private afAuth:AngularFireAuth, private app:App, private storage:Storage) {

  this.dataservice.cardData().subscribe(
   data => {
    var jsonObj = JSON.parse(data["_body"]);
    this.card = jsonObj.data;
    console.log(jsonObj.data)
  }
 );
}

A: You can create an object which will hold the returned data from the api and you can just navigate the object values.
Example:
export class Class1 {
    data: Class2[];
}

export class Class2 {
    title: string;
    image: string;
    date: string;
    location: string;
    details: Class3[];
}

export class Class3 {
    f1: Class4[];
    f2: Class4[];
}

export class Class4 {
   FunctioName: string;
   Time: string
}

@Component({
 selector: 'page-card',
 templateUrl: 'card.html',
})
export class CardPage {

 card:Class1;
 constructor(private dataservice: DataService, private afAuth:AngularFireAuth, private app:App, private storage:Storage) {

  this.dataservice.cardData().subscribe(
   data => {
    this.card = data;
  }
 );
}

then in your component template

Date

{{item.date}}

Program


text:
Q: Ubuntu 16.04 LTS Radeon HD 7500M/7600M Series drivers I found a similar post it wasn't answered so I posted this since I have a similar problem
Since fglrx is not supported anymore on 16.04 and the amdgpu doesn't support HD7500M/7600M series we are in a wee bit of a pickle when using some softwares.
This is my card:
    otakupup@otakupup-HP-Pavilion-g6-Notebook-PC:~$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Thames [Radeon HD 7500M/7600M Series] (rev ff)
otakupup@otakupup-HP-Pavilion-g6-Notebook-PC:~$ sudo lshw -C video
  *-display
       description: VGA compatible controller
       product: 3rd Gen Core processor Graphics Controller
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 09
       width: 64 bits
       clock: 33MHz
       capabilities: msi pm vga_controller bus_master cap_list rom
       configuration: driver=i915 latency=0
       resources: irq:29 memory:63000000-633fffff memory:50000000-5fffffff ioport:5000(size=64) memory:c0000-dffff

and this what is supported by amdgpu:
SUPPORTED HARDWARE
   The radeon driver supports PCI, AGP, and PCIe video cards based on the following ATI/AMD chips
   (note: list is non-exhaustive):

   R100        Radeon 7200
   RV100       Radeon 7000(VE), M6, RN50/ES1000
   RS100       Radeon IGP320(M)
   RV200       Radeon 7500, M7, FireGL 7800
   RS200       Radeon IGP330(M)/IGP340(M)
   RS250       Radeon Mobility 7000 IGP
   R200        Radeon 8500, 9100, FireGL 8800/8700
   RV250       Radeon 9000PRO/9000, M9
   RV280       Radeon 9200PRO/9200/9200SE/9250, M9+
   RS300       Radeon 9100 IGP
   RS350       Radeon 9200 IGP
   RS400/RS480 Radeon XPRESS 200(M)/1100 IGP
   R300        Radeon 9700PRO/9700/9500PRO/9500/9600TX, FireGL X1/Z1
   R350        Radeon 9800PRO/9800SE/9800, FireGL X2
   R360        Radeon 9800XT
   RV350       Radeon 9600PRO/9600SE/9600/9550, M10/M11, FireGL T2
   RV360       Radeon 9600XT
   RV370       Radeon X300, M22
   RV380       Radeon X600, M24
   RV410       Radeon X700, M26 PCIe
   R420        Radeon X800 AGP
   R423/R430   Radeon X800, M28 PCIe
   R480/R481   Radeon X850 PCIe/AGP
   RV505/RV515/RV516/RV550
               Radeon X1300/X1400/X1500/X1550/X2300
   R520        Radeon X1800
   RV530/RV560 Radeon X1600/X1650/X1700
   RV570/R580  Radeon X1900/X1950
   RS600/RS690/RS740
               Radeon X1200/X1250/X2100
   R600        Radeon HD 2900
   RV610/RV630 Radeon HD 2400/2600/2700/4200/4225/4250
   RV620/RV635 Radeon HD 3410/3430/3450/3470/3650/3670
   RV670       Radeon HD 3690/3850/3870
   RS780/RS880 Radeon HD 3100/3200/3300/4100/4200/4250/4290
   RV710/RV730 Radeon HD 4330/4350/4550/4650/4670/5145/5165/530v/545v/560v/565v
   RV740/RV770/RV790
               Radeon HD 4770/4730/4830/4850/4860/4870/4890
   CEDAR       Radeon HD 5430/5450/6330/6350/6370
   REDWOOD     Radeon HD 5550/5570/5650/5670/5730/5750/5770/6530/6550/6570
   JUNIPER     Radeon HD 5750/5770/5830/5850/5870/6750/6770/6830/6850/6870
   CYPRESS     Radeon HD 5830/5850/5870
   HEMLOCK     Radeon HD 5970
   PALM        Radeon HD 6310/6250
   SUMO/SUMO2  Radeon HD 6370/6380/6410/6480/6520/6530/6550/6620
   BARTS       Radeon HD 6790/6850/6870/6950/6970/6990
   TURKS       Radeon HD 6570/6630/6650/6670/6730/6750/6770
   CAICOS      Radeon HD 6430/6450/6470/6490
   CAYMAN      Radeon HD 6950/6970/6990
   ARUBA       Radeon HD 7000 series
   TAHITI      Radeon HD 7900 series
   PITCAIRN    Radeon HD 7800 series
   VERDE       Radeon HD 7700 series
   OLAND       Radeon HD 8000 series
   HAINAN      Radeon HD 8000 series
   BONAIRE     Radeon HD 7790 series
   KAVERI      KAVERI APUs
   KABINI      KABINI APUs
   HAWAII      Radeon R9 series
   MULLINS     MULLINS APUs

AMDGPU-PRO supports newer cards only.
The drivers provided by AMD for Radeon™ HD 6000M and HD 5000M Series doesn't have support for 16.04
So my question/s are:

*

*Can I use the AMDGPU driver for my card although it ain't listed

*Can I use the 15.04 or earlier drivers for my version available for my card

*Is there anything else I can do other than switching my graphics card?


text:
Q: Umbraco 7 - Umbraco Forms checkbox stays always false In Umbraco 7.5.9 (and 7.5.9) i've encounter the following issue:
When saving my form, checkboxes are always posted as False
When viewing the record inside Umbraco, the values are False
When retrieving the field value, the value is False.
The recorddata in table UFRecords also shows json with false values for checkboxes
Example data in the database:
{'183fba08-5ed2-4a1a-8cc1-3364b0529e7e':'item 1, item 2','aec143aa-806c-43dd-9289-f9bcfb76065d':'False','eb357878-54cb-4a44-ba42-74959fd5b1cd':'False','a3491195-de34-47a9-dc1e-8bc5911dc604':'10-7-2018 00:00:00','7a19dfa1-98cb-4a08-b719-7fb5e96ea681':'Input 123','629e6d2f-10fd-4564-c6fc-30efc68ceb7a':'','f450c3ab-7fdd-4cc7-c246-d1171f4b983b':'No'}

Love to hear a working solution!

A: Tried upgrading to Umbraco Forms 4.4.7. After the second attempt I managed to get it working. Also running the package created by Tim helpt:
https://our.umbraco.com/forum/umbraco-pro/contour/60744-Entries-have-dissappeared#comment-206075
After restoring my bootstrap markup, new and old Umbraco Form were working again.


text:
Q: Error: Seg. Fault. Want to copy multiple files using multithreading ****** SOLVED ******
I wanted to copy multiple files using multi-threading. This ends in error: segmentation fault. Cannot figure out where.
What I tried: print("test"); on different lines, but gives me the same error. I think the main function is correct, something in the start_routine() block.
Code:
typedef struct filePair
{
    char srcName[100];
    char dstName[100];
} filePair;

void * start_routine(void *arg) //file handling using system calls
{
    char tmp;

    printf("Copying %s to %s.\n", ((filePair *)arg)->srcName, ((filePair *)arg)->dstName);

    int src = open(((filePair *)arg)->srcName, O_RDWR); //open source file
    if (!src)
    {
        printf("Cannot open source file.\n"); //error handling
        exit(0);
    }

    //open dst file
    int dst = open(((filePair *)arg)->dstName, O_WRONLY | O_CREAT, 0641);
    if (!dst)
    {
        printf("Error in destination file.\n"); //error handling
        exit(0);
    }

    while (read(src, &tmp, 1)) //while loop to copy contents
        write(dst, &tmp, 1);

    close(src); //close src and dst files
    close(dst);

    return NULL;
}

//main function...

A: The name of the type is struct filePair. A common way to make the usage of the type shorter is to incorporate a typedef:
typedef struct
{
    char src[100];
    char dst[100];
} filePair;

Then, you can refer to teh filePair type.

A: 1.cause of segmentation fault in code is improper usage of pointers.
creating pointers of type filePair and not allocating sufficient memory for those pointers will cause segmentation fault. If we allocate sufficient memory for those pointers, it won't be a problem anymore.

*prototype for pthread_create() is

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void
*(*start_routine) (void *), void *arg);

before passing *file1 in pthread_create() we should typecast file1 pointer to be of type
(void *).
Here I am providing a simple version without using pointers for filePair, but using filePair instances instead.
#include <stdio.h>     /* printf, stderr */
#include <sys/types.h> /* pid_t */
#include <unistd.h>    /* fork */
#include <stdlib.h>    /* atoi */
#include <errno.h>     /* errno */
#include <pthread.h>   /* pthread */
#include <sys/stat.h>
#include <fcntl.h> /* file handling */
#include <time.h>  /* CLOCK */
#include <string.h>

typedef struct
{
    char srcName[100];
    char dstName[100];
} filePair;

void * start_routine(void *arg) //file handling using system calls
{
    char tmp;

    printf("Copying %s to %s.\n", ((filePair *)arg)->srcName, ((filePair *)arg)->dstName);

    int src = open(((filePair *)arg)->srcName, O_RDWR); //open source file
    if (!src)
    {
        printf("Cannot open source file.\n"); //error handling
        exit(0);
    }

    //open dst file
    int dst = open(((filePair *)arg)->dstName, O_WRONLY | O_CREAT, 0641);
    if (!dst)
    {
        printf("Error in destination file.\n"); //error handling
        exit(0);
    }

    while (read(src, &tmp, 1)) //while loop to copy contents
        write(dst, &tmp, 1);

    close(src); //close src and dst files
    close(dst);

    return NULL;
}

/* main function */
int main(int argc, char *argv[])
{
    pthread_t thread1; //Threads init
    pthread_t thread2;
    pthread_t thread3;
    pthread_t thread4;
    pthread_t thread5;

    filePair  file1;
    strcpy(file1.srcName, "file1.dat");
    strcpy(file1.dstName, "copy1.dat");

    filePair  file2;
    strcpy(file2.srcName, "file2.dat");
    strcpy(file2.dstName, "copy2.dat");

    filePair  file3;
    strcpy(file3.srcName, "file3.dat");
    strcpy(file3.dstName, "copy3.dat");

    filePair  file4;
    strcpy(file4.srcName, "file4.dat");
    strcpy(file4.dstName, "copy4.dat");

    filePair  file5;
    strcpy(file5.srcName, "file5.dat");
    strcpy(file5.dstName, "copy5.dat");

    printf("\n Before threading.\n\n");

    //Creating threads
    pthread_create(&thread1, NULL, start_routine, (void *)&file1);
    pthread_create(&thread2, NULL, start_routine, (void *)&file2);
    pthread_create(&thread3, NULL, start_routine, (void *)&file3);
    pthread_create(&thread4, NULL, start_routine, (void *)&file4);
    pthread_create(&thread5, NULL, start_routine, (void *)&file5);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);
    pthread_join(thread4, NULL);
    pthread_join(thread5, NULL);

    printf("\n After threading.\n\n");

    return 0;
}


text:
Q: How to append a new list item with different css properties based on the priority I need to specify each list item with different color based on the priority if it is high then the background color will be red this is my code and i don't know whats wrong with it
   $("form").submit(function(e){
            var task = $('#task').val();
            var cat = $("#category").val();
            var prio = $("input[name=priority]:checked").val();
            var date = $("#date").val();
            var html ='<input type="checkbox" id="check">';
            var newtask = $("ul").append("
"+task+"
"+cat+"
"+prio+"
"+date+html+"
"+"
");
            if(prio == "high")
            {newtask.css({"background-color":"#ea9999","border-radius":"10px" , "margin-bottom":"30px" , "padding-left":"20px"});}
            if(prio == "medium")
            {newtask.css({"background-color":"#f8ca9c","border-radius":"10px" , "margin-bottom":"30px" , "padding-left":"20px"});}
            if(prio == "low")
            {newtask.css({"background-color":"#ffe498","border-radius":"10px" , "margin-bottom":"30px" , "padding-left":"20px"});}
            e.preventDefault();
          });


text:
Q: Python best practice in terms of logging When using the logging module from python for logging purposes. Is it best-practice to define a logger for each class?
Considering some things would be redundant such as file log location, I was thinking of abstracting logging to its own class and import an instance into each of my classes requiring logging. However I'm not sure if this is best practice or not?

A: Best practice is to follow Python's rules for software (de)composition - the module is the unit of Python software, not the class. Hence, the recommended approach is to use
logger = logging.getLogger(__name__)

in each module, and to configure logging (using basicConfig() or dictConfig()) from the main script.
Loggers are singletons - there is no point in passing them around or storing them in instances of your classes.

A: Use structured logging. Two great tools for this:

*

*Eliot: Logging that tells you why it happened

Most logging systems tell you what happened in your application,
  whereas eliot also tells you why it happened.
eliot is a Python logging system that outputs causal chains of
  actions: actions can spawn other actions, and eventually they either
  succeed or fail. The resulting logs tell you the story of what your
  software did: what happened, and what caused it.

*

*Structlog: structlog makes logging in Python less painful and more powerful by adding structure to your log entries.

Structured logging means that you don't write hard-to-parse and
  hard-to-keep-consistent prose in your logs but that you log events
  that happen in a context instead.

I've had very positive experiences with Eliot.

A: Use JSON or YAML logging configuration - After Python 2.7, you can load logging configuration from a dict. It means you can load the logging configuration from a JSON or YAML file.
Yaml Example  -
version: 1
disable_existing_loggers: False
formatters:
    simple:
        format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple
        stream: ext://sys.stdout

    info_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: INFO
        formatter: simple
        filename: info.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

    error_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: ERROR
        formatter: simple
        filename: errors.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

loggers:
    my_module:
        level: ERROR
        handlers: [console]
        propagate: no

root:
    level: INFO
    handlers: [console, info_file_handler, error_file_handler]

Ref -  Good-logging-practice-in-python


text:
Q: How to preserve generated content after back button pressed? There is some generated contents with the links on an ASP.NET page, which is created after the user inputs values and hits a button. The links take the user to another page.
When the user hits the Back button, the generated content is gone as the page returns to its initial state with the inputs cleared and generated content not there.
Is it possible to preserve the state of the page after its content has been generated and restore it after the Back button was clicked?

A: I think you can you can you temporary cookies.
and on load check whether cookie is exists or not.

A: Save the inputs in the session, so that the page will know how to correctly render on later requests. Even better, have the first code that runs when the data is submitted redirect to new page with a URL parameter that you use to know which links to show. This is a called a POST-REDIRECT-GET pattern.


text:
Q: Autotest not testing Autotest doesn't seem to be working for me.  I've installed what seem to be all the dependencies. When I make changes in my code, or force failures in tests, nothing happens while running autotest.
When I run autotest either just as 'autotest' or 'bundle exec autotest' I see the following:
(Not running features.  To run features in autotest, set AUTOFEATURE=true.)
loading autotest/rails_rspec2

Here is the excerpt from my GemFile:
gem "rspec-rails"
gem "cucumber-rails"
gem "webrat"
gem 'ZenTest'
gem 'test_notifier'
gem 'autotest'
gem 'autotest-rails'
gem 'autotest-fsevent'
gem 'autotest-growl'
gem 'redgreen'

The following is my discover.rb:
Autotest.add_discovery { "rails" }
Autotest.add_discovery { "rspec2" }

I'm on rails 3.0.0, ruby 1.8.7
Thanks for your help!

A: there have been a few updates to rspec2 lately with regards to autotest checkout the latest release and release notes


text:
Q: Scala: order of definition for companion object vs case class In Scala 2.9.1 I get the following behavior:
class Foo {
   case class X()
   object X            // this compiles

   def bar() {
      object Y         // this compiles
      case class Y()

      case class Z()
      object Z         // won't compile (see below)
   }
}

The compiler complains for Object Z:
    error: Z is already defined as (compiler-generated) case class companion object Z
It looks as if it is not permissible to define a companion object for a case class after the case class definition if they are within a function definition. Is this a compiler bug, or intentional? If the latter, why?

A: This is a known bug: SI-3772: companions and method-owned case classes. This is partially fixed, but the OP's issue still remains. Vote it up if you want it fixed.

A: The reason why the first is allowed and the second is not is that classes and objects can have forward definitions, but definitions cannot.  So why it is possible for the compiler to mix object X with the one defined by the case class, it is not possible to do so in the second case.
I wonder what happens in the Y case: shadowing or the object companion does not get generated at all?


text:
Q: Syntax difficulties in ajax I have a function connected with onclick button.
It sends some data through ajax to another php file.
Actually everything was working fine, but I tried to add now to 'success' a simple IF statement, that would get true or false from external file.
I guess some of the syntax may be wrong here because the error message says that my main fuction is not defined.
Could someone find some mistakes here please?
main file (here in success: i have added if else statement only):
              $.ajax({
              type: 'get',
              url: '/editcomment',
              data: {newComment: newComment,
                             id: id,
                         userId: userId},

              success:function(data){
                  if(data.success){
                       $(".newCommentForm" +id).replaceWith("" + newComment + "");
                       $(thisId).data("PinComment", newComment);
                   }
                   else { alert('error');},

              error:function(){
                       alert('error');
                     }
          });
      }

external file (i have added the return arrays here):
public function editComment(){

   $userId = Input::get('userId');

   if ( $userId == Auth::id() or Auth::user()->hasRole("admin")){

      $id = Input::get('id');
      $newComment = Input::get('newComment');
      DB::update('UPDATE `comments` SET f_text = ? WHERE h_id = ?', array($newComment, $id));
      return array('success' => true);

     } else {
         return array('success' => false);
     }
}

A: You have a typo here else { alert('error');},, you need another closing brace to close the success function.

A: You are trying to access PHP array in JS that not possible. What you need to do is, either you need to return response as an string or JSON from PHP file
see: Get data from php array - AJAX - jQuery

A: Get rid of commas. Try this in else block
jAlert('No Success', 'alert box');


text:
Q: CORS Issue: Response for preflight has invalid HTTP status code 403 Environment
Tomcat Server hosting webservice app.
Website is built using SpringMVC and AngularJS.
Core issue:
REST GET triggers OPTIONS request, which fails.
The GET in question returns an application/JSON response.
Initially, I got the error :
"Failed to load resource: the server responded with a status of 403 (Forbidden)

Failed to load http://myServer:8084/wsPRDE/navbar/getnavbartxt: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myServer:8080' is therefore not allowed access. The response had HTTP status code 403."

Prior to this problem, all we did was have @CrossOrigin in our Controllers. Then httpd.conf was set to add those headers. Which it did for all the script-retrieving from the site (ironically not CORS) but not for the actual CORS responses. When I ensured Access-Control- Allow-Origin, Allow-Methods and Allow-Headers were returned in the response, by coding a CORSFilter into the webservice, the error changed to :

"OPTIONS http://myServer:8084/wsPOFA/navbar/getnavbartxt 403 (Forbidden)
  Failed to load http://myServer:8084/wsPOFA/navbar/getnavbartxt: Response for preflight has invalid HTTP status code 403."

Background:
The error was detected in a rather random way.
A process management colleague of mine had a windows 10 update.
Since said update, the entire webservice fails because it can't be reached. Any request from the site itself to the webapplication (same address, different ports), fail. My superior (I'm an intern) then found that in Chrome and IE(when using Server alias, not when using the "normal" URL) have the same issue without the windows 10 update. Prior to the update (or when using IE with normal URL), the GET does not seem to trigger an OPTIONS request.
Further Attempts After this I've tried to expand the Allow-Headers to include all fields present in the GET request/response. I also compare the Origin in the OPTIONS request to a whitelist of Origins, setting the OPTIONS response Allow-Origin header value to the request Origin value if they match.
So the origins match and all the headers in the request/response are set to be allowed. I've spent 3 days so far reading up on CORS and looking for solutions on the web. Most solutions mention the CORS filter I've implemented, and then there are a ton of dirty-workarounds from clearing the header entirely, to always responding 200 OK to OPTIONS requests. But they seem very "dirty" solutions.
Can anyone point me in the right direction? Should I be looking at adding CORS-related code to my Spring Controllers? Is the delegation of constructing httpRequests to AngularJS the crux of my problems? Or am I thinking in the wrong direction entirely?
Currently, my request/response headers look like this:

A: This question got downvoted, probably because I wasn't exactly clearminded by the time I decided to ask for help. In any case, I managed to resolve the problem today. By the time I posted the question, I had already made a Custom CORS filter at the application level. Changing this filter to manually set the Status Code to 200 for Options if the Allow-Origin and Allow-Methods fields were set and only applying the chain.doFilter() on non-options requests resolved the issue. I'm a bit unsure if it's an ideal/safe solution. But it works. Below you can find the full solution used.
web.xml:
<filter>
    <filter-name>SimpleCORSFilter</filter-name>
    <filter-class>com.ofis.webservice.CORS.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SimpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Filter class:
package com.ofis.webservice.CORS;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleCORSFilter implements Filter {

    ArrayList<String> AllowedOrigins;
    ArrayList<String> AllowedMethods;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    if (request.getMethod().equals("OPTIONS")) {
        String reqOrigin;
        reqOrigin = request.getHeader("Origin");

        for (String origin : AllowedOrigins) {
            if (origin.equals(reqOrigin)) {
                response.setHeader("Access-Control-Allow-Origin", reqOrigin);
                break;
            }
        }

        String reqMethod;
        reqMethod = request.getHeader("Access-Control-Request-Method");

        for (String method : AllowedMethods) {
            if (method.equals(reqMethod)) {
                response.setHeader("Access-Control-Allow-Method", reqMethod);
            }
        }

        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "cache-control,if-modified-since,pragma,Content-Type");

        //Checks if Allow-Method and Allow-Origin got set. 200 OK if both are set.
        if(!response.getHeader("Access-Control-Allow-Method").equals("") && !response.getHeader("Access-Control-Allow-Origin").equals("")){
            response.setStatus(200);
        }
    } else {
        chain.doFilter(req, res);
    }


text:
Q: Progress bars not displaying information correctly My progress bars are always showing 100% that everything is full even when I hover over them its everything is 100/100 this is what I have as of now
energy = 100 & maxenergy = 100(when there full)
right now its energy = 50 & maxenergy = 100(there still showing 100% full)

/*energy bars*/
.bar_a{
    border: 1px solid #4CAf50;
    padding: 2px;
 width: 150px;
    height: 10;
 background-color: #ffffff;
    border-radius: 6px;

}

.bar_b{
 font-size: 10px;
    height: 10;
 background-color: #4CAF50;

}

for the php values I have
 $is = $db->query("SELECT `u`.*, `us`.* FROM `users` AS `u` INNER JOIN `userstats` AS `us` ON `u`.`userid`=`us`.`userid` WHERE `u`.`userid` = {$userid} LIMIT 1"); $ir = $db->fetch_row($is);

        $enperc = min((int) ($ir['energy'] / $ir['maxenergy'] * 100), 100);
        $enopp = 100 - $enperc;

and for the rest of the php as in the bars them self
Energy

'.$ir['energy'].'/'.$ir['maxenergy'].'('.$enperc.'%)

I have 4 different bars that's one of the 4 and they are all having the same issue one of them are even in the negatives and its still showing 100/100 (100%)


text:
Q: in swift, how do i get the string value from a print_r statement in php? print_r($response);

I have used Alamofire to call a GET request from php code that uses print_r (as above)
I use this to get the 'outputString' in Swift:
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)

however, I get an error if i use '.rangeOfString' to see if a string is in the response string, how do i do this?


text:
Q: Android listview images disappear when scrolling When scrolling my listview with images. The images will disappear then reappear a second or two later. Any help on the matter would be appreciated!
This is in my getView which calls the below code:
        image_main.setImageBitmap(null);
        if (curr == 0 && image != null) {

            list_image.setVisibility(View.VISIBLE);
            image_preference = preferences.getString("image_preferences", "false");
            time_right.setVisibility(View.GONE);
            if (image_preference.equals("false")) {
                 ImageDownloader imgDwn = new ImageDownloader();
                 imgDwn.download(image, image_main, image_table);
            }

My code:
public class ImageDownloader {

    public void download(String url, ImageView imageView, TableLayout imageTable) {
        if (cancelPotentialDownload(url, imageView)) {
        BitmapDownloaderTask task = new BitmapDownloaderTask(imageView, imageTable);
        DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
        imageView.setImageDrawable(downloadedDrawable);
        task.execute(url);
        }
    }

    class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
        String url;
        private final WeakReference<ImageView> imageViewReference;
        private final WeakReference<TableLayout> imageTableReference;

        public BitmapDownloaderTask(ImageView imageView, TableLayout imageTable) {
            imageViewReference = new WeakReference<ImageView>(imageView);
            imageTableReference = new WeakReference<TableLayout>(imageTable);
        }

          @Override
          protected Bitmap doInBackground(String... params) {
                 BitmapFactory.Options o = new BitmapFactory.Options();
                  o.inJustDecodeBounds = true;
                  BitmapFactory.decodeFile(params[0], o);
                  final int REQUIRED_SIZE=70;

                  //Find the correct scale value. It should be the power of 2.
                  int width_tmp=o.outWidth, height_tmp=o.outHeight;
                  int scale=4;
                  while(true){
                      if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                          break;
                      width_tmp/=2;
                      height_tmp/=2;
                      scale++;
                  }
                  //Decode with inSampleSize
                  BitmapFactory.Options o2 = new BitmapFactory.Options();
                  o2.inSampleSize=scale;
                  return BitmapFactory.decodeFile(params[0], o2);
          }

          @Override
          protected void onPostExecute(Bitmap result) {
                if (isCancelled()) {
                    result = null;
                }

                if (imageViewReference != null) {
                    ImageView imageView = imageViewReference.get();
                    TableLayout imageTable = imageTableReference.get();
                    BitmapDownloaderTask bitmapDownloaderTask = ImageDownloader.getBitmapDownloaderTask(imageView);
                    // Change bitmap only if this process is still associated with it
                    if (this == bitmapDownloaderTask) {
                          imageView.setImageBitmap(result);
                          imageView.setVisibility(View.VISIBLE);
                          imageTable.setVisibility(View.VISIBLE);
                    }
                }
            }
    }

    static class DownloadedDrawable extends ColorDrawable {
        private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference;

        public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) {
            super(Color.BLACK);
            bitmapDownloaderTaskReference =
                new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
        }

        public BitmapDownloaderTask getBitmapDownloaderTask() {
            return bitmapDownloaderTaskReference.get();
        }
    }

    private static boolean cancelPotentialDownload(String url, ImageView imageView) {
        BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);

        if (bitmapDownloaderTask != null) {
            String bitmapUrl = bitmapDownloaderTask.url;
            if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
                bitmapDownloaderTask.cancel(true);
            } else {
                // The same URL is already being downloaded.
                return false;
            }
        }
        return true;
    }

    private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
        if (imageView != null) {
            Drawable drawable = imageView.getDrawable();
            if (drawable instanceof DownloadedDrawable) {
                DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable;
                return downloadedDrawable.getBitmapDownloaderTask();
            }
        }
        return null;
    }
}

A: I figured out the problem by reading this question. If you hide some elements then you must show them again :) simple like that.

A: Well paul as far as your code is concerned you are downloading the images everytime from the desired server whenever you are scrolling through your list view. Probably a bitmap cache implementation could solve your problem.


text:
Q: How to Automatically and More Perfectly Center a Text Divider in the TOC The code
 \documentclass{article}

\begin{document}
\tableofcontents
  \addcontentsline{toc}{section}{\textbf{Table of Contents Entry 1}}
\addtocontents{toc}{\vskip 7pt \hskip 135pt \protect\rule{0.85in}{.02mm} \vskip 3pt}
  \addcontentsline{toc}{section}{\textbf{Table of Contents Entry 2}}
\end{document}

produces the output

I would like to be able to automatically center the text divider in the TOC without having to try to guess how much of an ``hskip'' to impose on it. I tried flanking the \protect\rule with two \hfills but that only results in an error.
Question: Can anyone tell me how I may automatically, and more perfectly, center a text divider in   the TOC?
Thank you.

A: Here, the use of \hfil on either side of the \rule is sufficient to provide the centering.
\documentclass{article}
\begin{document}
\tableofcontents
  \addcontentsline{toc}{section}{\textbf{Table of Contents Entry 1}}
\addtocontents{toc}{\hfil\protect\rule{0.85in}{.02mm}\hfil\vskip 3pt}
  \addcontentsline{toc}{section}{\textbf{Table of Contents Entry 2}}
\end{document}

Here are the contents of the aux file
\relax
\@writefile{toc}{\contentsline {section}{\textbf  {Table of Contents Entry 1}}{1}{}\protected@file@percent }
\@writefile{toc}{\hfil \rule {0.85in}{.02mm}\hfil \vskip 3pt}
\@writefile{toc}{\contentsline {section}{\textbf  {Table of Contents Entry 2}}{1}{}\protected@file@percent }
\gdef \@abspage@last{1}


text:
Q: Android AsyncTask Can't create handler inside thread that has not called Looper.prepare()? Why i am getting this error when i use this code in the asynctask even i am using  runOnUiThread() this is the code i am using ( i am using fragments ).
private class GmailXMPP_AfterLogin extends AsyncTask<AfterLogging, Void, Void> {

    private ProgressDialog _dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        _dialog = new ProgressDialog(getActivity());
        _dialog.setCancelable(false);
        _dialog.setTitle("colors");
        //((ProgressDialog)dialog).setIcon(R.drawable.icon);
        _dialog.setMessage("Your content is loading.. \nPlease wait..");
        _dialog.setIndeterminate(false);
        _dialog.show();
        //ProgressBar_show();
        Log.i(TAG, " GmailXMPP_AfterLogin onPreExecute" );
    }

    @Override
    protected void onPostExecute(Void feed) {
        //ProgressBar_hide();
        _dialog.dismiss();
        Log.i(TAG, " GmailXMPP_AfterLogin onPostExecute" );
    }

    @Override
    protected Void doInBackground(AfterLogging... arg0) {

        Log.i(TAG, " GmailXMPP_AfterLogin doInBackground" );
        AfterLogging after = arg0[0];
        final XMPPConnection _connection = after.getConn();
        final String Uname = after.getAcc_Name();

                //synchronized (contactJids) {
        Roster roster = Gtalk_xmpp_client.getRoster();
        String file_name;
        for (RosterEntry entry : roster.getEntries()) {
            if (entry.getType() == ItemType.to || entry.getType() == ItemType.both) {

                boolean yes = Contact_data_source.checkUsername(entry.getUser());
                Log.i(TAG, "Con=" + yes);
                if (!yes) {

                    Bitmap buddy_img = buddyImage(entry, _connection);
                    if (buddy_img != null)
                        file_name = Store(buddy_img);
                    else
                        file_name = "";
                    if (entry.getName() == null)
                        Contact_data_source.createContact( entry.getUser(), entry.getUser(), Uname, file_name, UsedStrings.GoogleAccount );
                    else
                        Contact_data_source.createContact( entry.getName(), entry.getUser(), Uname, file_name, UsedStrings.GoogleAccount );
                } else {
                    Log.i(TAG, "Con=exist");
                }
            }
        }
        return null;
    }
 }

logcat shows
12-01 11:59:21.549: E/AndroidRuntime(16595): FATAL EXCEPTION: AsyncTask #1
12-01 11:59:21.549: E/AndroidRuntime(16595): java.lang.RuntimeException: An error occured while executing doInBackground()
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.lang.Thread.run(Thread.java:1019)
12-01 11:59:21.549: E/AndroidRuntime(16595): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.os.Handler.<init>(Handler.java:121)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.app.Dialog.<init>(Dialog.java:101)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.app.AlertDialog.<init>(AlertDialog.java:63)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.app.ProgressDialog.<init>(ProgressDialog.java:80)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.app.ProgressDialog.<init>(ProgressDialog.java:76)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at com.pipemedia.fragments.ChatAccountsFragment$GmailXMPP_AfterLogin.onPreExecute(ChatAccountsFragment.java:372)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.os.AsyncTask.execute(AsyncTask.java:391)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at com.pipemedia.fragments.ChatAccountsFragment.Gtalk_logInComplete(ChatAccountsFragment.java:435)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at com.pipemedia.xmpp.GmailXmppClient.Login(GmailXmppClient.java:60)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at com.pipemedia.fragments.ChatAccountsFragment$GmailXMPP.doInBackground(ChatAccountsFragment.java:337)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at  com.pipemedia.fragments.ChatAccountsFragment$GmailXMPP.doInBackground(ChatAccountsFragment.java:1)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-01 11:59:21.549: E/AndroidRuntime(16595):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-01 11:59:21.549: E/AndroidRuntime(16595):    ... 4 more

this is the line creating error
line 372 : progress_dialog = new ProgressDialog(getActivity());

A: Probablly you called AsyncTask.execute() in a background thread.
You can only execute AsyncTask in UI thread.

A: asynctask is a thread which run in background and update the ui thread only one time at last when it finish but runnable thread is not like asynctask, runnable thread calls the handler to  updated the ui thread in a loop so you cannot put handler inside the asynctask.

A: If you want to show a progress dialog in ongoing task which is already run in the thread then try this way.May it helps to you ::
Handler mHandler=new Handler();

mHandler.post(new Runnable()
{
     public void run()
     {
          //SHOW PROGRESS DIALOG HERE
     }
});

A: Create
progressDialog = ProgressDialog.show(SplashScreen.this, "Please wait...", "Porcessing ...", true);

in Activity class where you are launching AsyncTask.


text:
Q: How to evaluate k-means considering initial conditions when having the ground truth? I use kernel k-means algorithm with different kernels and want to see which one is the best. The way i do it is to fix the number of $K$ equal to number of classes (ground truth) and check the accuracy of the clustering result comparing to the true labels.
I also try it 1000 times with different initial point to take the best clustering result. But i think this evaluation is so supervised as i take the best initial point based on my ground truth knowledge.
Isn't it better to split into test/train batches and cluster the test data according to cluster centers obtained from the most accurate clustering on train data?


text:
Q: Why is a file resumeData.json not being loaded properly on github pages after deploy? So I was following this tutorial to deploy this personal website template to github pages. My personal page is hosting here:
https://samuelstentz.github.io/react-resume-sam/
master branch shows the source I run npm run deploy from. (https://github.com/SamuelStentz/react-resume-sam)
But it appears all of the information in public/resumeData.json does not load for some reason. If I run it locally with npm start all of this info shows up. Not sure why. I fiddled with the path of this url which loads resumeData.json with jquery inside of App.js and it didn't change anything. I run npm run deploy to add to github pages.
getResumeData(){
$.ajax({
  url:'/resumeData.json',
  dataType:'json',
  cache: false,
  success: function(data){
    this.setState({resumeData: data});
  }.bind(this),
  error: function(xhr, status, err){
    console.log(err);
    alert(err);
  }
});

}
Does anyone have any troubleshooting tips? Thanks.

A: I was able to solve this issue by changing the ajax url to /{reponame}/resumeData.json per the suggestion here: https://github.com/gitname/react-gh-pages/issues/9

A: I was able to "fix" this by manually adding "./" to the front of the static.js in gh-pages but I'm sure there is a better solution


text:
Q: Can I schedule workloads based on namespace in Kubernetes? The question says everything really - is it possible to schedule a Pod based on the namespace it is assigned to?

A: It's not built in as far as I know, but there's a couple of ways you could do it:
Create a mutating webhook that modifies the pod affinity rules if the namespace == something. Using something like this: https://github.com/slok/kubewebhook
Using the PodNodeSelector admission controller: https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/
Using the PodPreset admission controller:
https://kubernetes.io/docs/tasks/inject-data-application/podpreset/


text:
Q: Convexity and local maxima If a continuous function $f$ on $(a,b)$ is not convex, there is some choice of number $m$ so that $g(x)=f(x)+mx$ has a local maximum at a point $z$ inside the interval $(a,b)$. Is that true?

A: A local maximum, yes.  There exist $c,d$ such that $f((c+d)/2) > f(c)/2 + f(d)/2$.  Adjust $m$ so that $g(c) = g(d)$...

A: $\newcommand{\Reals}{\mathbf{R}}$Referring to your earlier closely related (now deleted) question, suppose $f:(a, b) \to \Reals$ is a continuous function. Let's say $f$ has:

*

*A peak if there exist numbers $x < z < y$ in $(a, b)$ such that $\max\bigl(f(x), f(y)\bigr) \leq f(z)$.

*A valley if there exist numbers $x < z < y$ in $(a, b)$ such that $f(z) \leq \min\bigl(f(x), f(y)\bigr)$.
If $f$ has a peak, then with the preceding notation, an easy application of the extreme value theorem on $[x, y]$ shows that $f$ has a (possibly non-strict) local maximum in $(x, y)$, and hence in $(a, b)$. Conversely, if $f$ has a local maximum at a point $z$ of $(a, b)$, then $f$ obviously has a peak.
An entirely analogous argument shows that $f$ has a valley if and only if $f$ has a local minimum in $(a, b)$.
Particularly, $f$ has a local extremum (maximum or minimum) if and only if $f$ is not strictly monotone.


text:
Q: ASP.NET MVC - MapRoute and User Defined Paths I have a problem with understanding ASP MVC3 directories system and map routing.
For example: I want some controllers to put them into Admin directory, so way to user editing should look like: "http://localhost/Admin/Users/Edit/1", where admin - subdirectory, users - controller, edit - action, 1 - user's id. What should I do to make this to work?
I have added MapRoute calling to Global.asax.cs:

   routes.MapRoute(
   "Admin", //
   "Admin/{controller}/{action}/{id}", //
   new { controller = "Home", action = "Index", id = UrlParameter.Optional } //
   );
,but it doesn't help.

A: You have to change the controller and the action from "Home" and "Index"
  routes.MapRoute(
    "Admin", //
    "Admin/{controller}/{action}/{id}", //
    new { controller = "Users", action = "Edit", id = UrlParameter.Optional } //
    );


text:
Q: PuLP only shows __dummy variable I am trying to use PuLP on dummy graph coloring problem. To solve the problem, we need to assign a colour to each node such that any adjacent nodes don't share a common colour while minimising the total number of colours used.
Here's a dummy data:
edges = [('A', 'H'), ('A', 'B'), ('H', 'G'), ('H', 'K'), ('H', 'J'),
         ('H', 'I'), ('G', 'F'), ('G', 'K'), ('F', 'E'), ('K', 'E'),
         ('K', 'J'), ('K', 'D'), ('I', 'J'), ('I', 'D'), ('D', 'C'),
         ('D', 'B')]
nodes = set(sum(edges, ()))
n_nodes = len(nodes)

Using Google's OR-Tools, I can find a solution:
from ortools.sat.python import cp_model

model = cp_model.CpModel()

# Set decision variables
var = {}
for node in nodes:
    var[node] = model.NewIntVar(0, n_nodes-1, node)

# Set objective
model.Minimize(len(set(var.values())))

# Add constraints
for edge in edges:
    model.Add(var[edge[0]] != var[edge[1]])

# Solve
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.OPTIMAL:
    print('Status: Optimal \n')

for node in nodes:
    print(f"{node}: {solver.Value(var[node])}")

Returns:
Status: Optimal

C: 0
A: 5
H: 4
K: 2
F: 1
E: 0
D: 1
J: 0
I: 2
B: 0
G: 3

Side note: While the status says optimal, I feel less colours could be used.
However, when using the similar approach with PuLP, I am unable to see any solution.
from pulp import *

model = LpProblem("coloring", LpMinimize)

# Set decision variables
var = {}
for node in nodes:
    var[node] = LpVariable(node, lowBound=0, upBound=n_nodes-1, cat=LpInteger)

# Set objective
model += len(set(var.values()))

# Add constraints
for edge in edges:
    model += var[edge[0]] != var[edge[1]]

# Solve
status = model.solve()
print(f'Status: {LpStatus[status]} \n')

for variable in prob.variables():
    print(f"{variable.name}, {v.varValue}")

Returns:
Status: Optimal

__dummy, None

Any help on where I have gone wrong would be greatly appreciated.

A: So you've got 2 issues in your formulation that are causing you problems.  First the len(set(...)) is a non-linear operation.  when you add expressions to the problem they need to be expressed as linear equations.  Your constraint has the same issue.  Your logic is correct, but you cannot pass x != y to the solver, that is also non-linear.  You have to look at how to formulate these pieces of logic with linear expressions to reformulate.
Note, that you can always print(model) in pulp to see what was built, if you print yours, nothing useful comes up... who knows how these things are evaluated and put into the model.  I suspect they are evaluated once at construction and you are throwing trivial expressions into the model like x = True or something, and not getting errors.
So here is an alternate formulation of your problem with linear expressions.  The this_color != that_color constraint is a little complex and relies on an indicator variable to enable the either-or construct.
I don't use Google's OR Tools much, but it is mostly just syntactic sugar on top of these concepts, so perhaps there is a way to elegantly state it in OR Tools, but at the end of the day, something like this is getting generated and passed to the solver.
There may be a better formulation of this in graph theory, but this works fine for simple ILP.  3 colors is the answer.
from pulp import *

edges = [('A', 'H'), ('A', 'B'), ('H', 'G'), ('H', 'K'), ('H', 'J'),
         ('H', 'I'), ('G', 'F'), ('G', 'K'), ('F', 'E'), ('K', 'E'),
         ('K', 'J'), ('K', 'D'), ('I', 'J'), ('I', 'D'), ('D', 'C'),
         ('D', 'B')]
nodes = set(sum(edges, ()))
n_nodes = len(nodes)
M = n_nodes + 1

model = LpProblem("coloring", LpMinimize)

# Set decision variables
color = {}
for node in nodes:
    color[node] = LpVariable(node, lowBound=1, cat=LpInteger)
num_colors = LpVariable('count', cat = LpInteger)

color_diff = {}
for idx, edge in enumerate(edges):
    color_diff[edge] = LpVariable(str(idx), cat=LpBinary)

# Set objective
# model += len(set(var.values()))
model += num_colors   # seek to minimize the maximal color index

# Add constraints

# get the max value of the colors...
for node in nodes:
    model += num_colors >= color[node]

# ensure the adjacent nodes are different color
for edge in edges:
    # force one or the other of these to be true, based on the color_diff
    # variable, which is just a binary indicator
    model += -M * color_diff[edge] + 1 <= color[edge[0]] - color[edge[1]]
    model += -M * (1-color_diff[edge]) + 1 <= color[edge[1]] - color[edge[0]]

# Solve
status = model.solve()
print(f'Status: {LpStatus[status]} \n')

for variable in model.variables():
    print(f"{variable.name}, {variable.varValue}")

Yields
Result - Optimal solution found

Objective value:                3.00000000
Enumerated nodes:               0
Total iterations:               0
Time (CPU seconds):             0.01
Time (Wallclock seconds):       0.01

Option for printingOptions changed from normal to all
Total time (CPU seconds):       0.01   (Wallclock seconds):       0.01

Status: Optimal

0, 1.0
1, 0.0
10, 0.0
11, 1.0
12, 0.0
13, 1.0
14, 0.0
15, 0.0
2, 0.0
3, 0.0
4, 0.0
5, 0.0
6, 1.0
7, 1.0
8, 0.0
9, 0.0
A, 2.0
B, 1.0
C, 1.0
D, 3.0
E, 1.0
F, 3.0
G, 1.0
H, 3.0
I, 2.0
J, 1.0
K, 2.0
count, 3.0
[Finished in 96ms]


text:
Q: issue with pagebeforeshow back and going to next page in jquery mobile am using pagebeforeshow to a page to getjson data and going back from that page displaying the same page again and again and after again clicking on back going to before page, same with going to next page from that particular page. any suggestion please thanks.
code is as follows,
$(document).on('pagebeforeshow', '#pagethree', function(e) {
        //alert("inpGrid");
        var i = 0;
        var url = "http://192.168.0.101:8080/iConfig/html5_XV/slideDemo/json/listinp.json";
             // var url = "http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139&callback=?" ;
              $.getJSON(url, function(res) {
                  console.log(res)
                  var attr = "";
                   $.each(res.response.output.records, function(i, v) {
                                  $.each(res.response.output.fieldInfo, function(index, value) {

                                        if (index == 0 && offset==v[value["label"]]) {
                                            attr =1;
                                        }
                                        if(attr == 1){
                                            if(index == 0){
                                                document.getElementById('inpName').value = v[value["label"]];
                                                inpName = v[value["label"]];
                                            }
                                            if(index == 1){
                                                document.getElementById('inpAlias').value = v[value["label"]];
                                                inpAlias = v[value["label"]];
                                            }
                                            if(index == 2){
                                                document.getElementById('inpDataType').value = v[value["label"]];
                                                inpDataType = v[value["label"]];
                                            }
                                            if(index == 3){
                                                document.getElementById('inpDefault').value = v[value["label"]];
                                                inpDefault = v[value["label"]];
                                            }
                                            if(index == 4){
                                                document.getElementById('inpVisible').value = v[value["label"]];
                                                inpVisible = v[value["label"]];
                                                attr = "";
                                            }
                                        }
                                  });
                 });

            });
});

and pagethree.html looks like

Selected Input

         <fieldset data-role="controlgroup">

                         Name:
                         <input type="text" name="inpName" id="inpName"   disabled="disabled"/>

                                     Alias:
                                     <input type="text" name="inpAlias" id="inpAlias"/>

                                                 Data Type:
                                                 <input type="text" name="inpDataType" id="inpDataType"   disabled="disabled"/>

                                                 Default Value:
                                                 <input type="text" name="inpDefault" id="inpDefault"  />

            Visibility:
                                <select name="inpVisible" id="inpVisible">
                                    <option value="0">0</option>
                                    <option value="1">1</option>
                                </select>

         </fieldset>

         back

    Go to Page One

Footer Text in Dialog


text:
Q: Заполнить ячейку значением из ячейки на несколько индексов меньше: pandas Народ, прошу помочь с Pandas (картинка для примера в экселе).
Есть датафрейм: номер рейса, дата вылета, количество купленных билетов, дней до вылета.
За день до вылета ни на одном рейсе продаж не было, но данную строку заполнить надо.
Количество купленных билетов заполнить не проблема - fillna(0).
А вот как заполнить номер рейса и дату вылета?
Важно: это только выборка с двумя рейсоднями, по факту во фрейме их гораздо больше.
UPD: заполнить внутри смог, но как быть с верхними пустыми значениями, где много нанов, и shift вставляет тот же самый nan?
dct = {'Дней_до_вылета': [4, 4, 3, 3, 2, 2, 1, 1, 0, 0],
       'Рейс': [np.nan, np.nan, np.nan, np.nan, 'x','y',np.nan, np.nan, 'x','y'],
       'Дата_вылета': [np.nan, np.nan, np.nan, np.nan, '2022-10-17', '2022-10-20', np.nan, np.nan, '2022-10-17', '2022-10-20'],
       'Купленные_билеты': [np.nan, np.nan, np.nan, np.nan, 5, 3, np.nan, np.nan, 1, 2]}
pd.DataFrame.from_dict(dct)


text:
Q: How to fetch browser cookie or browser catch in JavaScript or jquery Hello Everyone i am new in JavaScript and jquery i am trying to fetch browser cookie and browser catche like we search some product on flip-kart or amazon and when we close this site and do normal work on net that time search product advertise show same like i tried.
so please suggest me what i can do for same.

A: jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.
Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.
Basic examples:
// Set a cookie
Cookies.set('name', 'value');
// Read the cookie
Cookies.get('name') => // => 'value'


text:
Q: Publishing an internal mail server to mobile clients using ISA Server 2004 First, let's start with a picture to illustrate my problem...

Naturally, IP addresses have been obfuscated for security reasons.
I have an internal LAN, 192.168.1.x behind ISA Server 2004. On this network reside a number of fixed workstations, a POP3 mail server (not Exchange) and a WAP supporting mobile clients. All devices are served by DHCP (though with reserved addresses where applicable).
On the Internet-side, I have an ADSL-connected router with a range of public IP addresses. The WAN port on the router has the IP address 123.0.0.241, the LAN port, 123.0.0.246.
Between the two, I have an ISA Server 2004 with two network cards. The first is attached to the router and has a public IP address, 123.0.0.242. The router is configured to route traffic, rather than use NAT. The ISA Server publishes the POP3 mail server on its 123.0.0.242 public IP address.
The problem is this...
When mobile devices are on-site, connected to the WAP, they belong to the 192.168.1.x subnet and connect to the mail server directly, without bothering the ISA Server.
However, when taken off-site, they must now access the POP3 server via the ISA Server on 123.0.0.242.
What I want is a single configuration for the mobile devices that works regardless of whether they're on-site or off-site.
If I configure them with the public IP of the ISA Server (123.0.0.242), they can't contact the mail server when they're on-site, because the IP is on the wrong side of the ISA Server.
Obviously, if I configure them with the private IP of the Mail Server, they can't access it when off-site.
I've tried a split DNS approach, where the FQDN of the mail server resolves to 192.168.1.2 on-site and 123.0.0.242 when off-site. The trouble is that the DNS TTL is too long, so I have to wait an eternity for the devices to refresh the IP address. The Internet-facing DNS Server isn't mine and I have no control over the TTL.
I've tried associating the FQDN of the Mail Server with both the public and the private IP addresses, relying on the DNS client's round-robin failover to eventually select the right IP address. Apart from the fact that it's a really bad idea to use the private IP address on someone else's network, some of the devices seem rather reluctant to fail over to the alternate address when you move from on- to off-site or vice versa.
I can't bind the public IP address to both the internal and external adapters on the ISA Server, as ISA Server complains bitterly (I can't say I blame it).
So, I'm stumped. What I want is for both internal and external clients to be able to access the Mail Server using a public IP address. I have some spare addresses, so I could use another, if that helps.
But I don't know where to go next. Any suggestions would be very gratefully received!

A: The split DNS should be workable.
I'd think that the system's local DNS cache would reset when switching wireless networks.. but now that I think of it, I haven't tried that before (and I can't find any documentation one way or the other).
If it is the OS cache, it's is easy to overcome:
HKLM\SYSTEM\CurrentControlSet\Services\Dnscache\Parameters\MaxCacheTtl

Times are in seconds, so crank that down to just a couple minutes; more frequent queries against a DNS server on your LAN never hurt anyone.
But, I suspect that's not the issue.  I would suspect that the mail client application is the culprit on keeping the old host resolution data.. which makes things a little more difficult.  Depends on your mail application, but, worst-case, users may need to restart their client application if it won't ditch the data from the no-longer-connected network.
Finally, the obligatory security note:
If you're using vanilla port 110 POP3, without an SSL component to the connection, that's a bad thing; it becomes a very, very bad thing on a public wifi network.  POP3 is a cleartext protocol; all authentication data and all mail are in clear text, and would be available for the taking to anyone else on the same wifi network.
If you are stuck using POP3 without encryption, then throw this architecture out the window and use remote access VPN.


text:
Q: Why isn't mixed-mode replication default on MySQL It is well known that mixed-mode replication was default from MySQL 5.1.12 to MySQL 5.1.28. However, this was reverted, and at the current moment, statement-based replication is default.
In the announcement that statement-based replication was default, Oracle claimed that this was only because mixed mode replication constituted a behavior change which may catch some users unaware. (See also Bug 39812.) However, MySQL 5.1 has many behavior changes, and it because the benefits of mixed-base replication so clear (I'm sure every DBA has run into a case where replication failed because a user submitted a query which didn't replicate properly and caused their databases to diverge), this doesn't seem like a particularly strong reason.
There are some mutterings that mixed replication "can provide the best of both worlds, but needs testing", but we're already on MySQL 5.1.61, and one would hope all of the bugs would have been ironed out by now. So that leaves us just rather confused. Why isn't mixed mode replication default?

A: I asked myself this question recently as well. At first, I looked at why row-based replication wasn't enabled by default. Obviously, row-based replication creates the possibility of IO-strain on disks by the amount of data that potentially could be written to the binary log.
Not surprisingly, this is the number one disadvantage of row-based replication the MySQL documentation mentions. A bit further down, another disadvantage would be a potential issue with performance with MyISAM:

For tables using the MyISAM storage engine, a stronger lock is required on the slave for INSERT statements when applying them as row-based events to the binary log than when applying them as statements. This means that concurrent inserts on MyISAM tables are not supported when using row-based replication.

MyISAM is the default engine of the 5.1 series. It is not until 5.5 that InnoDB is default. This replication impact on MyISAM, to me, is a strong reason not to use RBR by default.
But your question revolves around the MIXED format. Under MIXED format, the default is to use statement-based replication until a statement is called that required row-based replication. The link above gives a nice overview of what type of logging gets performed on certain situations (safe, unsafe, row injection).
I think there are too many potential situations that would cause replication to switch to row-based replication, causing some of the performance issues noted above on non-optimal  hardware. And let's face it, MySQL has a large following of users running it on non-optimal hardware.
This situation stands out to me the most:

If a statement is logged by row and the session that executed the statement has any temporary tables, logging by row is used for all subsequent statements (except for those accessing temporary tables) until all temporary tables in use by that session are dropped.

Note that all statements involving temporary table in row-based logging is considered unsafe, so this could cause issues with your replication setup.
Ultimately, I think it is a good idea to have STATEMENT be the default, having to make a conscious, educated decision to switch to MIXED.

A: According to current documentation, SBR is the default for MySQL 5.5
In the question, it says It is well known that mixed-mode replication was default from MySQL 5.1.12 to MySQL 5.1.28.
However, it is worthy noting that

*

*MySQL 5.1.30 is the first GA release of MySQL 5.1 (Dec 2008)

*MySQL 5.1.24 was released Apr 2008

*MySQL 5.1.12 was released Nov 2006
In light of this, technically speaking, early GA releases of MySQL 5.1 are always SBR by default. In addition

*

*Oracle bought Sun April 20, 2009, predating Oracle involvement in MySQL 5.1 rc versions

*Sun bought MySQL Jan 2008, predating Sun's initial involvement in MySQL 5.1 rc versions

So, the proper question is Why did MySQL AB not incorporate mixed-mode replication in MySQL 5.1?
IMHO I could easily see that being the case. Oracle would naturally have a hands-off approach to describing the problem and claiming any responsibility. While Oracle has always used RBR in its flagship database, I don't see Oracle stepping in to make RBR have any sort of limelight in MySQL.
From another angle, since MySQL can readily run on commodity hardware, SBR would be more than adequate. One would also not be bludgeoned to death by rapidly growing binary logs. Larger MySQL installations with advanced replication setups would be better suited for RBR.
Getting around issues with using SBR, RBR, and Mixed should be as simple as clearing all relay logs and starting replication from scratch on any given Slave.


text:
Q: Is there any pure CSS solution to make a div's relative size the same aspect to its parent? Say I have an SVG code like this:

#svgparent {width:90%}

<svg width="100%" viewBox="0 0 300 100">
  <rect x="5" y="15" width="250" height="70" style="fill:none;stroke-width:3;stroke:rgb(0,0,0)" />
  <text  x="5" y="35"><tspan font-weight="bold" font-size="15">Auto resizing, relative location is fixed</tspan></text>
  <rect x="15" y="35" width="50" height="25" style="fill:#fcc;stroke-width:3;stroke:none" />
</svg>

Is there any way that I can use pure CSS to do this for HTML elements?

#out {
  position:relative;
  width:90%;
  height:200px;
  border:1px solid red;
}
#in {
  font-size:16px;
}

Reszing not following as the SVG elements


text:
Q: Team Development menu option in IBM Lotus Domino Designer Is there a way to add the Team Development menu option to the Domino Development perspective in IBM Lotus Domino Designer?

A: Found the answer. Go to Windows menu on DDE and select "Customize perspective". Switch to the "Commands" tab and in the "Available command groups" find "Domino Designer Team Development" and activate it.


text:
Q: Forecasting methods to work globally on a series of datasets Forecasting a numeric time-series is providing an estimator $\hat y(t+1)$ of $y(t+1)$ computed from $(y(1),y(2)...y(t))$. You want it to be close to $y(t+1)$ (say in terms of squared distance).
Now instead of just a numeric value, assume $Y(t)$ is a full dataset with several categorical features. It can be seen as a bag since order does not matter. You want to provide an estimator $\hat Y(t+1)$ of $Y(t+1)$ that is statistically close to $Y(t+1)$.
Datasets $A$ and $B$ being statistically close means something a bit vague. I can give a sketch of a definition. Let $F$ be a condition on the features like for example "feature1=1 and feature2=5". Call $F_A$ and $F_B$ the number of elements satisfying $F$ in $A$ and $B$ respectively. $A$ and $B$ are said to be close if $F_A$ and $F_B$ are close for all $F$ as long $F$ is not restrictive enough to match a very small number of elements where difference would be essentially caused by random. A sort of measure of statistically significative distance.
It is possible to implement a bag-wise exponential smoothing (a simple forecasting method) for bags directly. Define $\hat Y(t+1)=(1-\alpha)\hat Y(t)+\alpha Y(t)$ where multiplication stands for taking a random sample ($aX$ means: the dataset resulting of keeping each element of $X$ with probability $a$ with independent trials) and + stands for concatenation (union on bags).
Are there known advanced forecast methods for datasets that extend some time-series methods, typically dealing with seasonality or trend?


text:
Q: Ruby: What is the difference between writing extend outside the class and inside the class I have read this question at url In Ruby or Rails, why is "include" sometimes inside the class and sometimes outside the class?. As per the answer of this question i am expecting the method print2 of module Calculation should be accessible to the class Addition and ABc .but i am getting error as undefined methodprint2' for Addition:Class (NoMethodError)`
module Calculation
    def print2
        puts "print2"
    end
end

require '/home/sanjay/Desktop/m'

extend Calculation;

class Addition

end

class Abc

end

Addition.print2
Abc.print2

Please explain why this error is comming??
Thanks

A: The receiver of extend should be each class, so you want Addition.extend Calculation and Abc.extend Calculation (after the class definitions). The semicolon is not required.
module D
  def dog
    puts "woof"
  end
end

class A; end
A.extend D
A.dog #=> "woof"

class B; end
B.extend D
B.dog #=> "woof"

A: My hunch is that your extend (outside any class) extends the Eigenclass of main. Main being the instance of Object that is your current runtime environment. An Eigenclass is the class of an object whose only instance is the given object. Each object in Ruby has a Eigenclass. Nothing inherits from an Eigenclass. So your extend is not inherited to any other classes.


text:
Q: ubuntu 14.10 and postgres 9.4 how to run pg_controldata I have a server with pg_xlog directory filled up. I need to determine the WAL(Write Ahead Log) files to delete and according to this link i need pg_controldata which is not available in ubuntu with postgresql-contrib-9.4 installed.
How can I proceed?

A: Use locate pg_controldata to locate it at /usr/lib/postgresql/9.4/bin/pg_controldata.
Alternatively, use find / -name pg_controldata. Ideally you would search somewhere more specific than the filesystem root.


text:
Q: Якорь на класс - такое возможно? Как?

url: http://example.com/.popup
Очень нужно ссылаться на класс, помогите реализовать? Ссылка пойдет в js в функцию с ajax.
A: Так вы load делаете  :) load ничего не делает, кроме как читает html и вставляет его, или куски его в блок, в вашем случае наверное надо
$('.popup_box').load('/includes/popup_product/'+entry+' .popup');

а лучше сразу генерируйте блок нужного вида по ajax запросу.
а ещё лучше отдавайте на ajax запрос ajax ответ, этим вы сэкономите 10-100 Ватт мирового электричества на 1000 посещений.
читаем про load

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

A: Думаю можно придумать универсальный способ по селекторам:
http://example.com/#.popup
http://example.com/##inp
http://example.com/#footer

$(document).ready(function() {
    var $search_element = $(location.hash.slice(1));
    if($search_element.length > 0) {
        $(window).scrollTop($search_element.offset().top);
    }
});


text:
Q: Unexpected side effect in "reversedList" computed property in VUE JS In my application I am trying to avoid mutating a prop directly, however I keep getting this error in the terminal:
Unexpected side effect in "reversedList" computed property

then in the console i get:
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "List"

My component code is:
 <template>

        My List
        {{List.length}}

        {{result.collectionName}}

        {{result.artistName}}

            <button
              class="btn btn-success btn-sm btn-block"
              v-on:click="removeElement(index)"
            >Remove</button>

            <button
              class="btn btn-info btn-sm btn-block"
              @click="toiTunesAlbum(result)"
            >View on iTunes</button>

    <button class="btn btn-info mt-5 btn-lg btn-block" @click="saveList()">Save</button>

</template>

Parent Component
<template>

{{title}}

{{intro}}

Enter a valid search term

      <button
        type="button"
        class="btn btn-primary btn-lg mb-3"
        v-on:click="refreshPage"
        v-if="result.length > 1"
      >
         Start again
      </button>
      <input
        class="form-control form-control-lg mb-3"
        type="search"
        placeholder="Search"
        aria-label="Search"
        v-model="search"
        required
        autocomplete="off"
        id="search"
      >

              <button
                type="button"
                class="btn btn-primary btn-lg mb-3 float-right"
                v-on:click="addItem(result)"
                :disabled="result.disableButton"
              >

              </button>

              {{result.collectionName}}

{{result.artistName}}

{{result.primaryGenreName}}

      <button
        class="btn btn-success btn-lg btn-block mb-3"
        type="submit"
        v-on:click="getData"
        v-if="result.length < 1"
      >
        Search
      </button>

    <List :List="List"/>

</template>

I was getting the main console error, then I added some code for reversedList however that did not work? Any idea's. The values come from a parent component that pass through a prop to this component.

A: The problem is that this mutates the original list:
return this.List.reverse();

You need to take a copy before reversing:
return [...this.List].reverse();

There are also problems with changing the prop here:
this.List = JSON.parse(localStorage.getItem("List"));

and here:
this.List.splice(index, 1);

In both cases you need to move this responsibility up to the parent if you want to use a prop.

A: The problem is that you are using splice.
this.List.splice(index, 1);

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Therefore, the splice() method mutates this.List.
Instead, you can you can return a new list like so:
removeElement: function(index) {
  return this.List.slice().splice(index, 1);
},

Slice will make a copy of this.List.
Similarly, avoid directly mutating this.List with reverse().


text:
Q: Trying to find the most expensive book written by a certain author in Oracle SQL Looking for the most expensive order written by LISA WHITE. I think that my problem is in my joining area. Not sure how to go about joining 3 tables together using a structure like this.
TABLE 1        TABLE 2         TABLE 3
Attribute 1--->Attrubute 1
               Attribute 2---->Attribute 2
SELECT a.LNAME, a.FNAME, b.TITLE, TO_CHAR(MAX(b.RETAIL), '$99.99') as (Most Exoensive)
FROM AUTHOR a JOIN
      BOOKS b
      using (ISBN)
      b JOIN
      BOOKAUTHOR ba
      using (AUTHORID)
WHERE a.LNAME = 'WHITE' AND a.FNAME = 'LISA'
GROUP BY a.LNAME;

A: Something like this might work.
select b.title, b.retail
from books b join bookauthor ba using (bookid, authorid)
join author a using (authorid)

join (select max(retail) highestprice
from books bb join bookauthor ba using (bookid, authorid)
join author aa using (authorid)
where aa.lname = 'WHITE' and aa.fname = 'LISA'
group by bb.bookid) temp on retail = highestprice

where a.lname = 'WHITE' and a.fname = 'LISA'


text:
Q: Build with @angular/cli from another folder I'm writing a script that will build my app. This script is outside of my app folder. I can't figure out how to build with @angular/cli from another folder.
Let say the structure is applications/my-app/.angular-cli.json. How can I build the app from applications/.? Is there a way to tell @angular/cli to look in the ./my-app folder while building with ng build?

A: Actually not. It looks up from the working directory up to the first node_modules it finds.
See github

A: If you are on Windows, you can temporary change the working directory in the script. Take a look a the pushd and popd commands.


text:
Q: PugiXML value output encoding I am a little confused. pugi::xml_node::value() returns string of type chart_t, which can be either wchar_t or char depends on compilation flags. In documentation to pugiXML said that it works with different types on utf family encodings. OK. I am loading using pugi::xml_document::load_file() a document in uft16 encoding. Then when I am iterating throw nodes and calling value() method on every node, in which encoding I'll get value? Presumably in encoding of my data, which I've loaded to xml_document. This means in utf16. If it in utf16 then I'll can't to work with that value because there will be 0-symbols and I'll can't use strlen, strcpy an so on...
I've made such test, but everything works fine. Anybody knows how it works?

A: There are two modes of compilation - the default, where the document stores the in-memory data using UTF8 in char arrays, and the wchar mode (PUGIXML_WCHAR_MODE), where the data is stored in wchar_t arrays using either UTF16 or UTF32,  depending on sizeof(wchar_t).
When you are loading or saving the document, pugixml automatically decodes the input data or encodes the output data in the encoding specified by 'encoding' argument for load/save functions.
In your case, pugixml automatically detects that the input file contains UTF16 data and decodes it into UTF8, which is what you get from value().

A: http://pugixml.googlecode.com/svn/tags/latest/docs/manual/loading.html
http://pugixml.googlecode.com/svn/tags/latest/docs/manual/loading.html#manual.loading.encoding
You can specify encoding by yourself or 'enjoy' auto-detected one.


text:
Q: Tornado: file log is also write to stdout I'm using FileHandler to write tornado access logs into file, but the same log is output to stdout.
from tornado.options import define, options

options.logging = None
options.parse_command_line()

access_log = logging.getLogger('tornado.access')
access_log.setLevel(logging.INFO)
handler = logging.FileHandler(log_path)
access_log.addHandler(handler)

// stdout::
INFO:tornado.access:200 GET / (ip) 0.93ms

It does write into log file, but I don't know why it's also output to stdout.

A: Python's logging framework is based on a hierarchy of loggers. Whatever is logged to tornado.access is also by default propagated to the root logger (which goes to stderr by default). If you don't want the access log to get duplicated, set the propagate attribute:
access_log.propagate = False


text:
Q: "Most" is used as an adjective and an adverb I read a sentence " He gave the most money". In this sentence "most" is used as an adjective. If I want to use "most" as an adverb can I say "He gave money the most" Is the latter correct grammar? and if it is does it sound natural?
Thank you :-)

A: "He gave the most money" and "He gave money the most" mean two different things.  The first is a comparison to others giving money.  The second is a comparison to other things he gives.
In sum, it's grammatical.  It's natural.  But watch for meaning.


text:
Q: Changing checkbox appearance to button I am using a checkbox as a toggle switch (ON-OFF Button) by changing its appearance to Button using Checkbox.Appearance property.
When I run the VB.NET application, the Checkbox turns into a button only after the first click. Is it possible to change the appearance of the Checkbox to button as default? I also want the button to Popup when the user clicks "ON". I have tried changing the appearance using FlatStyle property, but it doesn't work.
I am using the following code:
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged

    CheckBox1.Appearance = System.Windows.Forms.Appearance.Button

    If CheckBox1.Checked = True Then
        CheckBox1.Text = "ON"
    ElseIf CheckBox1.Checked = False Then
        CheckBox1.Text = "OFF"
    End If

End Sub

A: It is possible to select Appearance into the Load event of the form
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Me.CheckBox1.Appearance = Appearance.Button
End Sub


text:
Q: Difficulty in understanding integrals of complex numbers I understand what integration of real numbers is. I know how the definition of it is made.
I have trouble in understanding how it works for complex numbers.
I am referring to the notes here: http://people.math.gatech.edu/~cain/winter99/ch4.pdf.
I understand till how the Reimann sum (page 2) is calculated because it is almost the same as reals. There after, I do not understand a thing.
Please elucidate what it is.

A: As far as contours go, a rough (and probably poor) analogy is suppose you want to integrate the height of a hill. You would lay out a tape measure and measure the height at each point as you walk up the hill - except you can walk up the hill in lots of different ways. You can walk up in a straight line from east to west, or maybe a curve from south to northwest, etc. Maybe you only want to walk AROUND the top of the hill. You can think of the complex function that you're integrating as the hill (except it has a complex height instead of a real height), and the line or curve you're integrating along as the path in the complex plane.
You'll get different measurements depending on where the start and end points are, and how well-behaved the curve is. If the curve is very well-behaved, there's a nifty property that it doesn't matter what the curve is, the integral will be the same as long as the start and end are the same. You could start at point $a=1$, head all the way out to point $c=10^{1000}$ then come back to point $b=2$, and as long as your path is continuous, you will get the same answer as if your curve went straight from $a$ to $b$.
From there, you can imagine that for these well-behaved functions, the curve from $a$ to $a$ - a closed path, would be the same as the integral from $a$ to $a$ - 0, and you would be right.
I'm glossing over a lot here, but this is a very high-level view of how you can visualize complex integration.

A: Some explanations on the examples the OP is interested in, namely those in
http://people.math.gatech.edu/~cain/winter99/ch4.pdf
at pag. 4.3-4.4.
We want to integrate the function $f(x,y)=u(x,y)+iv(x,y)=(x^2+y)+i(xy)$ along different paths. Using the notation $z=x+iy$, we have
$$f(z)=\operatorname{Re}(z)^2+\operatorname{Im}(z)+i(\operatorname{Re}(z)\operatorname{Im}(z)).$$
Remark: the function $f$ is not differentiable at $z$ because it does not satisy the Cauchy Riemann equations.

*

*Case 1:   $\gamma_1(t)=t+it^2$, $t\in [0,1]$.

The locus of points described by the  path $t\mapsto \gamma_1(t)$ is a parabola in the complex plane. In fact, by definition
$$\operatorname{Im}(\gamma_1(t))=\operatorname{Re}(\gamma_1(t))^2,$$
 for all $t\in [0,1]$.

*

*Case 2  $\gamma_2(t)=1+it$, $t\in [0,1]$.
The locus of points described by the  path $t\mapsto \gamma_2(t)$ is the vertical line connecting the point $\gamma_2(0)=1+i0$ to $\gamma_2(1)=1+i1$ in the complex plane. By definition all points $\gamma_2(t)$ satisfy

$$\operatorname{Re}(\gamma_2(t))=1$$
with $t\in [0,1]$. Their imaginary part $$\operatorname{Im}(\gamma_2(t))=t$$ increases linearly from the minimum $\operatorname{Im}(\gamma_2(0))=0$ to the maximum $\operatorname{Im}(\gamma_2(1))=1$.

*

*Case 3 Similar to Case 2, with due changes.

EDIT. Extra example for the OP
Let $\gamma(t):=t+i\sqrt{1-t^2}$ for $t\in[0,1]$. As
$$\operatorname{Re}(\gamma(t))^2+\operatorname{Im}(\gamma(t))^2=
t^2+(1-t^2)=1,$$
then the locus of points $\gamma(t)$ in the complex plane is a 1/4 of a circle of radius $1$, with initial point $\gamma(0)=0+i$ and final point  $\gamma(1)=1$ (direction:clockwise).
Let us introduce the simplified notation $x(t):=\operatorname{Re}(\gamma(t))$ and
$y(t):=\operatorname{Im}(\gamma(t))$
If $f(x,y)=u(x,y)+iv(x,y)=(x^2+y)+ixy$, then
$$f(\gamma(t)):=u(x(t),y(t))+i v(x(t),v(t))=(x(t)^2+y(t))+ix(t)y(t)=
(t^2+\sqrt{1-t^2})+i t\sqrt{1-t^2}.$$
A comment on terminology. "Locus" (http://en.wikipedia.org/wiki/Locus_(mathematics))
denotes a set of points satisfying certain conditions. When I write "the locus of points
$\gamma(t)$..." I mean the set of all points in the complex plane which are of the form
$$\gamma(t)=x(t)+iy(t).$$
In other words, here "locus" means the image in the complex plane of the map (called also curve)  $t\mapsto \gamma(t)$.


text:
Q: is it possible to use ?? operator on class member? In c# there is a great operator '??' that makes life much simplier. Instead of writing (foo != null)? foo : default I can write foo ?? default. Is there a simple way to apply this operator to class memeber e.g. in situation (foo != null)? foo.bar : default?
upd: OK I'll expalin a bit:
string a = (someVeryLongVariableName != null)? someVeryLongVariableName : ""; // Long way
string a = someVeryLongVariableName ?? ""; // Shorter with same result
string a = (someVeryLongVariableName != null)? someVeryLongVariableName.bar : ""; // What's the shorter way in this case?

upd2: Situation when I need this feature looks like this:
if (foo is MyClass) bar1 = (foo as MyClass).SpecificMember;
if (foo is OneMoreClass) bar2 = (foo as OneMoreClass).AnotherSpecificMember;
if (foo is MyFavoriteClass) bar3 = (foo as MyFavoriteClass).YetAnotherMember;

It'll be cool if I can shorten these to something like
bar1 = (foo as MyClass).SpecificMember ?? null;

Maybe it's not much shorter but it casts foo to MyClass only once and explicitly initializes bar with default value.  And most important it looks nicer.

A: Only if you have some way of doing it like this
  (foo ?? defaultFoo).bar

But that would mean that you'd have to have an object of the same time as foo around with its bar set up the way you want it.

A: No, there's currently no such operator (access member or return default value) in C#. You can, of course, write a method to do this:
public static TMember MemberOrDefault<T, TMember>(T obj,
                                                  Func<T, TMember> accessor,
                                                  TMember @default) {
    return obj == null ? @default : accessor(obj);
}

string a = MemberOrDefault(someVeryLongVariableName, v => v.bar, "");

Note, however, that this will still return null if someVeryLongVariableName.bar is null (which might or might not be what you want).

A: There is no built-in C# operator that does what you describe. A new operator (most people suggest .? or ?.) has been requested, but it has not been added to C#.
As a workaround, many developers implement an IfNotNull extension method, e.g., in this StackOverflow question and answer.


text:
Q: How to concat all JS files in a folder and use SASS in GruntJS? I have been trying this for sometime now. Each time I run grunt in my Terminal I get the following error:
User$: grunt
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected identifier
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.

This is my GruntFile.js
module.exports = function (grunt) {

    grunt.initConfig({

        sass: {
            dist: {
                files: {
                    'css/css.css' : 'css/css.scss'
                }
            }
        },
        concat: {
            js: {
                src:['js/*.js'],
                dest: 'js/js.js'
            }
        },
        watch: {
            css: {
                files: '**/*.scss',
                tasks: ['sass']
            }
            js: {
                files: ['js/*.js'],
                tasks: ['concat:js']
            },
        }

    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.registerTask('default', ['watch', 'concat']);

};

My basic directory:
/js/jquery.js
/js/angular.js
/js/js.js
/css/settings.scss
/css/slider.scss
/css/css.css

A: You're missing a comma after your watch:css target (line 23).
Also, please note that the watch task never exits, so you want your default task to run it last:
grunt.registerTask('default', ['concat', 'watch']);

And finally, you should exclude your concatenated js from the list of watched files, to avoid looping.
module.exports = function (grunt) {
  grunt.initConfig({
    sass: {
        dist: {
            files: {
                'css/css.css' : 'css/css.scss'
            }
        }
    },
    concat: {
        js: {
            src:['js/*.js', '!js/js.js'],
            dest: 'js/js.js'
        }
    },
    watch: {
        css: {
            files: 'css/*.scss',
            tasks: ['sass']
        },
        js: {
            files: ['js/*.js', '!js/js.js'],
            tasks: ['concat:js']
        },
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['concat', 'watch']);
};


text:
Q: Setting Tailwind Typography Default Header Font What is the best way to set all headers in my prose class to a specific font?
The following is what I have, but does not seem to be working:
theme: {
 typography: {
  DEFAULT: {
    css: {
      h1: {
        fontFamily: ['Bebas Neue', 'sans-serif'],
      },
      h2: {
        fontFamily: ['Bebas Neue', 'sans-serif'],
      },
      h3: {
        fontFamily: ['Bebas Neue', 'sans-serif'],
      },
      h4: {
        fontFamily: ['Bebas Neue', 'sans-serif'],
      },
      h5: {
        fontFamily: ['Bebas Neue', 'sans-serif'],
      },
...

Also is there a less verbose way to set all headers at once?

A: You can use prose-headings variant or any other element modifier you need. Prose headings will target h1, h2, h3, h4, th
<div class="prose prose-headings:text-red-400">
 // Content
</div>

DEMO


text:
Q: Yii: Update content widget with ajax I have build a notification widget in Yii framework which is called every page and gives the user notifications. Now I would like to update those notifications automatically every 10 seconds with Ajax. The structure is as follows:
<?php

class NotificationsWidget extends CWidget {

public function init(){

}
public function run() {

}

What is the best way to do this? I have searched everywhere, but I cannot seem to find the answer. Maybe I'm just looking with the wrong keywords.. If anyone has another (better) way to do this, please! Only restriction is that it has to be loaded into the interface layout and update at least every 10 seconds.
Thanks a lot:)

A: You setup an action in your controller and poll it every 10 seconds, if there is update it will return the notification from a partial view, if there is no update nothing is returned, this is a skeleton implementation to give you an idea, note it will not work as is.
In your layout file
...
// Your normal layout content

<?php Yii::app()->clientScript->registerScript("poll_ajax_notifications",
 'function getNotification(){'.
   CHtml::ajax(array(
       'url'=>array("//notifications/update"),
       'dataType'=>'html',
       'type'=>'GET',
       'update'=>'#divcontainingNotificationWidget',
         )
     ) . '. }
   timer = setTimeout("getNotification()", 10000);
    ', CClientScript::POS_END);

In your Notifications controller
class NotificationsController extends CController {
....
 public function actionUpdate(){
     $user = Yii::app()->user->id;
     // Your logic logic for finding notifications
     if($notificationPresent){ // or any validation to check whether to push data or not
       $this->renderPartial('_notificationWidget',array('widgetData'=>$widgetData)); // pass data required by widget here
     }
     Yii::app()->end();
  }
 ...
}

Finally create a partial view in views/notifications folder called _notificationsWidget.php
In your view place your widget call
<?php
  $this->widget('path.to.my.widget',array(
     //widget parameters
   ));