text:
Q: Gnome-shell keeps crashing (logs says :Error looking up permission: GDBus.Error:org.freedesktop.portal.Error.NotFound: No entry for geolocation) I had installed Ubuntu 20.04, which kept crashing randomly. Searching it up on google, tried all the solutions but didn't work.
What I was able to assume is that most common problems point to graphics driver issues.
typing
sudo dpkg -l nvidia*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                             Version                    Architecture Description
+++-================================-==========================-============-===========================>
un  nvidia-304                       <none>                     <none>       (no description available)
un  nvidia-340                       <none>                     <none>       (no description available)
un  nvidia-384                       <none>                     <none>       (no description available)
un  nvidia-390                       <none>                     <none>       (no description available)
un  nvidia-common                    <none>                     <none>       (no description available)
ii  nvidia-compute-utils-390         390.138-0ubuntu0.20.04.1   amd64        NVIDIA compute utilities
rc  nvidia-compute-utils-450         450.80.02-0ubuntu0.20.04.2 amd64        NVIDIA compute utilities
un  nvidia-cuda-dev                  <none>                     <none>       (no description available)
ii  nvidia-cuda-doc                  10.1.243-3                 all          NVIDIA CUDA and OpenCL docu>
ii  nvidia-cuda-gdb                  10.1.243-3                 amd64        NVIDIA CUDA Debugger (GDB)
rc  nvidia-cuda-toolkit              10.1.243-3                 amd64        NVIDIA CUDA development too>
ii  nvidia-dkms-390                  390.138-0ubuntu0.20.04.1   amd64        NVIDIA DKMS package
rc  nvidia-dkms-450                  450.80.02-0ubuntu0.20.04.2 amd64        NVIDIA DKMS package
un  nvidia-dkms-kernel               <none>                     <none>       (no description available)
un  nvidia-driver                    <none>                     <none>       (no description available)
ii  nvidia-driver-390                390.138-0ubuntu0.20.04.1   amd64        NVIDIA driver metapackage
un  nvidia-driver-binary             <none>                     <none>       (no description available)
un  nvidia-kernel-common             <none>                     <none>       (no description available)
ii  nvidia-kernel-common-390         390.138-0ubuntu0.20.04.1   amd64        Shared files used with the >
rc  nvidia-kernel-common-450         450.80.02-0ubuntu0.20.04.2 amd64        Shared files used with the >
un  nvidia-kernel-source             <none>                     <none>       (no description available)
ii  nvidia-kernel-source-390         390.138-0ubuntu0.20.04.1   amd64        NVIDIA kernel source package
un  nvidia-kernel-source-450         <none>                     <none>       (no description available)
un  nvidia-legacy-304xx-vdpau-driver <none>                     <none>       (no description available)
un  nvidia-legacy-340xx-vdpau-driver <none>                     <none>       (no description available)
un  nvidia-libopencl1                <none>                     <none>       (no description available)
un  nvidia-libopencl1-dev            <none>                     <none>       (no description available)
ii  nvidia-opencl-dev:amd64          10.1.243-3                 amd64        NVIDIA OpenCL development f>
un  nvidia-opencl-icd                <none>                     <none>       (no description available)
un  nvidia-persistenced              <none>                     <none>       (no description available)
ii  nvidia-prime                     0.8.14                     all          Tools to enable NVIDIA's Pr>
un  nvidia-profiler                  <none>                     <none>       (no description available)
ii  nvidia-settings                  440.82-0ubuntu0.20.04.1    amd64        Tool for configuring the NV>
un  nvidia-settings-binary           <none>                     <none>       (no description available)
un  nvidia-smi                       <none>                     <none>       (no description available)
un  nvidia-tesla-418-driver          <none>                     <none>       (no description available)
un  nvidia-tesla-440-driver          <none>                     <none>       (no description available)
un  nvidia-utils                     <none>                     <none>       (no description available)
ii  nvidia-utils-390                 390.138-0ubuntu0.20.04.1   amd64        NVIDIA driver support binar>
un  nvidia-vdpau-driver              <none>                     <none>       (no description available)
un  nvidia-visual-profiler           <none>                     <none>       (no description available)

so far whenever I have to force restart my system, I always see this error on /var/log/syslog
**37713b62c32fd,:1.85/org.gnome.Shell.NetworkAgent/1000]: agent registered
38086 Nov  9 18:38:04 aissy-System gnome-shell[3673]: Error looking up permission: GDBus.Error:org.freede      sktop.portal.Error.NotFound: No entry for geolocation
38087 Nov  9 18:38:04 aissy-System dbus-daemon[1047]: [session uid=1000 pid=1047] Successfully activated       service 'org.freedesktop.FileManager1'
38088 Nov  9 18:38:04 aissy-System gsd-media-keys[1494]: Failed to grab accelerator for keybinding settin      gs:playback-random
38089 Nov  9 18:38:04 aissy-System gsd-media-keys[1494]: Failed to grab accelerator for keybinding settin      gs:hibernate
38090 Nov  9 18:38:04 aissy-System gsd-media-keys[1494]: Failed to grab accelerator for keybinding settin      gs:rfkill
38091 Nov  9 18:38:04 aissy-System gsd-media-keys[1494]: Failed to grab accelerator for keybinding settin      gs:playback-repeat**

I'm not sure if it's related to this issue of freezing randomly, but it seems that gnome-shell is crashing after this message.
I also reinstalled Nvidia drivers.


text:
Q: Laravel Sql query groupBy and Order I need some help to make a query.
Database tabless
Example:
The user inserts a actor name(name and surname) and i need to loop over all the movies and then retrieve which category has more occurrences.
I need some help to make the query(this one is only a sketch):
$src=array("Leonardo","DiCaprio");
     $film2=film::with('category')->with('actor')->wherehas('actor', function($q) use($src){
                                  $q->where('first_name', $src[0])->where('last_name', $src[1]);
                                })->wherehas('category', function($qr){
                                  $qr->groupBy('name')->orderBy('name', 'DESC');
                                })->FIRST();

model Film:

class film extends Model{
    protected $table = "film";
    protected $primaryKey = 'film_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['film_id', 'title', 'length'];

    public function category(){
         return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
    }
    public function actor(){
          return $this->belongsToMany(actor::class,'film_actor', 'film_id', 'actor_id');
    }
}

model Actor:

class actor extends Model{
    protected $primaryKey = 'actor_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['actor_id', 'first_name', 'last_name'];
}

model Category:

class category extends Model{
    protected $table = "category";
    protected $primaryKey = 'category_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['category_id','name'];

    public function film(){
        return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
    }
}

A: Here is the solution:
In Actor.php add Join
 public function filmActor(){
     return $this->hasMany(FilmActor::class, 'actor_id','actor_id');
 }

Find the actor with filmActor join table
 $src=array("Leonardo","DiCaprio");
 $actor=Actor::whereHas('filmActor')->where(['first_name' => $src[0],'last_name'=> $src[1]])->first();

Put film_id in the array
 foreach($actor->filmActor as $film){
      $filmIds[]=$film->film_id;
 }

Get FilmCategory who have filmIds
$filmCategory=FilmCategory::whereIn('film_id',$filmIds)->get();

Put category_id in the array
 foreach($filmCategory as $category){
      $categoryIds[]=$category->category_id;
 }

Count how much is duplicate category_id
 $count =array_count_values($categoryIds);

Get the higher counted $max =  max($count);
Get the key of max which is category_id  $key = array_search($max, $count);
Here is the category who has more occurrences.
 $category=Category::where('category_id',$key)->first();

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF ContentPresenter doesn't work with single Entry in ResourceDictionary I have a curious problem with my ContentPresenter. In my standard WPF application I have a "TestView", a "TestViewModel", a "MainWindowView" and a "MainWindowViewModel".
The MainWindowView contains a ContentPresenter, which content is bound to a ViewModelProperty of the MainWindowViewModel:
<ContentPresenter DockPanel.Dock="Right"
                  Height="Auto"
                  Width="Auto"
                  Content="{Binding CurrentContentViewModel}" />

And the ViewModel:
private IViewModel _currentContentViewModel;
public IViewModel CurrentContentViewModel
{
    get
    {
        return  _currentContentViewModel;
    }
    set
    {
        _currentContentViewModel = value;
        OnPropertyChanged();
    }
 }

The TestView is bound to the TestViewModel in my App.xaml:
<Application.Resources>
    <ResourceDictionary >
        <DataTemplate DataType="{x:Type viewModel:TestViewModel}">
            <view:TestView />
        </DataTemplate>
    </ResourceDictionary>
</Application.Resources>

When I now assign an instance of the TestViewModel to the CurrentContentViewModel, the ContentPresenter shows the class name of the TestViewModel:
MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
MainWindowView mainWindowView = new MainWindowView(mainWindowViewModel);

TestViewModel testViewModel = new TestViewModel();

mainWindowView.Show();
mainWindowViewModel.CurrentContentViewModel = testViewModel;

How did I fix the problem? I added an empty style tag, an SolidColorBrush definition or something else to my ResourceDictionary:
<Application.Resources>
    <ResourceDictionary >
        <DataTemplate DataType="{x:Type viewModel:TestViewModel}">
            <view:TestView />
        </DataTemplate>

        <SolidColorBrush x:Key="ColorBrushDummy" Color="HotPink"/>

    </ResourceDictionary>
 </Application.Resources>

Now is everything fine and the ContentPresenter show the TestView.
And now my question: Why?
Edit:
I've made a new SampleProject and reproduced the error. The problem occurs, when I started to use the OnStartup method of my App.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
    MainWindowView mainWindowView = new MainWindowView(mainWindowViewModel);

    TestViewModel testViewModel = new TestViewModel();

    mainWindowView.Show();
    mainWindowViewModel.CurrentContentViewModel = testViewModel;
}

My TestView:
<UserControl x:Class="ErrorSample.TestView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:ErrorSample"
         mc:Ignorable="d"
         d:DesignHeight="450"
         d:DesignWidth="800"
         d:DataContext="{d:DesignInstance local:TestViewModel}">
<Grid Background="Red">
        <TextBlock Text="{Binding Text}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"/>
</Grid>

My TestViewModel:
public class TestViewModel : ViewModelBase
{
    public string Text { get; } = "Sample Text";
}

And my MainWindowViewModel:
public class MainWindowViewModel : ViewModelBase
{
    private IViewModel _currentContentViewModel;

    public IViewModel CurrentContentViewModel
    {
        get => _currentContentViewModel;
        set
        {
            _currentContentViewModel = value;
            OnPropertyChanged();
        }
    }

    public MainWindowViewModel()
    {

    }
}


text:
Q: Google Chrome не отображает div-блоки Всем привет.
Хром не хочет показывать блоки с фоновыми изображениями. Притом Microsoft Edge их показывает как положено.
HTML + CSS:

@font-face {
    font-family: Neucha;
    src: url(/static/fonts/Neucha.ttf)
}

@font-face {
    font-family: Pattaya;
    src: url(/static/fonts/Pattaya-Regular.ttf)
}

html, body {
    margin: 0;
    padding: 0;
}

.header {
    padding: 0;
    padding-top: 15px;
    padding-left: 20px;
    width: auto;
    height: 100px;
    background: #643000;
    font-family: Neucha;
    font-size: 3em;
    letter-spacing: 2px;
    color: #F0C975;
    vertical-align: middle;
    text-shadow: 0 0 20px rgba(0,0,0,0.5);
}

.header p {
    display: inline;
    vertical-align: middle;
    margin: 0;
}

.content {
    display: flex;
    flex-flow: column nowrap;
    margin: 20px auto;
    align-items: stretch;
}

.menu {
    flex: 1 1 0;
}

.menu li {
    list-style: none;
    background: #643000;
    border-bottom: #F0C975;
}

.menu a {
    font-family: Neucha;
    font-size: 1.2em;
    letter-spacing: 2px;
    color: #F0C975;
    text-decoration: none;
}

img {
}

.gallery {
    display: flex;
    flex: 1 1 0;
    flex-flow: row wrap;
    align-items: stretch;
}

.picture {
    max-height: 320px;
    background-color: #643000;
    margin: 5px;
    display: flex;
    flex: 1 1 300px;
    flex-flow: column wrap;
    justify-content: flex-end;
    box-sizing: border-box;
    overflow: hidden;

}

.image {
    width: 480px;
    height: 320px;
    background-clip: border-box;
    background-position: center;
    background-repeat: no-repeat;
    box-shadow: 0 0 5px rgba(0,0,0,0.3);
}

.btest {
    width: 400px;
    height: 400px;
    border: 2px solid black;
}
<!doctype html>

    <meta charset="utf-8">
    <title>Мои фотографии</title>
    <link href="/static/content/base.css" rel="stylesheet">

Simple Photosite

Домой

Загрузить фото

Альбомы

Управление

Выход

                    Здесь должен быть коммент

                    Здесь должен быть коммент

                    Здесь должен быть коммент

И сервер говорит, что картинки загружены
127.0.0.1 - - [12/Mar/2017 20:28:14] "GET /photo/temp/20170312005037520000.thumbnail.jpg HTTP/1.1" 200 14313
127.0.0.1 - - [12/Mar/2017 20:28:14] "GET /photo/temp/20170312004957384000.thumbnail.jpg HTTP/1.1" 200 32355
127.0.0.1 - - [12/Mar/2017 20:28:14] "GET /photo/temp/20170312005840708000.thumbnail.jpg HTTP/1.1" 200 55539

В чем может быть проблема?

A: Уберите у .gallery {... flex: 1 1 0; ... } из-за него все пропадает или замените на flex: 1 1 auto;
3-ий параметр принимает значения: flex-basis:NN% | NNpx | auto

@font-face {
    font-family: Neucha;
    src: url(/static/fonts/Neucha.ttf)
}

@font-face {
    font-family: Pattaya;
    src: url(/static/fonts/Pattaya-Regular.ttf)
}

html, body {
    margin: 0;
    padding: 0;
}

.header {
    padding: 0;
    padding-top: 15px;
    padding-left: 20px;
    width: auto;
    height: 100px;
    background: #643000;
    font-family: Neucha;
    font-size: 3em;
    letter-spacing: 2px;
    color: #F0C975;
    vertical-align: middle;
    text-shadow: 0 0 20px rgba(0,0,0,0.5);
}

.header p {
    display: inline;
    vertical-align: middle;
    margin: 0;
}

.content {
    display: flex;
    flex-flow: column nowrap;
    margin: 20px auto;
    align-items: stretch;
}

.menu {
    flex: 1 1 0;
}

.menu li {
    list-style: none;
    background: #643000;
    border-bottom: #F0C975;
}

.menu a {
    font-family: Neucha;
    font-size: 1.2em;
    letter-spacing: 2px;
    color: #F0C975;
    text-decoration: none;
}

img {
}

.gallery {
    display: flex;
     flex: 1 1 auto;
    flex-flow: row wrap;
    align-items: stretch;
}

.picture {
    max-height: 320px;
    background-color: #643000;
    margin: 5px;
    display: flex;
    flex: 1 1 300px;
    flex-flow: column wrap;
    justify-content: flex-end;
    box-sizing: border-box;
    overflow: hidden;

}

.image {
    width: 480px;
    height: 320px;
    background-clip: border-box;
    background-position: center;
    background-repeat: no-repeat;
    box-shadow: 0 0 5px rgba(0,0,0,0.3);
}

.btest {
    width: 400px;
    height: 400px;
    border: 2px solid black;
}
<!doctype html>

    <meta charset="utf-8">
    <title>Мои фотографии</title>
    <link href="/static/content/base.css" rel="stylesheet">

Simple Photosite

Домой

Загрузить фото

Альбомы

Управление

Выход

                    Здесь должен быть коммент

                    Здесь должен быть коммент

                    Здесь должен быть коммент


text:
Q: Using GL_POINTS in GLKit (iOS 5) New with OpenGL, I am successfully displaying lines using GLKit on iOS 5 with GL_LINE_LOOP, but displaying points with GL_POINTS is giving me trouble. Specifically, I am unable to display anything but a single pixel. I've scoured the web with no success, so I'm hoping someone can point out what I'm missing.
Here is my test code...
//positions and colors, vertices and indices...
typedef struct {
    float Position[2];
    float Color[4];
} Vertex;

const Vertex Vertices[] = {
    {{50, 50}, {0, 0, 1, 1}},
    {{200, 50}, {0, 0, 1, 1}},
    {{200, 200}, {0, 0, 1, 1}},
    {{50, 200}, {0, 0, 1, 1}}
};

const GLubyte Indices[] = {
    0, 1, 2, 3
};

@interface AppViewController() {
    GLuint _vertexBuffer;
    GLuint _indexBuffer;
}

...
//some unrelated properties, the @implementation and other methods
...

- (void)viewDidLoad {
    [super viewDidLoad];

    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    if (!self.context) NSLog(@"Failed to create ES context");

    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    [EAGLContext setCurrentContext:self.context];

    self.effect = [[GLKBaseEffect alloc] init];

    GLKMatrix4 projectionMatrix = GLKMatrix4MakeOrtho(0, self.view.bounds.size.width, 0, self.view.bounds.size.height, -1024, 1024);
    self.effect.transform.projectionMatrix = projectionMatrix;

    glGenBuffers(1, &_vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &_indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW);
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);

    [self.effect prepareToDraw];

    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, Position));
    glEnableVertexAttribArray(GLKVertexAttribColor);
    glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, Color));

    //this worked for drawing my lines...
    //glLineWidth(10);
    //glDrawElements(GL_LINE_LOOP, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0);

    //this does NOT work for drawing 10-pixel points. single pixel only.
    glEnable(GL_POINT_SMOOTH);
    glPointSize(10);
    glDrawElements(GL_POINTS, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0);
}

Thanks for your time!

A: I don't think glPointSize() is part of OpenGL ES 2.0.
Try setting…
gl_PointSize = 10.0; //has to be a floating point value

…in your vertex shader.


text:
Q: Emulate pthread_kill with C++ threads How can I go about emulating the pthread_kill() function with C++ threads? I asked a question about this earlier but there was no response to it. Will the thread::native_handle() function help here?

A: So the answer to this question is to rely on platform dependent features and use std::thread::native_handle with pthread_kill()


text:
Q: View with data from many databases I'm building site in django, which lists items of many suppliers. Each supplier has own big database and make changes quite often. I have to be aware of all changes in no more than 60 minutes. There are about 10m items to display. How to implement all that in a efficient way?

A: It seems to me that your application has a pretty ugly architecture. Try to refactor it or you will have troubles.
Anyway, you can try to cache your suppliers' data to your own database (single) and save some resources.


text:
Q: Mutable List Update Event My question is very simple.
I can write as below with no problem and below code helps me not to check every time isScanning is updated, buttonScan.text also must be updated.
private var isScanning = false
    set(value) {
        field = value
        Handler(Looper.getMainLooper()).post {
            buttonScan.text = if (value) "Stop Scan" else "Start Scan"
        }
    }

Can I apply this in list in the same way? What is the best way to achieve this?
var myList = mutableListOf(1, 2, 3)
set(value) {
    field = value
    Handler(Looper.getMainLooper()).post {
        buttonCount.text = "${value.size}"
    }
}
fun main() {
    myList.add(1)
}

//Bad approach
fun fun1() {
    myList.add(1)
    buttonCount.text = "${myList.size}"
}

 //Bad approach
fun fun2() {
    myList.clear()
    buttonCount.text = "${myList.size}"
}


text:
Q: Is there a way to restart (Stop and Start) AWS ElasticSearch? Not sure why AWS ES does not allow the cluster to be stopped and started. I believe behind the scene its just a set of AWS EC2 instances that themselves could be easily stopped and started. This way customers may not have to take backup delete cluster, launch new restore from back up and then not to mention work with the new URL!! I understand that the service provider(AWS) needs to maintain/reserve the instances for customers while they are not "in the job".
Therefore,

*

*Is there a way to restart (stop and start) AWS ES?

*If not, aside from this possible financial non-viability is there any other key technical reasons I am missing that allows this kind of architecture to be the most appropriate?
BTW, I looked at elastic.co and they have same concept (Except they call it "shutdown").

Thanks,
Rahul


text:
Q: Are the Szpiro ratios of 37b1 over certain number fields {33,39,42,48,51,66}? Related to this question.
According to Hindry p.7 Conj 3.1
and Stein's notes Szpiro's conjecture over number fields states that the Szpiro ratio is:
$$ \sigma_{E/K}=\frac{\log{|N_{K/Q}\Delta_{E/K}|}}{\log{|N_{K/Q} f_{E/K}}|}$$
Given $ \varepsilon >0$ there are only finitely many $ E/K$ with $ \sigma_{E/K}\geq 6+\varepsilon $. In particular, $ \sigma_{E/K}$ is bounded.
$\Delta_{E/K}$ is the minimal discriminant and $f_{E/K}$
is the conductor.
To my knowledge over the rationals the largest known Szpiro ratio
is about $9.01$.
Consider the elliptic curve with cremona label 37b1 and ainvariants
$[0, 1, 1, -23, -50]$. Over the rationals the discriminant is
$37^3$. Over the number field with defining polynomial
$x^{22} - 37^3$ the norm of the minimal discriminant is $37^{66}$ and the
norm of the conductor is $37$ while the global minimal model is the same
as over the rationals, giving Szpiro ratio $66$. If this pattern continue
for number fields of the form $x^n - 37^3$, the Szpiro ratio probably
will be unbounded.
Computation with sage, possibly assuming GRH since the number fields are not
certified suggest the following large Szpiro ratios {33,39,42,48,51,66}:
a_i= [0, 1, 1, -23, -50]  ratio= 33.00000 Delta= 37^33 f= 37 d_E/Q= 37^3  global minimal model= Elliptic Curve defined by y^2 + y = x^3 + x^2 + (-23)*x + (-50) over Number Field in w with defining polynomial x^11 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 39.00000 Delta= 37^39 f= 37 d_E/Q= 37^3  global minimal model= Elliptic Curve defined by y^2 + y = x^3 + x^2 + (-23)*x + (-50) over Number Field in w with defining polynomial x^13 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 42.00000 Delta= 37^42 f= 37 d_E/Q= 37^3  global minimal model= Elliptic Curve defined by y^2 + y = x^3 + x^2 + (-23)*x + (-50) over Number Field in w with defining polynomial x^14 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 48.00000 Delta= 37^48 f= 37 d_E/Q= 37^3  global minimal model= Elliptic Curve defined by y^2 + y = x^3 + x^2 + (-23)*x + (-50) over Number Field in w with defining polynomial x^16 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 51.00000 Delta= 37^51 f= 37 d_E/Q= 37^3  global minimal model= Elliptic Curve defined by y^2 + y = x^3 + x^2 + (-23)*x + (-50) over Number Field in w with defining polynomial x^17 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 66.00000 Delta= 37^66 f= 37 d_E/Q= 37^3  global minimal model= Elliptic Curve defined by y^2 + y = x^3 + x^2 + (-23)*x + (-50) over Number Field in w with defining polynomial x^22 - 50653

Q1 Are the computations correct?
Q2 Does increasing the degree of the number field continue to increase the ratio?
Q3 (New) Is this a counterexample this formulation of Szpiro's conjecture? My concern is bounded, not infinitely many?

Working will large degree fields is not fast for me.

Small search found 46 ratios greater than $24$.
The largest is $134.6199$ from ainvariants $[1, 1, 1, -110, -880]$
 a_i= (1, 1, 1, -110, -880)  ratio= 134.6199 Delta= -1 * 3^304 * 5^19 f= 3 * 5 d_E/Q= -1 * 3^16 * 5  global minimal model= Elliptic Curve defined by y^2 + x*y + y = x^3 + x^2 + (-110)*x + (-880) over Number Field in w with defining polynomial x^19 + 215233605

Added Addressing Jamie Weigandt answer.
With his code and possibly assuming GRH, I get the same ratio.
To assume GRH, replace K.<a> = NumberField(x^11 - 50653)
with K.<a> = NumberField(x^11 - 50653,check=False). This avoids
certification of the NF with pari's bnfcertify.
Here is the output of
Nf.<w>=NumberField(x**D-d)
Nf.<w>=NumberField(x**D-d,check=False) #assume GRH
print 'a_i=',ai,' ratio=',szpiro_ratio(E2),Nf

a_i= [0, 1, 1, -23, -50]  ratio= 30.0 Number Field in w with defining polynomial x^10 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 33.0 Number Field in w with defining polynomial x^11 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 39.0 Number Field in w with defining polynomial x^13 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 42.0 Number Field in w with defining polynomial x^14 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 48.0 Number Field in w with defining polynomial x^16 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 51.0 Number Field in w with defining polynomial x^17 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 57.0 Number Field in w with defining polynomial x^19 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 60.0 Number Field in w with defining polynomial x^20 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 66.0 Number Field in w with defining polynomial x^22 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 69.0 Number Field in w with defining polynomial x^23 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 75.0 Number Field in w with defining polynomial x^25 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 78.0 Number Field in w with defining polynomial x^26 - 50653
a_i= [0, 1, 1, -23, -50]  ratio= 84.0 Number Field in w with defining polynomial x^28 - 50653

According to pari's documentation, the comment: #Don't do this. It will take forever probably will mean GRH fails for this NF, since in this case
pari's bnfcertify doesn't return.
Regarding his comment about Q2 and 32a1:  32a1 has $a_6=0$, so the
ratio degrades for trivial reasons. I didn't claim high ratio for it.
The claim that the ratio is bounded over number fields is from
here and William Stein' notes
Similar definition of the Szpiro's conjecture is in Silverman's
The Arithmetic of Elliptic Curves, p. 275.
With the above notation, there is constant $k$, depending on $\epsilon$
and $K$ s.t.:
$$ N_{K/Q} \Delta_{E/K} \le k(N_{K/Q} f_{E/K})^{6+ \epsilon}\qquad (2) $$
Silverman asks "It is very interesting to ask how the constants $k$ appearing in these conjectures depend on the field $K$."
In analogy with the uniform abc conjecture, probably Silverman should take $k$ the discriminant of $K$.

A: The correct discriminant ideal to compute is a locally defined ideal
$$\mathcal D_{E/K}^\text{min} = \prod_{\frak {p}} {\frak{p}}^{v_\frak{p}}$$
where $v_{\frak p}$ is the valuation of the discriminant of a local minimal model of $E$ at $p$. For general number fields, global minimal models do not exist. They exist if and only if the class number is 1.
This may or may not bring down your Szpiro ratios. If it doesn't, I still don't think this is inconsistent with Szpiro's conjecture since the finite set of counterexamples depends both on $\epsilon$ and the number field $K$. For every number field $K$ there is a finite (and sometimes non-empty) set of elliptic curves over $K$ with everywhere good reduction. These curves have conductor ideal $(1)$ so the Szpiro ratio can arguably be taken to be $\infty$.
I can't say whether your discriminant calculations are correct because I'm not sure how exactly you computed them, and working in these number fields is a bit too hard for me to do the calculations myself today. Here's code to compute the honest Szpiro ratio:
def szpiro_ratio(E):
    #Only works over number fields.
    N = E.conductor()
    nN = N.norm()
    S = N.prime_factors()
    local_norms =[p.norm()^E.local_minimal_model(p).discriminant().ord(p) for p in S]
    nD = prod(local_norms)
    return log(RDF(abs(nD)))/log(RDF(abs(nN)))

To do these calculations, I would try:
sage: E = EllipticCurve('37b1')
sage: K.<a> = NumberField(x^11 - 50653)
sage: EK = E.base_extend(K)
sage: szpiro_ratio(EK) #Don't do this. It will take forever.

Then I would give up after 10 minutes because it would be clear that this is not a feasible approach for such high degree number fields. There might be a way around this difficulty with high degree number fields. I'd look at the code for local_minimal_model?? and try doing it by hand for primes in $K$ above $37$ to understand what's going it.
Here's an example where the code does work, and gives a negative answer to Q2.
sage: E = EllipticCurve('32a1').quadratic_twist(97)
sage: K.<a> = QuadraticField(97)
sage: L.<b> = NumberField(x^4 - 97)
sage: szpiro_ratio(E.base_extend(K))
2.4
sage: szpiro_ratio(E.base_extend(L))
2.25

EDIT: (Fixed some inaccuracies, and added a more reasonable explanation for the $2-2g$ term.
Look at the Shioda-Tate formula:
$$ N = \frac{D}{6} + 2 - 2g  + r + (h^{1,1} - \rho).$$
This is the elliptic surface analog of Szpiro's conjecture. Here $N$ is the conductor degree, $D$ is the discriminant degree, $r$ is the Mordell-Weil rank, $(h^{1,1} - \rho)$ is a non-negative number we don't need to worry about. We do have to worry about $2-2g$ where $g$ is the genus of the base curve.
There are two things this could be reflecting in the number field case.
(1) The negative $2g$ could be accounting for the difference between the minimal discriminant ideal and the discriminant ideal attached to a global model, since it measures the size of the Picard group of the base.
(2) (2-2g) could be correspond to something like $(1 + \epsilon)\log|\text{Disc}_{K/\Bbb Q}|$. Maybe both are related to the degree of some canonical divisor. I suppose this would be an Arakelov divisor in the number field case.
I think the second interpretation seems more reasonable, and agrees with what you're trying to say.


text:
Q: Do we have '@' operator in embedded c or embedded c++ ? If yes please explain me the below code? code:
static volatile unsigned char   TMR0    @ 0x01;

static volatile unsigned char   PORTA   @ 0x05;

static volatile unsigned char   PORTB   @ 0x06;

static volatile unsigned char   PORTC   @ 0x07;

This code is from HT-PICC compiler pic.h library file for PIC16F877A
I understand what static volatile and other keyword means .
Here Timer0 register address is 0x01 but why they use @ in front of it? Does it have something to do with pointer?

A: It's a common compiler extension in many embedded compilers, which allows you to place variable in absolute memory address.
From HI-TECH C compiler manual:

3.5.4 Absolute Variables
Most variables can be located at an absolute address by following its declaration with
  the construct
  @ address, where address is the location in memory where the variable is to be positioned. Such a variables is known as an absolute variables.
3.5.4.1
  ABSOLUTE VARIABLES IN DATA MEMORY
Absolute variables are primarily intended for equating the address of a C identifier with
  a special function register, but can be used to place ordinary variables at an absolute
  address in data memory.

In your example:
static volatile unsigned char   TMR0    @ 0x01;

TMR0 is presumably 8-bit unsigned hardware register which exists at address 0x01.

A: It is an variable located at(@) a specific memory location. So there is an 8 bit variable TMR0 located at address 0x01. In the manual for the Hi-Tech C compiler for PIC see section 3.4.4 Pointer types for more information.
In vanilla C the equivalent would be:
static volatile unsigned char * TMR0 = (volatile unsigned char *) 0x01;
The @ operator is used in architectures with very low memory to help lower the memory footprint.

A: This is a common non-standard notation for allocating a variable at a specific address. In your case, it is used to map hardware registers to C variables.
Specifically, the purpose of @ is to allow a linker/debugger to use the registers as if they were objects. Meaning that you can add a watch or rw breakpoint on them in the debugger, like with any other variable.
Otherwise, if you have no need to view these in the debugger, you can use the standard C equivalent:
#define TMR0 (*(volatile uint8_t*)0x01u)

And of course, there's no need to allocate room for hardware registers, since they are already there in the hardware regardless of what the C program does.
Good debuggers come with MCU support and have the option to view MCU-specific registers in a separate window. So the main reason for using @ for registers/register maps, is because the tool chain comes with a crappy debugger. This is sadly my experience of embedded tool chains: the worse the debugger is, the messier the compiler-provided register map becomes.
But the @ notation can also be used for declaring RAM/ROM variables at specific locations. Other non-standard extensions by other compilers use various #pragma, ___declspec(section... or __attribute__(section.... Would be nice if a standard way existed, but sadly there is none.


text:
Q: Phonegap app don't work with IPv6 on iPhone I have PhoneGap based application that uses WebSockets. It works well under Android and Windows (via Chrome) - both for IPv4 and IPv6. However, on iPhone it works with IPv4 only.
For example, if I use address "104.217.75.167" (my test server), it works on Android, Windows and iPhone. If I use "::ffff:104.217.75.167" or "::ffff:68d9:4ba7" (the same), it works on Android and Windows only, but not on iPhone.
I guess the problem is in Safari browser (WebKit) because PhoneGap engine uses it as a base of application. But I have no Mac to debug it.
The code I use is this:
    const ip_input = <HTMLInputElement>document.getElementById("ipaddress");
    const ip: string = ip_input.value.replace(/\s/g, ''); // remove spaces
    const isIpV6 = ip.includes(':');
    const bracketedIp = isIpV6 ? '['+ip+']' : ip;
    const fullAddr: string = "ws://" + bracketedIp + ":44405/websocket";
    TheSocket = new WebSocket(fullAddr);

What can be wrong?


text:
Q: Пишет "Приложение не установлено" на планшете. На телефоне все ок Скорей всего что-то с permission, но я все закомментил и все равно. Приложение уже удалил, ставлю новой - та же ошибка. На телефон ставится нормально и запускается тоже.
Кто-то сталкивался с данной проблемой?
Манифест:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="lnk.iclient">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings" />
        <activity
            android:name=".LoginActivity"
            android:label="@string/title_activity_login"></activity>

    </application>

</manifest>

A: В общем убрал из build.gradle вот эти лишние сервисы и все встало:
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.google.android.gms:play-services-location:8.1.0'
     спасибо всем!

A: Подобное может произойти если:

*

*На девайсе не включены настройки разработчика и не разрешён режим отладки.

*Девайс не находится в режиме, позволяющем доступ к памяти (например находится в режиме зарядки)

*В манифесте запрещено устанавливать приложение на девайсы с большим экраном (<supports-screens android:largeScreens="false" android:xlargeScreens="false")

*minSdkVersion больше, чем SDK девайса.

*В манифесте есть требование на доступ к датчикам, не имеющимся на девайсе. Например запрос на тачСкрин. Таки есть же, наверное, такие планшеты - без тача...

*Битый кабель. Попробуйте другой. Да, бывает, что один кабель работает с телефоном и не работает с планшетом.


text:
Q: how to make a tab in chrome into a live chat window I would like to make a tab in Google Chrome (http://web.whatsapp.com) into a live chat window so that it is separate from other chrome tabs, similar to this.
How can I do this?

A: In order to seperate a tab from the main window and create a new one, all you have to do is:

*

*Click and hold on the tab you want to seperate.

*Drag the tab away from the top bar that contains the tabs.

*Release the tab wherever you want Google Chrome to spawn a new window.

However, in order to make it into a popup window like in your screenshot, you would have to add an extension to Google Chrome.  I personally like this extension, as it is a one-click solution.


text:
Q: Observable ViewModel with sharedPreferences The LoginPreferences is used to persist data with sharedPreference.
private const val PREF_LOGIN_NAME = "loginName"
private const val PREF_LOGIN_PASS = "loginPass"

object LoginPreferences {

    fun getStoredName(context: Context): String {
        val prefs = PreferenceManager.getDefaultSharedPreferences(context)
        return prefs.getString(PREF_LOGIN_NAME, "")!!
    }

    fun setStoredName(context: Context, query: String) {
        PreferenceManager.getDefaultSharedPreferences(context)
            .edit()
            .putString(PREF_LOGIN_NAME, query)
            .apply()
    }

    fun getStoredPass(context: Context): String {
        val prefs = PreferenceManager.getDefaultSharedPreferences(context)
        return prefs.getString(PREF_LOGIN_PASS, "")!!
    }

    fun setStoredPass(context: Context, query: String) {
        PreferenceManager.getDefaultSharedPreferences(context)
            .edit()
            .putString(PREF_LOGIN_PASS, query)
            .apply()
    }
}

The LoginViewModel is a ViewModel use sharedPreferences to be observable data binding in fragment_login.xml.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="loginViewModel"
            type="com.example.login.LoginViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout>
        ...
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

But if I want LoginViewModel to work with sharedPreference and observable data binding, it report a one super class error.
// (private val app: Application) : AndroidViewModel(app) is used to access to the sharedPreference.
// BaseObservable() is used to observe the data binding in xml file.
class LoginViewModel(private val app: Application) : AndroidViewModel(app), BaseObservable() {

    ...
}


text:
Q: Multiple DefaultMessageListenerContainer instances with different message selectors I have a requirement where i have messages in a queue with configurable number of message selectors. Where I need to process those messages parallely.
After careful consideration I came to a point where using multiple DefaultMessageListenerContainers will yield good results.
so I configured everything
<bean id="parallelProcess"
      class="org.springframework.jms.listener.DefaultMessageListenerContainer"  scope="prototype">
    <property name="connectionFactory" ref="jmsConnectionFactory"/>
    <property name="autoStartup" value="false"/>
    <property name="destinationName" value="parallel.process.queue"/>
    <property name="messageListener" ref="messageProcessor"/>
</bean>

and creating DefaultMessageListenerContainers on the fly
for (String selector : messageSelectors.getSelectors()) {
        parallelProcess.setMessageSelector("Message" + " = '" + selector + "'");
        parallelProcess.start();
    }

the problem is, if I have 3 selectors it is creating DefaultMessageListenerContainer for only the last one. i.e., if selectors={"TYPE1", "TYPE3", "TYPE3"}
only messages with TYPE3 are caught in message listener
Thank you in advance

A: After hours of researching and googling, found out that the foreach loop i am iterating is setting the same parallelProcess so it end up setting TYPE3
so the solution is to create a new bean every time you loop...
here is the solution
<bean id="myBeanFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
    <property name="targetBeanName">
        <idref local="parallelProcess"/>
    </property>
</bean>

 for (String selector : messageSelectors.getSelectors()) {
        DefaultMessageListenerContainer parallelProcess= myBeanFactory.getObject();
        parallelProcess.setMessageSelector(QueueDecisionProcessor.MESSAGE_CATEGORY + " = '" + selector + "'");
        parallelProcess.start();
    }


text:
Q: TCPDF ERROR: Error in 1D barcode string Getting the following error while generating 1D barcode images in pdf document with array of barcodes using tcpdf  module.

"TCPDF ERROR: Error in 1D barcode string"

if (file_exists("data1.txt"))
{
echo("File Exists data1.txt");
$arrText = file("data1.txt");
for ($i=0; $i<count($arrText); $i++)
{
echo("
$arrText[$i]
");
$pdf->write1DBarcode("'".chop($arrText[$i])."'", 'UPCA', '', '', '', 18, 0.4, $style, 'N');
$pdf->Ln();
}
}
else
{
echo("Cannot find file");
exit;
}

A: Normally this means that you are try to create a barcode using unsupported characters.
Each barcode type support only a character subset so, it is up to you to verify the code.
Keep in mind UTF-8 characters are normally not accepted. Check the documentation of the barcode type you are trying to use for further information, good-luck.


text:
Q: Doubt Regarding Function to check whether a tree is balanced or not? I read in a book named "Coding Interview Cracked", that to check whether a BST is balanced or not, just find out the difference between the maximum and minimum height but I not sure whether it is 100% correct. Though I am unable to find a counter test case.
Can anyone confirm whether this approach is correct or not.
For checking whether a tree is balanced or not.
|MaxHieght(root) - MinHieght(root)| <=1
   return true
else return false

A: Given the definition of balanced (from the Wiki of Pedias)

The balance factor of a node is the height of its left subtree minus
  the height of its right subtree (sometimes opposite) and a node with
  balance factor 1, 0, or −1 is considered balanced. A node with any
  other balance factor is considered unbalanced and requires rebalancing
  the tree. The balance factor is either stored directly at each node or
  computed from the heights of the subtrees.

This seems correct.  Since the minHeight and maxHeight are going to be equal to the height of either side, looks like the definition holds

A: You can try this way also, if you feel like.
bool isBalanced(node curPtr)
{
        static int heightLeft,heightRight; //Need to save previous return value

        if ( !curPtr )
        {
                return 0;
        }

        heightLeft  = isBalanced(curPtr->lChild);
        heightRight = isBalanced(curPtr->rChild);

        ++heightLeft;   // Height of the Tree should be atleast 1 ( ideally )
        ++heightRight;

        return ( ( ( heightLeft - heightRight ) == 0 ) || (( heightRight - heightLeft ) == 0 ) );
}

HTH


text:
Q: uniform sampling of the sphere w.r.t. inner products other than the usual one I will have a small (usually 2 or 3, probably no bigger than 6) positive integer $n$

and symmetric positive-definite real $n$-by-$n$ matrices $A$,

and will want to sample an $\:\mathbf{R}^n$-valued$\:$ random variable $\mathbf{x}$ such that
for any/all linear map(s) $\: f : \mathbf{R}^n \to \mathbf{R}^n \:$ such that $\Big[$for all vectors $v$, $\;\;v^{\hspace{0.015 in}T} Av\:=\:\left(||f(v)||_2\right)^2\;\;\Big]$,

$\big[||f(\mathbf{x})||_2 = 1 \:$ almost surely$\big]$ and $\big[f(\mathbf{x})$ is distributed uniformly on the unit sphere$\big]$
.

The way I thought of to do this is to Gram-Schmidt orthonormalize the standard basis

with respect to the inner product induced by $A$, and then take the linear combination with

coefficients given as the entries of a uniform sample from the unit sphere. $\:$ However, since I

will be sampling from $\mathbf{x}$ only once for each $A$, I'm hoping for a rather more efficient method.

Is there any faster way  to do the sampling I want?

(The matrices will be changing somewhat slowly, which might help.)

A: I think we can dispense with the "all linear maps" part, since all such linear maps are given by one such map followed by an arbitrary rotation of the unit sphere, which doesn't affect the uniform distribution; thus we can focus on a particular such map, $f(x)=A^{1/2}x$.
The problem is that you can easily apply $A$, but not $A^{-1/2}$. If the eigenvalues of $A$ are sufficiently similar and you have an efficient way to bound the least eigenvalue $\def\lmin{\lambda_{\text{min}}}\lmin\gt\kappa$ of $A$, you can get around this using rejection sampling: sample $x$ uniformly from the unit ball, reject the sample if $x^\top Ax\gt\kappa$, else divide it by $\sqrt{x^\top Ax}$ and use it. (Ideally, if you know $\lmin$, then $\kappa=\lmin$ yields the lowest rejection rate.)


text:
Q: Bind NodeJS app variables to Pivotal Cloud Foundry Service I am looking to bind a PCF (Pivotal Cloud Foundry) Service to allow us to set certain api endpoints used by our UI within PCF environment. I want to use the values in this service to overwrite the values in the root directory file, 'config.json'. Are there any examples out there that accomplish this sort of thing?

A: The primary way to tackle this is to have your application do this parsing.  Most (all?) programming languages give you the ability to load environment variables and to parse JSON.  Using these capabilities, what you'd want to do is to read the VCAP_SERVICES environment variable and parse the JSON.  This is where the platform will insert the information from your bound services.  From there you, you have the configuration information so you can configure your app using the values from your bound service.
Manual Ex:
var vcap_services = JSON.parse(process.env.VCAP_SERVICES)

or you can use a library.  There's a handy Node.js library called cfenv.  You can read more about both of these options in the docs.
https://docs.cloudfoundry.org/buildpacks/node/node-service-bindings.html
If you cannot read the configuration inside of your application, perhaps there's a timing problem and you need the information before your app starts, you can use the platform's pre-runtime hooks.
https://docs.cloudfoundry.org/devguide/deploy-apps/deploy-app.html#profile
The runtime hooks allow your application to include a file called .profile which will execute before your application.  The .profile file is a simple bash script which can do anything needed to ready your application to be run.  The only catch is that this needs to happen very quickly because it must complete before your application is able to start up and your application has a finite amount of time to start (usually 60s).
In your case, you could use jq to parse you values and insert them info your config file, perhaps using sed to overwrite a template value.  Another option would be to run a small Node.js script, since your app is using Node.js it should be available on the path when this script runs, to read the environment variables and generate your config file.
Hope that helps!


text:
Q: Flatten a nested array of objects over a array field Have an object a1 =
[{name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
{name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]]

Desired output:
[{name:'x',age:21, addr:{flat:1,add:'xyz'}},
{name:'x',age:21, addr:{flat:2,add:'xsr'}},
{name:'y',age:22, addr:{flat:3,add:'xyz1'},
{name:'y',age:22, addr:{flat:4,add:'xsr1'}]

Please suggest! I am trying to accomplish this using lodash/underscore.

A: Map every item in the original array to a new array, with a number of items according to the number of addr fields. Using concat flatten everything to a new array.
You can create new items using Object.assign() if you're transpiling to ES5 with babel or similar, as it's not supported by IE. However, since you're using angular, you can use angular.extend instead.
ES5:

var arr = [
  {name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
  {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}
];

var result = [].concat.apply([], arr.map(function(item) {
  return item.addr.map(function(addr) {
    return angular.extend({}, item, { addr: addr });
  });
}));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>

ES6:

const arr = [
  {name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
  {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}
];

const result = [].concat(...arr.map((item) => item.addr.map((addr) => Object.assign({}, item, { addr }))));

console.log(result);

A: You could iterate the array and the inner array for building the wanted result.

var array = [{ name: 'x', age: 21, addr: [{ flat: 1, add: 'xyz' }, { flat: 2, add: 'xsr' }] }, { name: 'y', age: 22, addr: [{ flat: 3, add: 'xyz1' }, { flat: 4, add: 'xsr1' }] }],
    result = array.reduce(function (r, a) {
        return r.concat(a.addr.map(function (b) {
            return { name: a.name, age: a.age, addr: b };
        }));
    }, []);

console.log(result);

ES6

var array = [{ name: 'x', age: 21, addr: [{ flat: 1, add: 'xyz' }, { flat: 2, add: 'xsr' }] }, { name: 'y', age: 22, addr: [{ flat: 3, add: 'xyz1' }, { flat: 4, add: 'xsr1' }] }],
    result = array.reduce((r, a) => r.concat(a.addr.map(b => ({ name: a.name, age: a.age, addr: b }))), []);

console.log(result);

A: You can use reduce(), forEach() and Object.assign() to return desired result.

var data = [{name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
{name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}];

var result = data.reduce(function(r, o) {
  o.addr.forEach(function(e) {
    r.push(Object.assign({name: o.name, age: o.age}, e));
  })
  return r;
}, []);

console.log(result)


text:
Q: Can all convex polytopes be realized with vertices on surface of convex body? Each convex polytope $P$ has a combinatorial type, its so-called face lattice. This lattice is just the poset of all faces of $P$ ordered by inclusion. Given one realization of such a combinatorial type, one can easily get many others. Just apply an arbitrary projective map to the given realization and the image will be combinatorially equivalent.
Now it would be very nice if one could realize every combinatorial type with vertices on the sphere. Unfortunately, this is not possible. For example, consider the octahedron with pyramids stacked on each facet -- this cannot have all vertices on the sphere (and still be convex).
So my questions is:
Is there a convex body in $\mathbb{R}^d$ such that every possible combinatorial type of a $d$-dimensional convex polytope can be realized with vertices on its surface?

A: I asked this question on MathOverflow and Sergei Ivanov gave an answer in the affirmative. See here for his beautiful argument.


text:
Q: Linearization of differential equations I was wondering if one could define an operator such that, when I give a certain number of (differential) equations as an output, and an "equilibrium" value for each of the variables, it returns the linear part in the perturbative expansion of the above-mentioned equations about the reference
For example, given:
$$\partial_t X + \partial_x Y+X\partial_xY+XY=0$$
and equilibrium values: $X=X_0+\delta X, Y=0+\delta Y$
Output would be, the linearized:
$$\partial_t (\delta X) + \partial_x (\delta Y)+X_0\partial_x(\delta Y)+X_0\ \delta Y=0$$

A: How about this:
Clear[x, t, X, Y, X0, δ, ϵ];
With[
  {functions = {X, Y},
   equilibrium = {X0, 0}
   },
  Normal@Series[
     D[X[t, x], t] +
        D[Y[t, x], x] +
        X[t, x] D[Y[t, x], x] +
        X[t, x] Y[t, x] == 0 /.
      Thread[functions ->
        Map[Function[{t, x}, #] &,
         equilibrium + ϵ Through[
            Thread[δ[functions]][t, x]]]
       ], {ϵ, 0, 1}] /. ϵ -> 1
  ] // TraditionalForm

$$\delta (X)^{(1,0)}(t,x)+\text{X0}\, \delta
   (Y)(t,x)+\text{X0} \,\delta (Y)^{(0,1)}(t,x)+\delta
   (Y)^{(0,1)}(t,x)=0$$

In the differential equations, X and Y are functions, so that a replacement must substitute a Function in their place. I do the linearization by the common trick of expanding linearly with respect to a dummy parameter $\epsilon$ and setting $\epsilon = 1$ at the end.
Here I used $\delta(X)$, $\delta(Y)$ for the linear terms. They are functions of x and t, whereas X0 is a constant. Since these two objects appear in a sum, I have to wrap that sum by Function in the replacement that is applied to the differential equation.
Here is a function that does the same as above:
op[eqn_, functions_, equilibrium_] :=
 Module[{ϵ},
  Normal@Series[
     eqn /. Thread[
       functions ->
        Map[Function[{t, x}, #] &,
         equilibrium + ϵ Through[
            Thread[δ[functions]][t, x]]]], {ϵ, 0,
      1}] /. ϵ -> 1
  ]

With[{
  eqn = D[X[t, x], t] + D[Y[t, x], x] + X[t, x] D[Y[t, x], x] +
     X[t, x] Y[t, x] == 0,
  functions = {X, Y},
  equilibrium = {X0, 0}
  },
 op[eqn, functions, equilibrium]
 ]//TraditionalForm

$$\delta (X)^{(1,0)}(t,x)+\text{X0}\, \delta
   (Y)(t,x)+\text{X0} \,\delta (Y)^{(0,1)}(t,x)+\delta
   (Y)^{(0,1)}(t,x)=0$$

A: Beginning with
D[X[t, x], t] + D[Y[t, x], t] + X D[Y[t, x], x] + X Y == 0

First replace the derivative by some other function to simplify manipulations.
%[[1]] /. Derivative[z1__][z2__][z3__] -> W[{z1}, z2, {z3}]

Make the first order substitution.
%/. {X -> X0 + d X1, Y -> Y0 + d Y1}

Expand the second argument of W.  (Depending on the complexity of the second argument, more transformations may be needed.)
%/. W[z__] :> Thread[W[z], Plus] /. W[z1__, d z2__, z3__] :> d W[z1, z2, z3]

Perform Series and extract the Coefficient of d.
Coefficient[Normal[Series[%, {d, 0, 1}]], d]

Finally, replace W by Derivative
(% /. W[{z1__}, z2_, {z3__}] :> Derivative[z1][z2][z3]) == 0
(* X1*Y0 + X0*Y1 + X1*Derivative[0, 1][Y0][t, x] + X0*Derivative[0, 1][Y1][t, x]
   + Derivative[1, 0][X1][t, x] + Derivative[1, 0][Y1][t, x] == 0 *)

This process is laborious because such functions as Expand  do not work with Derivative.  Perhaps, in a future release of Mathematica.
Addendum
Note that a much simpler approach is available, if the equation to be linearized exists in an Unevaluated form.
Unevaluated[(D[X[t, x], t] + D[Y[t, x], t] + X[t, x] D[Y[t, x], x] + X[t, x] Y[t, x] == 0)] /.
  {X[t, x] -> X0[t, x] + d X1[t, x], Y[t, x] -> Y0[t, x] + d Y1[t, x]};
Coefficient[Normal[Series[%[[1]], {d, 0, 1}]], d] == 0

yields the desired result.


text:
Q: Matlab : Reading strings and numbers to workspace so this is my excel file test.xlsx
have    1.44E+12    33   noChange   1.44E+12
four    1.44E+12    466  noChange   1.44E+12
have    1.44E+12    467  noChange   1.44E+12
four    1.44E+12    100  noChange   1.44E+12
minutes 1.44E+12    666  noChange   1.44E+12

I used EyeT = xlsread(test.xlsx)
and im getting the numbers right, but NaN for the string values.
Is there any other function to read it? Textscan maybe?

A: Use the three outputs of xlsread. Here's an example:
Excel file:
have    1   aa  5
four    2   bb  6
have    3   bb  67

Matlab code:
>> [num, txt, raw] = xlsread('test.xls')
num =
     1   NaN     5
     2   NaN     6
     3   NaN    67
txt =
    'have'    ''    'aa'
    'four'    ''    'bb'
    'have'    ''    'bb'
raw =
    'have'    [  1]    'aa'     [  5]
    'four'    [  2]    'bb'     [  6]
    'have'    [  3]    'bb'     [ 67]
    [ NaN]    [NaN]    [NaN]    [NaN]

As you can see, num is a matrix containing the numbers, and NaN for strings; txt is a cell array of strings, with '' for numbers; and raw is a cell array containing numbers and strings.


text:
Q: Suppose that $f''(x)>a$ for all $x\in \mathbb{R}$ and some $a>0$. Proof that $f$ has a absolute minimun. Let $f: \mathbb{R} \to \mathbb{R}$ of class $C^2$ i.e $f$ is differentiable with continuous  second derivative. Suppose that $f''(x)>a$ for all $x\in \mathbb{R}$ and some $a>0$. Proof that $f$ has a absolute minimun.
I have tried to solve this problem without any success, my attempt is:
Let $x>0$. By fundamental theorem of calculus we have that
$\int_{0}^{x} f''(t)dt=f'(x)-f'(0).$ Then $$f'(x)=f'(0)+\int_{0}^{x} f''(t)dt\geq f'(0)+ax$$ for all $x>0$.
On the other hand, note that $\int_{0}^{x} f'(t)dt=f(x)-f(0)$ so $$f(x)=f(0)+\int_{0}^{x} f'(t)dt\geq f(0)+\int_{0}^{x} (f'(0)+at)dt$$ I just conclude
$$f(x)\geq f(0)+f'(0)x+\frac{1}{2}ax^2 \text{ for all } x\in \mathbb{R}$$
I have only found that $f$ is above a quadratic function but I would actually think that the local minimum would be the vertex of the quadratic function.
Any suggestion is appreciated.

A: Your inequality shows that the function $f$ tends to $+\infty$ both for $x$ going to $-\infty$ and to $+\infty$.
A continuous function that has $+\infty$ as its limit both for $x$ going to $-\infty$ and to $+\infty$ has a minimum.
This follows from the fact that there is a closed interval $[-A,A]$ outside of which $f$ is larger than $f(0)$. Then use the fact that a continuous function on $[-A,A]$ has always a minimum.

A: Just observe that $f'(x) $ is strictly increasing and hence it either tends to a limit or to $\infty$ as $x\to \infty$. If it tends to a limit $L$ then $$f'(x+1)-f'(x)\to L-L=0$$ By mean value theorem the left hand side equals $f''(c) $ and it thus always exceeds a positive number $a$. So the above equation can't hold and thus $f' (x) \to\infty $ as $x\to\infty $.
Similarly $f'(x) \to-\infty $ as $x\to-\infty $. And by intermediate value theorem we see that $f'$ vanishes somewhere say at $c$. Since the derivative $f'$ is strictly increasing, $f'$ vanishes only at $c$. Then $f'<0$ in $(-\infty, c) $ and $f'>0$ in $(c, \infty) $. Then $f$ is strictly decreasing in $(-\infty, c] $ and strictly increasing in $[c, \infty) $. Then $f$ attains absolute minimum at $c$.
There is no need to assume continuity of second derivative.


text:
Q: Materializecss sidenav not working I am trying to get the sidenav to work for the Materializecss framework.
MATERIALIZECSS http://next.materializecss.com/getting-started.html
SIDENAV DEMO http://next.materializecss.com/sidenav.html
MY CODEPEN https://codepen.io/gregoryksanders/pen/RxoyqB

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/

cloudFirst Link With Icon

Second Link

Subheader

Third Link With Waves

    menu

3 Days trying to figure this out :/ so any help is welcomed.

A: The problem is that you should initialize the side-nav in Javascript code like this
 var elem = document.querySelector('.sidenav');
  var instance = new M.Sidenav(elem);

   // with jquery

  $(document).ready(function(){
   $('.sidenav').sidenav();
  });

now your code will work perfect

 var elem = document.querySelector('.sidenav');
  var instance = new M.Sidenav(elem);

  // Initialize collapsible (uncomment the lines below if you use the dropdown variation)
  // var collapsibleElem = document.querySelector('.collapsible');
  // var collapsibleInstance = new M.Collapsible(collapsibleElem, options);

  // Or with jQuery

  $(document).ready(function(){
    $('.sidenav').sidenav();
  });

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/

      John Doe
      jdandturk@gmail.com

cloudFirst Link With Icon

Second Link

Subheader

Third Link With Waves

  menu

A: On the materialize website, this code is given to initialize Sidenav bar
document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.sidenav');
    var instances = M.Sidenav.init(elems, options);
});

but You modify This code and remove option in var instance and now code look like and you should paste this code in  your script tag  or your javascript file
document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.sidenav');
    var instances = M.Sidenav.init(elems);
});

Now I explain what is the problem in upper code that given on the materialize website
in code, variable instances give 2 arguments 1st argument is elems and 2nd argument is the option that is not defined in your code so you remove the option argument in this code to solve this problem

A: Initialization is the most important thing when using materialize.js, for example i want to initialize a carousel.
  // Javascript

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.carousel');
    var instances = M.Carousel.init(elems, options);
  });

  // Or with jQuery

  $(document).ready(function(){
    $('.carousel').carousel();
  });


text:
Q: Sails min, max, minLength, maxLength for number and string types gives userError I am using waterline v0.13.5 package with expressjs.

*

*I get an user error { userError: The attribute 'str' on the 'action' model contains invalid properties. The property 'minLength' isn't a recognized property. when trying to use min, max (with number type) and minLength, maxLength (with string type).

*This same type of error is also  received with isIn property when used like this "isIn": [1,2,3].

*autoPK: true also doesnt work as expected. It forces me to define _id in the model attributes definition and primaryKey key in the extend definition options.

*I am also not able to get the types validator function triggered in general. The function isStringType is not triggered when there is a entry into mongodb.
But the documentation for sails v1.0 says it can be done. This error is  occuring when I am trying to extend/create the model using the Waterline.Collection.extend function. I can specify manually the min and max but want to keep it dynamic for different attributes properties. So that is not a viable option.
waterline.registerModel(Waterline.Collection.extend({
    identity: 'action',
    datastore: 'recAuth',
    schema: true,
    tableName: 'action',
    autoPK: true,
    primaryKey: '_id',
    types: {
        isStringType: function (v) {
           console.log('String validator triggered');
           return typeof v === 'string';
        }
    },
    attributes: {
        "_id": {
            "type": "string"
        },
        "str": {
            "type": "string",
            "required": true,
            "minLength": 12,
            "isStringType": true
        }
    }
}));


text:
Q: Cann't get the router in composition api by useRouter()? <script setup>
import { useRouter } from 'vue-router'

const menus = useRouter();
console.log(menus);
</script>

it's not return the routers , but return an obejct like this:

So what I can do to fix that?

A: I'm usually like this, without using {}
import VueRouter from "vue-router";
const routes = [
 {
   path: "/",
   name: "Home",
   component: Home,
 },
];

const router = new VueRouter({
 mode: "history",
 base: process.env.BASE_URL,
 routes,
});


text:
Q: How to override Azure Sql connection in Azure portal I tried to override connectionstring in Azure portal with this connection :
Server=tcp:server.database.windows.net,1433;Database=mydatabase;User ID=username@server;Password=xxxxxx;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;

It gives me an error Keyword not supported: 'server' and when I tried it as:
metadata=res://*/DataAccess.MyDataBase.csdl|res://*/DataAccess.MyDataBase.ssdl|res://*/DataAccess.MyDataBase.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:server.database.windows.net,1433;initial catalog=MyDataBase;persist security info=True;user id=username@server;password=xxxxxx;MultipleActiveResultSets=True;App=EntityFramework""

It gives "Keyword not supported: 'metadata'. !!
So what is the exact connectionstring should I write ??
Also I tried all of connection string types as provided in the screenshot.

A: Ok I found an answer relative to my issue, but also I figured out something
First of all the connection string should be like
metadata=res://*/DataAccess.MyDataBase.csdl|res://*/DataAccess.MyDataBase.ssdl|res://*/DataAccess.MyDataBase.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:server.database.windows.net,1433;Database=MyDataBase;User ID=username@server;Password=xxxxxx;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"

And notice the quotation should be " not " , Also as Nick said it should be Custom .

A: The first connection string ('Server=..') is used for connecting directly to the database, without passing through Entity Framework.
The second connection string ('metadata=..') is an Entity Framework connection string. If you're using EF, you should mark the connection string in the Azure Management portal as 'Custom' as opposed to 'SQL Database'.

A: In the control panel, there is a spot on the Database Panel that says "Show database connection strings" that gives you complete connection strings for your database for ADO.Net, PHP, Java and ODBC. These can be used as a starting point, from which I added MARS support and a different user/password to mine.
Here is my connection string to help you out. We use this one to override in the Azure WebApps Control Panel.
Server=tcp:[AZURE_DB_NAME].database.windows.net,1433;Database=[DATABASE_NAME];User ID=[USER_ID];Password=[PASSWORD];Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;MultipleActiveResultSets=True

As to the Drop Down, we have it set to SQL Database.
One thing that comes to mind. Have you tried using your connection string in VS Debug mode to see what happens? You just have to configure your AzureDB to allow a remote connection from your IP for that to work. It could provide some insight for you that your connection is correct but something else is failing.

A: I tried solution from Mohamed Farrag but got this error:

System.ArgumentException: Keyword not supported:
  '.ssdl|res://*/dataaccess.MyDataBase.msl;provider'.

After removing DataAccess. from my connection string it worked:
metadata=res://*/MyDataBase.csdl|res://*/MyDataBase.ssdl|res://*/MyDataBase.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:server.database.windows.net,1433;Database=MyDataBase;User ID=username@server;Password=xxxxxx;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"


text:
Q: It is possible to stream voice from phone mic to Bluetooth speaker using HFP or HSP (api level 19-22)? I have some apps to play music, or audio file to bluetooth speaker or headset successfully, all the proccess made with AudioTrack loading media, but now it is necessary to me, to capture the input from the phone mic and stream it to a bluetooth speaker or headset.
AudioRecord(MediaRecorder.AudioSource.MIC,
                    RECORDER_SAMPLERATE, RECORDER_CHANNEL,
                    RECORDER_AUDIO_ENCODING, minsize);

Now, my question is, it is possible to achieve this with android sdk level from 19 and above using hsp, hfp or a2dp?

A: On Android you might use A2DP source to playback the audio out to remote, however for HF I don't think you can transfer the audio to remote since the HF/HS audio was configured directly from PCM->chip->air->chip->pcm out.


text:
Q: Using quadratic extensions, show that there is only one field of order $p^2$ for an odd prime $p$. I understand that this result has been proven before, but I am trying to prove it in another way that I can't seem to find on SE.
The question goes as follows:

Let $E$ be a quadratic extension of a field $F$. Let $S(E)$ be the set of all $a\in F$ such that $a\neq 0$ and $a$ is a square in $E$. Show that $E\cong E' \Leftrightarrow S(E)=S(E')$. Use this result to show that for any odd prime $p$, there is exactly one field of order $p^2$ up to isomorphism.

I have proven the forward implication of the first statement, but not the reverse implication. The proof for the forward implication uses the fact that isomorphism is surjective and preserves squares. Apart from that, I feel totally stuck, and I don't even know why this result helps me prove that there is only one field of order $p^2$. I haven't learned about Galois extensions yet, so I'm trying to avoid them in my proof.
Ultimately, my questions are:

*

*How do I show that $S(E)=S(E')\Rightarrow E\cong E'$?

*How does this result show that there is only one field of order $p^2$ for odd primes $p$?

*Why does the oddness of $p$ matter?


text:
Q: Changed integer value doesn't show up in other parts of the code? I'm sorry for the weird title, I didn't really know how to describe it. Basically I have a code that once the if statement is called, it changed the value of the integer, taxrate. I thought it was working, but once I try to call it into a JTextField in another part of the code, it shows up as 0. The IF statement is the following:
if (taxable >= 1 && taxable <= 9075){
        taxrate = (int) (taxable * .10);
    } else if (taxable >= 9076 && taxable <= 36900) {
        taxrate = (int) (taxable * .15 + 908);
    } else if (taxable >= 36901 && taxable <= 89350) {
        taxrate = (int) (taxable * .25 + 5082);
    } else if (taxable >= 89351 && taxable <= 186350){
        taxrate = (int) (taxable * .28 + 18195);
    } else if (taxable >= 186351 && taxable <= 405100){
        taxrate = (int) (taxable * .33 + 45355);
    } else if (taxable >= 405101 && taxable <= 406750) {
        taxrate = (int) (taxable * .35 + 45883);
    } else if (taxable >= 406751) {
        taxrate = (int) (taxable * .396);
    }

taxable is defined by the user, it has no defined value until the user inputs it.

A: Any value of taxable between 0 and 10 (excluding 10) will give you a taxrate of 0 with the code working flawlessly.
If this is not your case, please make sure that your taxable value is actually assigned before this comparison is made. It is possible that the program is never actually getting to the code block inside the if statement.

A: First of all you need to clear up your code
if (taxable >= 1 && taxable <= 9075){
    taxrate =  (taxable * .10);
} else if (taxable >= 9076 && taxable <= 36900) {
    taxrate =  (taxable * .15 + 908);
} else if (taxable >= 36901 && taxable <= 89350) {
    taxrate =  (taxable * .25 + 5082);
} else if (taxable >= 89351 && taxable <= 186350){
    taxrate =  (taxable * .28 + 18195);
} else if (taxable >= 186351 && taxable <= 405100){
    taxrate =  (taxable * .33 + 45355);
} else if (taxable >= 405101 && taxable <= 406750) {
    taxrate =  (taxable * .35 + 45883);
} else if (taxable >= 406751) {
    taxrate =  (taxable * .396);
}

What is the point of having decimals if you cast them to an INT ? Integers can not have decimal places. If you want to have Decimals use Double - otherwise just dont use decimals.
Also make sure that taxable is initialized before the if block is executed
i.e.
private double taxable = "some value";


text:
Q: graphQL with mongoDB - is it possible to be TOO flexible with a query? I've recently started learning and using graphQL and I see that a common pattern is to make queries flexible enough to accept inputs such as _id, last, first, take, etc.
Is this the right way to form queries or are there any design patterns or best practices that can be followed ?.
For example, here's a resolver for a collection that is searchable and limitable.
Query: {
clients: async (parent, args, context) => {
  return await mongoDb
    .getCollection(CLIENTS_COLLECTION)
    .aggregate([
      {
        $match: {
          name: {
            $regex: args.input.text ? new RegExp(args.input.text) : '',
            $options: 'i'
          }
        }
      },
      { $limit: args.input.take || LIMIT }
    ])
    .toArray();
}
}

Should I also add inputs to find by _id in this same query? What about filtering and sorting? And is there such thing as too flexible?

A: You should look at GraphQL-to-MongoDB, or how I learned to stop worrying and love generated query APIs. It talks about a middleware package that leverages GraphQL's types to generate your GraphQL API and parses requests sent from clients into MongoDB queries. It features most of the standard query operations. This way you can enjoy all the flexibility offered by the package without having to implement it yourself for any change in your data models.
Disclaimer: this is my blog post.
The package generates GraphQL input types for your schema field args, and wraps around the resolve function to parse them into MongoDB queries.
Given a simple, classic GraphQLType declaration:
const PersonType = new GraphQLObjectType({
    name: 'PersonType',
    fields: () => ({
        age: { type: GraphQLInt },
        name: {
            type: new GraphQLNonNull(new GraphQLObjectType({
                name: 'NameType',
                fields: () => ({
                    firstName: { type: GraphQLString },
                    lastName: { type: GraphQLString }
                })
            }))
        }
    })
});

For the most common use case, you'll build a field in the GraphQL schema with a getMongoDbQueryResolver and getGraphQLQueryArgs. The filter, projection, and options provided by the wrapper can be passed directly to the find function.
person: {
    type: new GraphQLList(PersonType),
    args: getGraphQLQueryArgs(PersonType),
    resolve: getMongoDbQueryResolver(PersonType,
        async (filter, projection, options, source, args, context) =>
            await mongoDb.getCollection('person')
                .find(filter, projection, options).toArray()
    )
}

An example of a query you could send to such a field:
{
    person (
        filter: {
            age: { GT: 18 },
            name: {
                firstName: { EQ: "John" }
            }
        },
        sort: { age: DESC },
        pagination: { limit: 50 }
    ) {
        name {
            lastName
        }
        age
    }
}

There's also a wrapper and argument types generator for mutation fields.


text:
Q: Regression with inverse independent variable Let's suppose I have a $N$-vector $Y$ of dependent variables, and an $N$-vector $X$ of independent variable. When $Y$ is plotted against $\frac{1}{X}$, I see that there is a linear relationship (upward trend) between the two. Now, this also means that there is a linear downward trend between $Y$ and $X$.
Now, if I run the regression: $Y = \beta * X + \epsilon$
and get the fitted value $\hat{Y} = \hat{\beta}X$
Then I run the regression: $Y = \alpha * \frac{1}{X} + \epsilon$ and get the fitted value  $\tilde{Y} = \hat{\alpha} \frac{1}{X}$
Will the two predicted values, $\hat{Y}$and $\tilde{Y}$ be approximately equal?

A: I see no reason for them to be "approximately equal" in general -- but what exactly do you mean by approximately equal?
Here's a toy example:
library(ggplot2)
n <- 10^3
df <- data.frame(x=runif(n, min=1, max=2))
df$y <- 5 / df$x + rnorm(n)
p <- (ggplot(df, aes(x=x, y=y)) +
      geom_point() +
      geom_smooth(method="lm", formula=y ~ 0 + x) +  # Blue, OP's y hat
      geom_smooth(method="lm", formula=y ~ 0 + I(x^-1), color="red"))  # Red, OP's y tilde
p

The picture:

The "blue" model would do much better if it were allowed to have an intercept (i.e. constant) term...

A:
 When Y is plotted against $\frac{1}{X}$, I see that there is a linear relationship (upward trend) between the two. Now, this also means that there is a linear downward trend between Y and X

The last sentence is wrong: there is a downward trend, but it is by no means linear:

I used a $f(x) = \frac{1}{x}$ as function plus a bit of noise on $Y$. As you can see, while plotting $Y$ against $\frac{1}{X}$ yields a linear behaviour, $Y$ against $X$ is far from linear.
(@whuber points out that the $Y$ against $\frac{1}{X}$ plot doesn't look homoscedastic. I think it appears to have higher variance for low $Y$ because the much higher case density leads to larger range which is essentially what we perceive. Actually, the data is homoscedastic: I used Y = 1 / X + rnorm (length (X), sd = 0.1) to generate the data, so no dependency on the size of $X$.)
So in general the relationship is very much non-linear. That is, unless your range of $X$ is so narrow that you can approximate $\frac{d \frac{1}{x}}{dx} = - \frac{1}{x^2} \approx const.$ Here's an example:

Bottomline:

*

*In general, it is very hard to approximate a  $\frac{1}{X}$-type function by a linear or polynomial function. And without offset term you'll never get a reasonable approximation.

*If the $X$ interval is narrow enough to allow a linear approximation, you'll anyways not be able from the data to guess the relation should be $\frac{1}{X}$ and not linear ($X$).


text:
Q: Travis terminates deploy by timeout I'm trying to setup deployment on Travis CI, but even with travis_wait it still fails by timeout after 20 minutes

Timeout (20 minutes) reached. Terminating "bundle exec cap staging deploy"

My .travis.yml is
language: ruby
services:
- mongodb
- redis-server
rvm:
- 2.1.1
before_script:
- cp config/secrets.example.yml config/secrets.yml
- cd frontend && npm install -g bower && npm install && bower install
script:
- RAILS_ENV=test bundle exec rake db:create
- bundle exec rake rspec-rerun:spec
before_install:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
after_success:
- openssl aes-256-cbc -k $DEPLOY_KEY -in /home/travis/build/my-build_location/config/deploy_id_rsa_enc_travis -d -a -out /home/travis/build/my-build_location/config/deploy_id_rsa
- chmod 600 /home/travis/build/my-build_location/config/deploy_id_rsa
- cd /home/travis/build/my-build_location
- "[[ $TRAVIS_BRANCH = 'development' ]] && travis_wait bundle exec cap staging deploy"
env:
  global:
    secure: secret_key


text:
Q: TextBox.SelectAll() does not justify text to left in silverlight I have given a fixed width to the textbox and I don't want to wrap the text too. So the problem here is if I enter text larger then the width then on GotFocus event of a textbox I do the following :
txtperson.SelectAll();

But it doesn't justify the text from left ?
Any help how can I achieve this ?

A: Well, what you can easily do is to retemplate your textbox. when it gets focus you just change background color of the text and it will does the trick.


text:
Q: How to stop repaint() flickering I am trying to make a program to java and i have the common problem with flickering. I have try many things to eliminate but all the same. while the oval that i paint is moving the japplet is flickering. i need your help to solve this problem. here is my code:
import java.awt.Color;

public class all extends JApplet implements Runnable {

    double x=0;
    double y=0;
    int m=0;
    int n=0;
    int f=30;
    int μ=0;
    Thread kinisi;
    JPanel panel;
    JFrame frame;
    private boolean running = false;
    private JTextField textField1;
    private JTextField textField2;
    Image backGround;
    JPanel panel_3;
    Image bf = createImage(m, n);
    private Graphics doubleg;
    private Image i;

    public void init() {
        this.setSize(800, 700);
    }

    public all() {
        getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("Start");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String b=textField2.getText();
                String z =textField1.getText();
                if (textField1.getText().equals("") ||
                    textField2.getText().equals("")){
                    JOptionPane.showMessageDialog(
                        new JFrame(),
                        "Δωστε τιμή για το φ και το μ!",
                        "ERROR",JOptionPane.ERROR_MESSAGE);
        } else{
                f = Integer.parseInt(b);
                μ = Integer.parseInt(z);
                Start();    }
            }
        });
        btnNewButton.setBounds(469, 168, 89, 23);
        getContentPane().add(btnNewButton);

        JButton btnStop = new JButton("Pause");
        btnStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pause();
            }
        });
        btnStop.setBounds(588, 168, 89, 23);
        getContentPane().add(btnStop);

        JButton btnReset = new JButton("Reset");
        btnReset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Reset();
            }
        });
        btnReset.setBounds(701, 168, 89, 23);
        getContentPane().add(btnReset);

        JLabel label = new JLabel("\u03BC");
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setBounds(549, 63, 46, 14);
        getContentPane().add(label);

        textField1 = new JTextField();
        textField1.setBounds(529, 101, 86, 20);
        getContentPane().add(textField1);
        textField1.setColumns(10);

        JLabel label_1 = new JLabel("\u03C6");
        label_1.setHorizontalAlignment(SwingConstants.CENTER);
        label_1.setBounds(681, 63, 46, 14);
        getContentPane().add(label_1);

        textField2 = new JTextField();
        textField2.setBounds(667, 101, 86, 20);
        getContentPane().add(textField2);
        textField2.setColumns(10);

        JButton btnNewButton_1 = new JButton("");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JOptionPane.showMessageDialog(
                    new JFrame(),
                    "Οδηγίες προγράμματος","Οδηγίες",
                    JOptionPane.INFORMATION_MESSAGE);
                }
        });
        btnNewButton_1.setIcon(
            new ImageIcon(all.class.getResource("/Images/info.png")));
        btnNewButton_1.setBounds(732, 5, 39, 35);
        getContentPane().add(btnNewButton_1);

        JLabel label_2 = new JLabel("");
        label_2.setIcon(
            new ImageIcon(all.class.getResource("/Images/earth.jpg")));
        label_2.setBounds(-20, 0, 820, 361);
        getContentPane().add(label_2);

        JPanel panel_1 = new JPanel();
        panel_1.setBorder(
            new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
        panel_1.setBounds(10, 372, 369, 290);
        getContentPane().add(panel_1);

        JPanel panel_2 = new JPanel();
        panel_2.setBorder(
            new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
        panel_2.setBounds(408, 372, 369, 290);
        getContentPane().add(panel_2);
    }

    public void paint(Graphics g){
        super.paint(g);
        g.drawLine(0,f,350,200);
        g.drawLine(0,200,350,200);
        g.drawOval(m,n,40,40);
        Color brown=new Color(137,66,0);
        g.setColor(brown);
        g.fillOval(m, n, 40, 40);
        //Graphics2D g2d = (Graphics2D) g;
        g.drawLine(460,400,460,650);
        g.drawLine(20, 620, 350, 620);
        g.drawLine(50,400,50,650);
        g.drawLine(430, 620, 760, 620);
    }

    public void Start() {
        kinisi = new Thread(this);
        kinisi.start();
        running = true;
    }

    public void run() {
        while (running) {
            if (x < 340){
                double l = 200-f;
                double k = l/350;
                double y=k*x+f-30;
                x= x+1;
                m = (int) x;
                n = (int) y;
                repaint();
                try {
                    Thread.sleep(μ);
                } catch (InterruptedException ie) {}
            }
        }
    }

    public void update(Graphics g) {
        if(i==null){
            i=createImage(800,700);
            doubleg = i.getGraphics();
        }
        doubleg.setColor(getBackground());
        doubleg.fillRect(0,0,800,700);
        doubleg.setColor(getForeground());
        paint(doubleg);
        g.drawImage(i,0,0,this);
    }

    public void paint1(Graphics g){
        g.drawLine(0, f ,350, 200);
        g.drawOval(m, n, 40, 40);
        Color brown=new Color(137,66,0);
        g.setColor(brown);
        g.fillOval(m, n, 40, 40);
    }

    public void pause() {
        if (kinisi != null) {
            running = false;
        }
    }

    public boolean Reset() {
        if (kinisi != null) {
            running = false;
            kinisi.interrupt();
            kinisi = null;
            x=0;
            y=0;
            f=30;
            m=0;
            n=0;
            repaint();
            textField1.setText("");
            textField2.setText("");
        }
        Graphics g = getGraphics();
        g.drawOval(m,n,40,40);
        Color brown=new Color(137,66,0);
        g.setColor(brown);
        g.fillOval(m, n, 40, 40);
        return false;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("FISIKI");
        frame.getContentPane().add(new all());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 700);
        frame.setVisible(true);
        frame.setResizable(false);
    }
}

Thank you very much and sorry for my english are not very good!

A: There are a number of things that jump out at me.

*

*You're extending from JApplet, but are adding it to a JFrame

*You're mixing components with you custom painting

*Not using layout managers.

*Using getGraphics.

Firstly...
You should never override paint of a top level container (like JApplet).  There are many reasons and you've found one.  Top level containers are not double buffered.  Instead, you should be creating a custom component (by extending something like JPanel) and overriding it's paintComponent method...
Secondly
Decided how you application is going to be.  Is it an applet or application?  If you follow the first point, then it really doesn't matter, as you only simply need to add the panel to the top level container.
Thirdly
I would create a panel that did the custom painting.  Then I would create separate containers for all the fields and other parts of the application.  This will allow you to separate the areas of responsibility.  It would also allow you to use layout managers ;)
Fourthly
Use layout managers.  The layout manager API has being designed to solve one of this most annoying aspects of GUI design, you're asking for a lot of trouble and work you decided to discard it - IMHO.
Fifthly
getGraphics should never be used.  Apart from the fact that it can return null, it is only a snap shot of what is currently on the screen.  As soon as the RepaintManager decides to perform a repaint, anything rendered to it will be lost.  You should use paintComponent to update the state of your custom pane.


text:
Q: Space Shuttle related quote referring to a bird on the back of a giant bird As I look at this amazing picture  of the last flight related to the space shuttle taken by Ben Cooper, I am trying to recollect a line from some book (Science or Science fiction) that I read a long time back. It described space flight being imagined as a "Bird on the back of another Giant Bird", or some such words...
Does anyone here recollect the book, author, exact line?
I think it was Arthur C. Clarke but I am not sure and can't find the reference with what I remember.
There are strong connotations to the Virgin Atlantic take-off technique as that line described the idea of taking off from a higher altitude (if my memory serves).

A: Located in 2001: A Space Odyssey by Arthur C. Clarke
Chapter 7: Space Flight,
Dr. Heywood Floyd recalls a quotation of Leonardo da Vinci's displayed in a NASA office once,

The Great Bird will take its flight on the back of the great bird,
  bringing glory to the nest where it was born

Referencing Leonardo da Vinci's Codex on the flight of birds,

The great bird will take its first flight from the back of Monte Cecero,
  filling the universe with stupor, filling all writings with its fame and
  bringing glory to the nest in which it was born

Other references,

*

*Yale University, Leonardo and the Science of Bird Flight (PDF)

*Decoding da Vinci

*

*Drawings from the Biblioteca Real in Turin
(featuring the Codex on the Flight of Birds and 11 drawings by the artist)


text:
Q: User Register DB Issue So, this is a script to dump the user info into the database using the PDO driver.  Whenever I run the script with a unique username it works and it dumps the info in.  But, if a user with the same username tries to sign up it should throw an error.  I'm using $stmt->errorCode() == 23000 to check for duplicates in the database but whenever I try and register a username I've already registered I just get a blank white screen.  I've ran through the script with xDebug and it looks like when I try and sign up with a username that's already in the database it's not even hitting the if/else statements at the bottom of the script.  It's just executing and throwing a blank white screen.
EDIT:  I do have the username field in the DB set to 'unique'.
Video of xDebug walkthrough: http://screencast.com/t/znZfMgV2
Any ideas?
// create a salt using the current timestamp
$salt = time();

// encrypt the password and salt
$password = sha1($password.$salt);

// prepare the sql statement
$sql = 'INSERT INTO users (created, username, salt, password) VALUES(now(), :username, :salt, :password)';
$stmt = $conn->prepare($sql);
// bind the parameters
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':salt', $salt, PDO::PARAM_INT);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();

if ($stmt->rowCount() == 1) {
    $registerResult = "$username has been registered. You may now log in.";
} elseif ($stmt->errorCode() == 23000) {
    $registerResult = "$username is already in use. Please choose another username.";
} else {
    $registerResult = 'Sorry, there was a problem with the database';
}

A: Checking for errorcodes will not work, because the duplicate error will throw an exception on the call to execute().
You need to catch PDOException :
try {
    // create a salt using the current timestamp
    $salt = time();

    // encrypt the password and salt
    $password = sha1($password.$salt);

    // prepare the sql statement
    $sql = 'INSERT INTO users (created, username, salt, password) VALUES(now(), :username, :salt, :password)';
    $stmt = $conn->prepare($sql);
    // bind the parameters
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':salt', $salt, PDO::PARAM_INT);
    $stmt->bindParam(':password', $password, PDO::PARAM_STR);
    $stmt->execute();

    if ($stmt->rowCount() == 1) {
        $registerResult = "$username has been registered. You may now log in.";
    }
} catch (PDOException $e) {
    if ($stmt->errorCode() == 23000) {
        $registerResult = "$username is already in use. Please choose another username.";
    } else {
        $registerResult = 'Sorry, there was a problem with the database';
    }
    die($e->getMessage());
}

Make sure your connection is set up to throw exception of course:
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

A: Are PHP errors disabled? (The blank page makes me think so)
If so, try inserting
error_reporting(-1);
ini_set('display_errors', 'On');

in your code, maybe the blank page will start having some useful error messages on it.
(Do not use on live server though, obviously)


text:
Q: Write file in UTF-8 mode using Perl I need to write a file with UTF-8 mode in Perl. How do i create that?
Can anyone help in this case?
I'm trying like this, Find my below code,
use utf8;
use open ':encoding(utf8)';
binmode(FH, ":utf32");

open(FH, ">test11.txt");
print FH "something Çirçös";

It's creating a file with UTF-8 Format. But i need to make sure whether that is happening from this script. Because if i'm writing a file without using utf8 encode also, File content is automatically taking as UTF-8 format.

A: You want
use utf8;                       # Source code is encoded using UTF-8.

open(my $FH, ">:encoding(utf-8)", "test11.txt")
    or die $!;

print $FH "something Çirçös";

or
use utf8;                       # Source code is encoded using UTF-8.
use open ':encoding(utf-8)';    # Sets the default encoding for handles opened in scope.

open(my $FH, ">", "test11.txt")
    or die $!;

print $FH "something Çirçös";

Notes:

*

*The encoding you want is utf-8 (case-insensitive), not utf8 (a Perl-specific encoding).

*Don't use global vars; use lexical (my) vars.

*If you leave off the instruction to encode, you might get lucky and get the right output (along with a "wide character" warning). Don't count on this. You won't always be lucky.
# Unlucky.
$ perl -we'use utf8; print "é"' | od -t x1
0000000 e9
0000001

# Lucky.
$ perl -we'use utf8; print "é♡"' | od -t x1
Wide character in print at -e line 1.
0000000 c3 a9 e2 99 a1
0000005

# Correct.
$ perl -we'use utf8; binmode STDOUT, ":encoding(utf-8)"; print "é♡"' | od -t x1
0000000 c3 a9 e2 99 a1
0000005


text:
Q: How to convert string rule to an expression which has a range in R x1=3
x2=3
x3=4
x4=7
df_new = data.frame(x1,x2,x3,x4)

a<-"-3>x1>=1.45 & -3<=x2<3 & x4==7"
df_new <- data.frame(x1=3,x2=3,x3=4,x4=7)
eval(parse(text=a),df_new)

I need to convert the above rule to "-3>x1 & x1>=-1.45 & -3<=x2 & x2<3 & x4==7" using regular expressions. Currently it will prompt an error. Please help me to solve this.

A: I'd do it in several steps:

*

*Split on logical operators into separate inequalities.

*Change double inequalities like -3>x1>=-1.45 into two inequalities.

*Change "=" to "==", and put it all together.

For example:
a1 <- strsplit(a, "&", fixed = TRUE)[[1]]
a1a <- gsub(" ", "", a1) # get rid of spaces
a2 <- gsub("([-0-9.]+[<>=]+)([[:alpha:]]+[[:alnum:]]*)([<>=]+.+)",
           "\\1\\2 & \\2\\3", a1a)
a3 <- paste(gsub("[^<>]={1}", "==", a2), collapse = " & ")

which gives a3 equal to
[1] "-3>x1 & x1>=-1.45 & -3<=x2 & x2<3 & x==7"

This won't work if you have other logical operations besides &, or if your variables have non-alphanumeric characters like dots or underscores.  It will also fail on inequalities like x1 <= x2 <= x3.  I'll leave you to handle those cases if they come up.