text:
Q: How to protect service from gzip bomb? I have test.gzip file with json
{"events": [
{"uuid":"56c1718c-8eb3-11e9-8157-e4b97a2c93d3",
"timestamp":"2019-06-14 14:47:31 +0000",
"number":732,
"user": {"full_name":"0"*1024*1024*1024}}]}

full_name filed contains 1GB of 0, zipped filesize ~1Mb
how can I protect my service during unpacking so that my memory is not over?
func ReadGzFile(filename string) ([]byte, error) {
    fi, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer fi.Close()

    fz, err := gzip.NewReader(fi)
    if err != nil {
        return nil, err
    }
    defer fz.Close()

    s, err := ioutil.ReadAll(fz)
    if err != nil {
        return nil, err
    }
    return s, nil
}

func main() {
    b, err := ReadGzFile("test.gzip")
    if err != nil {
        log.Println(err)
    }
    var dat map[string]interface{}
    if err := json.Unmarshal(b, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}

In this case output can kill my service by OOMKiller

A: What can be deceiving is that the compressed size may be significantly smaller that the allowed size (the size you can or you wish to handle). In your example the input is about 1 MB, while the uncompressed size is about 1 GB.
While reading the uncompressed data you should stop after reaching a reasonable limit. To easily do that, you may use io.LimitReader() where you can specify the max amount of bytes you wish to read. Yes, you have to wrap the unzipped stream, not the original, compressed stream.
This is an example how it would look like:
limited := io.LimitReader(fz, 2*1024*1024)

s, err := ioutil.ReadAll(limited)

The above example limits the readable data to 2 MB. What happens when the unzipped data is more than that? The io.Reader returned by io.LimitReader() (which is by the way an io.LimitedReader) will report io.EOF. This protects your server from the attack, but might not be the best way to handle it.
Since you mentioned this is for a rest API, a better suited solution would be the similar http.MaxBytesReader(). This wraps the passed reader to read up until a given limit, and if that is reached, it returns an error, and also sends an error back to the HTTP client, and also closes the underlying read-closer. If the default behavior of http.MaxBytesReader() is not suitable for you, check its sources, copy it and modify it, it's relatively simple. Tune it to your needs.
Also note that you should not read everything (the uncompressed data) into memory. You may pass the "limited reader" to json.NewDecoder() which will read from the given reader while decoding the input JSON. Of course if the passed limited reader reports an error, the decoding will fail.

A: Don't read everything into memory. Operate on a stream if possible. This is 100% possible in your example:
func ReadGzFile(filename string) (io.ReadCloser, error) {
    fi, err := os.Open(filename)
    if err != nil {
        return nil, err
    }

    return gzip.NewReader(fi)
}

func main() {
    b, err := ReadGzFile("test.gzip")
    if err != nil {
        log.Println(err)
    }
    defer b.Close()
    var dat map[string]interface{}
    if err := json.NewDecoder(b).Decode(&dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}

This Decode approach has the side effect (which may or may not be desirable) of ignoring any garbage in the stream after the first valid JSON object.  In your case, this seems like a benefit. In some cases, it may not be.


text:
Q: Keyboard Overlaps Edittext - Activity Fullscreen I am working on chat application where Edittext and send button is at bottom.
Activity is fullscreen, hidden navigation and status bar.
I need to push edittext and send button up when keyboard comes into focus.

*

*I tried to set android:windowSoftInputMode="adjustResize" but it didn't worked.

*I tried using AndroidBug5497Workaround.assistActivity(this) class referred from https://github.com/madebycm/AndroidBug5497Workaround but it didn't worked.

Below is my activity theme and code in activity to hide bar and make full screen :
 decorView = getWindow().getDecorView();
    uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

Theme :
 <style name="AppTheme_DarkStatus" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryveryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>

XMl :
 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/include_view"
    android:isScrollContainer="true"
    android:background="@android:color/white">

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/lv_chat"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/rl_send"
        android:divider="@null"
        android:fadeScrollbars="false"
        android:fadingEdge="none"
        android:overScrollMode="never"
        android:scrollbars="none"
        ptr:ptrHeaderSubTextColor="@color/c_input_text_color"
        ptr:ptrHeaderTextColor="@color/c_input_text_color"
        ptr:ptrOverScroll="false"
        ptr:ptrPullLabel="Pull to refresh"
        ptr:ptrRefreshLabel="Loading..."
        ptr:ptrReleaseLabel="Release to refresh"
        ptr:ptrRotateDrawableWhilePulling="true"
        ptr:ptrShowIndicator="false" >
    </com.handmark.pulltorefresh.library.PullToRefreshListView>

    <RelativeLayout
        android:id="@+id/rl_send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/c_white"
        android:gravity="center" >

        <View
            android:id="@+id/view_dummy"
            android:layout_width="match_parent"
            android:layout_height="@dimen/d_diff_p5dp"
            android:background="@color/c_text_light_color" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/view_dummy"
            android:layout_toLeftOf="@+id/btn_send"
            android:layout_marginRight="@dimen/d_diff_5dp"
            android:layout_marginLeft="@dimen/d_diff_10dp"
            android:layout_marginTop="@dimen/s_diff_7sp"
            android:layout_marginBottom="@dimen/s_diff_7sp"
            android:background="@drawable/opawhite_rectcorner_all" android:id="@+id/relativeLayout">

            <EditText
                android:id="@+id/et_message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/d_diff_1dp"
                android:background="@null"
                android:focusableInTouchMode="true"
                android:maxHeight="100dp"
                android:hint="Type here..."
                android:maxLength="150"
                android:textSize="@dimen/s_diff_16sp"
                android:padding="@dimen/s_diff_6sp"
                android:textColorHint="@color/c_input_text_color"
                android:textColor="@color/c_black" />
        </RelativeLayout>

        <Textview
            android:id="@+id/btn_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/c_white"
            android:text="Send"
            android:padding="@dimen/d_diff_5dp"
            android:layout_marginRight="@dimen/d_diff_5dp"
            android:gravity="center"
            android:textColor="@color/c_orange_main"
            android:textSize="@dimen/s_diff_16sp"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"/>
    </RelativeLayout>
</RelativeLayout>

I want to show edittext and send button above keyboard but it overlaps edittext.
Thanks!

A: The property android:windowSoftInputMode="adjustResize" doesn't work with full screen activity, you have to remove activity full screen  flags in order to get advantage of adjust resize.
see this:
A fullscreen window will ignore a value of SOFT_INPUT_ADJUST_RESIZE for the window's softInputMode field; the window will stay fullscreen and will not resize.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i hide the  if the  appears I'm working on a WordPress site that automatically displays an h2 on the page as what the page/post is titled.  I want to manually create h1 for some pages and have the h2 to be hidden if the h1 appears.
Is there a way to do that?

A: There are two ways to do this, though one is arguably better than the other.
Use JavaScript (Works, but not optimal)
The first way to do this is by using JavaScript. I'm not a fan of using this approach because it requires a web browser to perform the toggling. This negatively impacts SEO because, to search engines, the element still exists in the document.
Still, if you opt for this approach, here's how you can do it...
Assuming that you page is setup something like this:

<?php the_title(); ?>

Some other text.

Then your JavaScript - jQuery-based (since WordPress uses jQuery) - would look like this:
if($('h1').is(':visible')) {
  $('h2').hide();
} // end if

You can make this code is a little bit clearer by providing ID's or class names on your heading elements. For example, say you've got the heading elements named as such:

<?php the_title(); ?>

This is a second title.

Then your JavaScript could look like this:
if($('#title').is(':visible')) {
  $('#alt-title').hide();
} // end if

Do it on the server-side
The better way to do this would be to actually set it up in the template file on the server-side.
Say, for example, you want to show an h1 only on single posts or pages but an h2 on archive pages or listing pages. You'd do it like this:
<?php if(is_page() || is_single()) { ?>

<?php the_title(); ?>

<?php } else { ?>

<?php the_title(); ?>

<?php } // end if/else ?>

This is better because the processing occurs on the server-side so that the document served to the requesting agent (that is, the search engine or the web browser) will only see a single-element.

A: I do this in my header.php file:
<?php $tag = ( is_front_page() ) ? 'h1' : 'h2'; echo '<' . $tag . ' id="branding">'; ?>
</<?php echo $tag; ?>>


text:
Q: Restore master database from SQL Server 2008 R2 on SQL Server 2012 I have a process that restores all my backups on a centralized server for testing. I have recently upgraded this server to SQL server 2012, and now I am getting an error when restoring master from SQL Server 2008 R2. Restores from SQL Server 2012 and SQL Server 2005 work fine. I get the same results when trying to restore to SQL 2014 as well.
This is my restore statement:
RESTORE DATABASE masttest
FROM DISK = 'c:\temp\master.bak'
WITH MOVE 'master' TO 'c:\temp\masttest.mdf',
MOVE 'mastlog' TO 'c:\temp\masttest.ldf';

And this is the results. The database ends up in Recovery pending.
Processed 400 pages for database 'masttest', file 'master' on file 1.
Processed 3 pages for database 'masttest', file 'mastlog' on file 1.
Converting database 'masttest' from version 661 to the current version 706.
Database 'masttest' running the upgrade step from version 661 to version 668.
Database 'masttest' running the upgrade step from version 668 to version 669.
Database 'masttest' running the upgrade step from version 669 to version 670.
Database 'masttest' running the upgrade step from version 670 to version 671.
Database 'masttest' running the upgrade step from version 671 to version 672.
Database 'masttest' running the upgrade step from version 672 to version 673.
Database 'masttest' running the upgrade step from version 673 to version 674.
Database 'masttest' running the upgrade step from version 674 to version 675.
Database 'masttest' running the upgrade step from version 675 to version 676.
Database 'masttest' running the upgrade step from version 676 to version 677.
Database 'masttest' running the upgrade step from version 677 to version 679.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
Msg 5570, Level 23, State 3, Line 1
FILESTREAM Failed to find the garbage collection table.

Filestream is not enabled on the source server or the server I am restoring to. Is there anything I can do to restore this successfully or does this look like a bug?

A: You should never restore a system database from from one version of SQL Server to another.  The master database contains tables and other objects that support the inner workings of the server itself.  I wouldn't even restore system databases to another server of the same version.  I would instead determine what the information was I was trying to capture (user accounts, scheduled jobs, SSIS packages etc.) and have those extracted and imported to the new server.


text:
Q: Writing tests for controllers with forms Ever since I started using Zend Framework 3, I had problems with testing my controllers. I'm trying to test my controllers with PhpUnit 5.7 and my controllers depend on Zend Form, which is hydrated with Doctrine's DoctrineObject.
I'm trying to put this as simple as possible, so here's a minimal example of a setup that's giving me headaches:
Controller:
class IndexController extends AbstractActionController {
    private $form;
    public function __construct(AlbumForm $form) {
        $this->form = $form;
    }
    public function indexAction() {
        return ['form' => $this-form];
    }
}

ControllerFactory:
class IndexControllerFactory implements FactoryInterface {
    public function __invoke(ContainerInterface $container, ...) {
        $formManager = $container->get('FormElementManager');
        return new IndexController($formManager->get(AlbumForm::class));
    }
}

The corresponding view template in albums/index/index.phtml:
<?php
$this->form->prepare();
$this->form->setAttribute('action', $this->url(null, [], true));

$albumFieldset = $this->form->get('album');
?>
<?= $this->form()->openTag($this-form) ?>
    <div class="form-group">
        <?= $this->formRow($albumFieldset->get('name')) ?>
    </div>
<?= $this->form()->closeTag() ?>

The form:
class AlbumForm extends Form {
    public function init() {
        $this->add([
            'name' => 'albumFieldset',
            'type' => AlbumFieldset::class,
            'options' => [
                'use_as_base_fieldset' => true,
            ],
        ]);
    }
}

The fieldset:
class AlbumFieldset extends Fieldset {
    public function init() {
        $this->add([
            'name' => 'name',
            'type' => Text::class,
            'options' => [
                'label' => 'Name of album',
            ],
        ]);
    }
}

The FieldsetFactory:
class AlbumFieldsetFactory implements FactoryInterface {
    public function __invoke(ContainerInterface $container, ...) {
        $objectManager = $container->get(ObjectManager::class);
        $fieldset = new AlbumFieldset();
        $fieldset->setHydrator(new DoctrineObject($objectManager));
        $fieldset->setObject(new Album());
        return $fieldset;
    }
}

Now, so far everything is working great.
However, when writing tests for this I run into troubles. Let me first show you what I have so far:
class IndexControllerTest extends AbstractHttpControllerTestCase {
    protected function setUp() {
        parent::setUp();
        $this->configureServiceManager($this->getApplicationServiceLocator());
    }
    private function configureServiceManager(ServiceManager $services) {
        $services->setAllowOverride(true);

        $services->setService(ObjectManager::class, $this->mockObjectManager()->reveal());
        $services->setService('FormElementManager', $this->mockFormManager()->reveal());

        $services->setAllowOverride(false);
    }
    private $objectManager;
    private function mockObjectManager() {
        $this->objectManager = $this->prophesize(ObjectManager::class);
        return $this->objectManager;
    }
    private $formManager;
    private function mockFormManager() {
        $this->formManager = $this->prophesize(FormElementManager::class);
        $this->formManager->get(AlbumForm::class)->willReturn($this->mockForm()->reveal());
        return $this->formManager;
    }
    private $form;
    private function mockForm() {
        $this->form = $this->prophesize(AlbumForm::class);
        $this->form->prepare()->willReturn(null);
        $this->form->setAttribute('action', Argument::type('string'))->willReturn(null);
        $this->form->getAttributes()->willReturn([]);
        $this->form->get('album')->willReturn($this->mockAlbumFieldset()->reveal());
        return $this->form;
    }
    private $albumFieldset;
    private function mockAlbumFieldset() {
        $this->albumFieldset = $this->prophesize(AlbumFieldset::class);
        $this->albumFieldset->get('name')->willReturn($this->mockName()->reveal());
        return $this->albumFieldset;
    }
    private $name;
    private function mockName() {
        $this->name = $this->prophesize(Text::class);
        $this->name->getLabel()->willReturn('label');
        $this->name->getLabelAttributes()->willReturn(['for' => 'name']);
        $this->name->getLabelOption('disable_html_escape')->willReturn(false);
        $this->name->getLabelOption('always_wrap')->willReturn(false);
        $this->name->getLabelOption('label_position')->willReturn('prepend');
        $this->name->getName('album[name]');
        $this->name->getAttribute('type')->willReturn('text');
        $this->name->hasAttribute('id')->willReturn(true);
        $this->name->getAttribute('id')->willReturn('name');
        $this->name->getAttributes([])->willReturn([]);
        $this->name->getValue()->willReturn(null);
        $this->name->getMessages()->willReturn([]);
        return $this->name;
    }
}

This will eventually run without errors. However, I would like to draw your attention to the last few methods, especially mockName(). Most of those definitions are totally default and almost none of them are specified in AlbumFieldset in the beginning (only name is). It is very annoying to write them down for every form input I may have and writing this down actually introduces more errors than it solves. For example, I'm still not sure what the correct label option for always_wrap would be. I actually don't even care about that option, but I have to write something about it in my test, because otherwise the test fails with 'Prophecy\Exception\Call\UnexpectedCallException' with message 'Method call: - getLabelOption("always_wrap") on Double\Zend\Form\Element\Text\P245 was not expected, expected calls were: ....
Therefore, I'm asking you: is there any better way to go about this? A way that does not involve writing 20+ rows for every field I have in my fieldset. If it involves rewriting my controllers/fieldsets/view templates (etc.), that would totally be fine!
Any help is greatly appreciated! Also, this is my very first time asking something in a forum in over eight years of programming, so please bear with me if anything is unclear.
Yours
Steffen
PS: What I have already tried is to give the IndexController null instead of an actual form and simply abort the view template when it detects that the form is null. However, while that worked without that much setup, I was basically just avoiding the view template's logic. Because of that, I was not able to detect errors in the view template. That's not what I want.

A: edit IndexControllerTest: Change private as protected elsewhere and extends it for your new fields. Each new controller must overwrite methods calling parent::methodname($args) and add the needed code...


text:
Q: How can i Share HLS Streaming on Facebook with Open Graph Tags? Here is the scenario..
I want to share HLS Live Streaming(.m3u8) on Facebook and it should play the live video in user's profile..
How can i achieve this..?
Here is my Sample Code..
<meta property='og:site_name' content='Content Title'>
 <meta property='og:url' content='https://fb.example.me/ravi'>
 <meta property='og:title' content='Content Title'>
 <meta property='og:image' content='IMAGE LINK'>
 <meta property='og:type' content='video.other'>
 <link rel='canonical' href='https://fb.example.me/ravi'>
 <meta property='og:video' content='M3U8 Link'>
 <meta property='og:video:secure_url' content='HTTPS M3U8 Link'>
 <meta property='og:video:type' content='application/x-shockwave-flash'>
 <meta property='og:video:width' content='472'>
 <meta property='og:video:height' content='296'>
 <meta property='fb:app_id' content='MY FB APP ID'>

Please assist me if i am missing anything..?


text:
Q: Visual studio 2022 for mac unable to find reference assemblies .netframework Whenever I try to build the project I receive the following error.

I checked .net sdk installation location, and it also looks fine.
The build setting is set to .net 7.
Here is the file .csproj
 <Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <LangVersion>preview</LangVersion>
  </PropertyGroup>

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <None Remove="docfx.console" />
    <None Remove="Microsoft.NETCore.Platforms" />
    <None Remove="NETStandard.Library" />
    <None Remove="Microsoft.AspNetCore.Http.Features" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="docfx.console" Version="2.59.4">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>
</Project>

I have uninstalled and installed the visual studio and the sdks. Also, removed the sdks and tried with brew donet sdk installation but it has not given any result because the visual failed to detect the brew installed dotnet sdk. Tried with other older versions of SDKs but the error remains same as Visual studio fails to detect the framework.
I have tried several solutions offered on StackOverflow and other platforms but none seem to be working. I am not sure if it is a bug in visual studio for macOS.


text: Q: abnormal behavior of the kernel jbd2 process I want to understand the mechanism of the journal of the ext4 file system on partitions with no free space. When a process (apache-tomcat, in my case) keeps making small additions to debug log files, after some time disk partitions run out of space. By itself this situation is not bad. But at this point, the abnormal behavior of the kernel's jbd2 process begins. The tool iotop shows that the process consumes 100% of IO. Looking at the storage system, I see increased write activity to a disk that does not have space for these writes.


text:
Q: Error with report class I am using the following packages for writing a document
\documentclass[12pt,a4paper,twoside]{report}
\usepackage[subpreambles=true]{standalone}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{import}
%\usepackage[a4paper, inner=2.5cm, outer=2.5cm, top=2.5cm,bottom=2.5cm, bindingoffset=1.25cm, twoside]{geometry}
\usepackage[a4paper, inner=2.5cm, outer=2.5cm, top=3.5cm,bottom=3.5cm, bindingoffset=1.25cm, twoside]{geometry}
\usepackage{array,longtable}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{color,soul}
\usepackage{graphicx}
\usepackage{setspace}
\usepackage{ragged2e}
\usepackage{enumitem}
\usepackage{lscape}
\usepackage{booktabs}
\usepackage[round]{natbib}
\usepackage{array,multirow,multicol}
\usepackage{setspace}
\usepackage{hyperref}
\usepackage{ltablex}
\usepackage{rotating}
\usepackage{amsmath}
\usepackage[titletoc]{appendix}
\usepackage{cite}
\usepackage{lmodern}
\usepackage{kpfonts}
\usepackage{mathptmx}
\usepackage[T1]{fontenc}
\usepackage{titlesec}
\usepackage{microtype}
\usepackage{tikz}
\usepackage{textcase}
% Load the package with the acronym option
%\usepackage[acronym]{glossaries}
%\usepackage{glossaries}
\usepackage{glossariX}
\usepackage{breakcites}
\usepackage{tabularx}
\usepackage{multirow}
\usepackage{csquotes}
\usepackage{float}
\usepackage{quotchap}
\usepackage{makecell}
\usepackage[edges]{forest}
\usepackage{caption}
\usepackage{longtable}
\usetikzlibrary{fit}
\setcellgapes{5pt}
\makegapedcells
\usepackage{fancyhdr}
%\usepackage[Glenn]{fncychap}
\usepackage{hyperref}
\usepackage{array}
%\usepackage{tabto}
%\newcolumntype{L}{>{\centering\arraybackslash}m{3cm}}

\pagestyle{fancy}           % Sets fancy header and footer

This is the error I am getting:

standalone.sty line 555 Extra }, or forgotten \endgroup. }


text:
Q: Is there any dependency of capitalize attribute of TextView and its ListView ListView having TextView as its ListItem
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent">

    <com.dexterous.genero15.font.Audiowide_Regular
        android:id="@+id/club_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:capitalize="characters"
        android:gravity="center"
        android:minHeight="70dp"
        android:padding="8dp" />

</LinearLayout>

Audiowide_Regular is child of AutofitTextView which is child of TextView
and listview having setOnItemClickListener on it.
If i removed attribute         android:capitalize="characters" from listItem then onItemClick works fine else onItemClick not executed.
Is there an dependency of setOnItemClickListener and         android:capitalize="characters" ?

A: From the docs:

If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types.

Since setting this attribute defines an input method for the TextView, it is most likely intercepting the OnItemClickListener and instead using some KeyListener event.
If what you were trying to do is force the TextView to display information in all uppercase characters, you can set the textAllCaps attribute to true.


text:
Q: How to find (or numerically find) a solution to a system of 10 equations with 14 variables? I am trying to construct a counterexample in $\mathbb{R}^4$. There are 10 relations, each of which is given as the vanishing set of a determinant. There are 14 variables in total. Is there a way to find a solution easily, possibly with the help of some computer program?

A: If the system is too complicated for symbolic solution, you might try some numerical experimentation.
Since there are more variables than equations, the system is likely to be
underdetermined as Moritz Firsching commented.  In this case, if you choose
 values for $4$ of the variables (hopefully the nature of the problem gives you some idea of likely orders of magnitude for them), you may be able to numerically solve the $10$ equations for the remaining $10$ variables, using
something like Maple's fsolve, and have a good chance of success.  It may even be possible to prove that a true solution exists near that numerical solution.

A: Mathematica has FindInstance for this.


text:
Q: Creating struct variable using the tag name I have read a article in the following link
http://www.embedded.com/electronics-blogs/programming-pointers/4024450/Tag-vs-Type-Names
Here author says that, use of follwing is wrong.
struct s
{
--
};

s var;

But in my sample code its works perfectly.
  1 #include<iostream>
  2 using namespace std;
  3
  4 struct s
  5 {
  6    int sd;
  7 };
  8 s v;
  9
 10
 11
 12 int main()
 13 {
 14
 15    v.sd=10;
 16    cout<<v.sd;
 17    return 0;
 18 }

EDIT:
What the actual difference?
why it works in c++ and not works in c;

A: It is the difference between C++ and C. The author you are citing speaks about C while you use C++ code instead of C code. In C you have to specify keyword struct, union or enum before declaring variables of correspondings types.

A: The article says that a user-defined type using
struct s {
   ...
};

defines a tag name s. To name the actual type, you can write struct s (C or C++) or class s (C++ only), but C++ makes both keywords optional (and almost never actually used). So whenever you write s in C++ it's actually interpreted as the correct type, while in C the keyword is obligatory to name the type.
So long story short: in C++ there is no difference in writing struct s, class s or s, they all mean the same.
In order to define the type name s in a C/C++ shared header, one typically writes
typedef struct {
   ...
} s;

Then the type s can be used in both C and C++ without the need to write struct.


text:
Q: Can't travel from Siwa to Alexandria So I'm on a PS4, Bayek level 7, with all of Siwa's missions completed. It says that I have to talk to Bayek's friend to go to Alexandria but when I talk to him he says that he is not ready yet packing my stuff for my trip and then on the screen a message in red and white pops up saying: "This feature hasn't been installed yet, let AC origins install...". I don't understand what is hapenning cause I installed everything and when I checked the updates, it says the game version is up to date. So I've tried restarting the PS4, reinstalling the AC Origins app, yet nothing changes. So I am stuck here and can't advance in story by traveling to Alexandria. Does anyone know what I need to do?

A: According to a Known Issues thread from Ubisoft:

Unable to leave Siwa
Description: We are aware of an issue where players are not able to leave Siwa and receive a "The game has not fully installed yet. Please wait for Assassin's Creed Origins to finish installing and try again." pop up.
  Status: Under Investigation - Please get in touch with the Customer Support if you experience this issue and provide them with as much information as you can.

Looks like the only thing you can do is wait for a patch to be released.
Update: Ubisoft has put in a request for users with the issue in hopes of narrowing down the issue further.


text:
Q: Store data Array from code behind into javascript in ASP.Net I have code like this :
 Dim ListMyDate = New List(Of MyDate)()

        Dim cek As Date = "2017/10/15","2017/10/16"
        ListMyDate.Add(New MyDate() With {.ShowDate = cek})

    allRecords = ListMyDate.ToArray()

    For Each obj As MyDate In ListMyDate
        Response.Write(obj.ShowDate.ToString() + ",")
    Next

This code work for me, but I want store data result from my array to javascript.


text:
Q: Show that if $|f(z)| \leq M$ for $z \in \partial D$ for $z \in \mathbb{C}$ and M being a constant, then $|f(z)| \leq M$ for all $z \in D$ We are given that $f$ is analytic in a bounded domain $D$ and continuous on the boundary $\partial D$. Also we can assume that $|f(z)| \leq M$ for $z \in \partial D$ for $z \in \mathbb{C}$.
I'm unsure what it means to be continuous on the boundary $\partial D$, but here is what I have thought up so far:
Since $f$ is analytic in the bounded domain $D$ we have that $f$ is continuously differentiable at some point $z \in D$. Since $f$ is continuously differentiable at $z$ we have that $f'$ is also continuous at $z$. As $f$ is continuous on the boundary $\partial D$ we have by the definition of $\epsilon - \delta$ continuity that for every $\epsilon >0$ there exists a $\delta >0$ such that $|z-z_0|<\delta \implies |f(z)-f(z_0)|<\epsilon$. We are also allowed to assume that $|f(z)| \leq M$ for $z \in \partial D$ for $z \in \mathbb{C}$. I'm not sure where to head with this problem, or if I have set up what was given correctly.
I think since $|f(z)-f(z_0)|<\epsilon$ we can rewrite this as $||f(z)|-|f(z_0)|| \leq \epsilon$ and so $|f(z)| \geq -\epsilon + |f(z_0)|$ where we then have that $M \geq -\epsilon +|f(z_0)|$. But, I don't think this leads in any particular direction.

A: This turned out a little more longwinded than I had hoped.
Suppose $f$ is analytic at $z^* \in D$. Since $D$ is open there is some $r>0$ such that $A=B(z^*,r) \subset \overline{B(z^*,r)} \subset D$. (This nitpick is just so that $f$ is defined on a set containing the closure of $A$.)
Let $R= \{ |f(z)| \}_{z \in A} $ and $\mu = \sup R$. ($|f|$ is bounded on the compact set $\overline{A}$ so $\mu$ is finite.)
If $\mu \in R$, then $|f|$ has a local $\max$ and hence $f$ is constant. Otherwise $|f(z)| < \mu$ for all $z \in A$.
If $f$ is constant then it is clear that $|f(z)| \le M$ for $z \in D$.
Hence we can assume that $f$ is non constant.
Let $\lambda = \sup_{z \in D} |f(z)|$. Then the above shows that $|f(z)| < \lambda$ for all $z \in D$ (show by contradiction).
Now note that $\lambda = \max_{z \in \overline{D}} |f(z)|$ and that the $\max$ is attained for some $z^* \in \overline{D}$ (using compactness).
From the second last sentence we see that $z^* \notin D$ and so $z^* \in \partial D$ and hence $\lambda \le M$.

A: "$f$ is analytic in a bounded domain $D$ and continuous on the boundary $\partial D$" is a somewhat imprecise formulation of the following:

*

*$D \subset \Bbb C$ is a bounded domain (i.e. a bounded, open, and connected set),

*$f: \overline D \to \Bbb C$ is a continuous function,

*the restriction of $f$ to $D$ is an analytic function.

In other words: $f$ is analytic in a bounded domain $D$ and has a continuous extension to $\overline D = D \cup \partial D$.
Then you can argue as follows: $|f|$ is continuous on the compact set $\overline D$, therefore it attains its maximum at some point $z_0 \in \overline D$. Now consider two cases:

*

*$z_0 \in \partial D$: Then $|f(z_0)| \le M$ according to the hypothesis, and we are done.

*$z_0 \in D$: Then $|f|$ has a local maximum at $z_0$. It follows from the maximum modulus principle that $f$ is constant, and we are done as well.

Remark: The condition "$f$ is analytic in a bounded domain $D$ and continuous on the boundary $\partial D$" is imprecise because it could be interpreted as

*

*The restriction of $f$ to $D$ is analytic, and

*the restriction of $f$ to $\partial D$ is continuous.

But then the statement is obviously wrong (take for example $D$ as the unit disk, $f(z) = z$ in $D$, and $f(z) = 0$ on $\partial D$).


text:
Q: How to pull docker images hosted on Google Container Registry via Kubernetes (kubernetes included on docker for desktop) I am having trouble pulling images from GCR ( pulled by my deployments )
I got ImagePullBackOff error.
I have followed this tutorial already, step by step.
https://container-solutions.com/using-google-container-registry-with-kubernetes/
However it doesn't seem to work for me. I have even tried using the Storage Admin role when creating the service account key but its still no use.
When describing the pod, I got this error:
  Warning  Failed                 14s (x2 over 30s)  kubelet, docker-for-desktop  Failed to pull image "gcr.io/<project-name>/<image-name>": rpc error: code = Unknown desc = Error response from daemon: Get https://gcr.io/v2/<project-name>/<image-name>/manifests/latest: unknown: Unable to parse json key.
  Warning  Failed                 14s (x2 over 30s)  kubelet, docker-for-desktop  Error: ErrImagePull
  Normal   BackOff                2s (x3 over 29s)   kubelet, docker-for-desktop  Back-off pulling image "gcr.io/<project-name>/<image-name>"
  Warning  Failed                 2s (x3 over 29s)   kubelet, docker-for-desktop  Error: ImagePullBackOff

When visiting the https://gcr.io/v2/project-name/image-name/manifests/latest url, I got this:
// 20181124152036
// https://gcr.io/v2/project-name/image-name/manifests/latest

{
  "errors": Array[1][
    {
      "code": "UNAUTHORIZED",
      "message": "You don't have the needed permissions to perform this operation, and you may have invalid credentials. To authenticate your request, follow the steps in: https://cloud.google.com/container-registry/docs/advanced-authentication"
    }
  ]
}

Pod Definition:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: microservice-1-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: microservice-1
  template:
    metadata:
      labels:
        app: microservice-1
    spec:
      containers:
        - name: microservice-1
          image: gcr.io/project-name/image-name
          ports:
            - containerPort: 80

Notes:
My deployments are able to pull images when they where hosted on docker hub, issue only occurs on pulling images in GCR.
Env

*

*Windows 10

*Docker Version 2.0.0.0-win78 (28905)

*Kubernetes 1.10.3 (Included on docker for desktop)

I hope you can help me on this,
Thanks in advance

A: OK found the culprit, it has something to do with Powershell and Command Prompt.
I switched to using Git Bash and followed the same instructions in this tutorial
https://container-solutions.com/using-google-container-registry-with-kubernetes/
and it worked!
Probably the culprit occurred when creating imagePullSecrets on Powershell and/or Command Prompt. Something probably went wrong when reading the json file, related to encoding or something.
Hope this helps anyone.

A: Looking at the error message it looks like that the json file you have provided has some issue unable to parse json file
The reason behind that is the json file you have has break (newline) in it and hence unable to recognise in secret.
Please have a look here and try one of the solution. You can always choose other authentication methods listed here
Docker Login to gcr.io in Powershell
Hope this helps.


text:
Q: api security implementation php I have a site that allow users to check their statistics (number of file uploaded, how many files they have, quotas, type of access etc...)
I create a section on my site: api.domain.com
This can be access via curl or a web browser since I am returning a json object or xml (depending on the user prefs)
My question is this: should I restrict the access using a user/pass or should I create a hash of the user file?
for example:
scenario 1:
The user create a php curl that sends user and pass via post or the curl auth and get back the results, parse it etc...
For me this is secure but the user has to maintain his script if they change their pass
scenario 2
The user access a file like: api.domain.com/j355HGssgf3HESAjh45jusf4325GSj5hbsHhdh5HGHFS3732he4548475wbe3447nSNe5XfgjhGJ and then access the data
This one, nothing to maintain

A: Here's my thoughts on this.
If you return a page not found or an error message (with a good 200 OK status) when a request is made to your page, it might send to bots or UN-trustable people a clue on what can they get and try again and again and again ...
On the other hand, if you send a access denied, like a 401, or better a 500 error code to simulate a server error, these bots or UN-trustable people might go away for good.
I will say the user/password method is a little more secure in this case.
Now, would you trust simply entering a big string (like scenario 2) when you check your mail? or your bank account information?

A: If it was me I would give each account the ability to create a unique api key,
api.domain.com/?key=<API.KEY>

for more security measure you could make it only accept connection via the post method with the api key. If contacted via get then show an error etc.
Then if they change their pass/username it won't affect their api key


text:
Q: How do I implement output variables in powershell? I realize "output variables" is probably the wrong terminology here which is why my google searching has failed me. I'm guessing it revolves around explicitly setting variable scope, but I've tried reading the about_Scopes doc and it's just not clicking for me.
Essentially what I'm trying to do is implement the equivalent of the -SessionVariable argument from Invoke-RestMethod in my own module's function. In other words, I need a string parameter that turns into a variable in the caller's scope.
function MyTest
{
    param([string]$outvar)

    # caller scoped variable magic goes here
    set-variable -Name $outvar -value "hello world"

    # normal function output to pipeline here
    Write-Output "my return value"
}

# calling the function initially outputs "my return value"
MyTest -outvar myvar

# referencing the variable outputs "hello world"
$myvar

For bonus points, how do things change (if at all) if I'm wrapping an existing function that has its own output variable and I want to effectively pass through the output variable name?
function MyWrapper
{
    param([string]$SessionVariable)

    Invoke-RestMethod -Uri "http://myhost" -SessionVariable $SessionVariable

    # caller scoped variable magic goes here
    set-variable -Name $SessionVariable -value $SessionVariable
}

# calling the wrapper outputs the normal results from Invoke-RestMethod
MyWrapper -SessionVariable myvar

# calling the variable outputs the WebRequestSession object from the inner Invoke-RestMethod call
$myvar

P.S. If it matters, I'm trying to keep the module compatible with Powershell v3+.

A: There's no need to attempt to implement this yourself, -OutVariable is a Common Parameter.
Add a CmdletBinding attribute to your param block to get these for free:
function MyTest {
    [CmdletBinding()]
    param()

    return "hello world"
}

MyTest -OutVariable testvar

$testvar now holds the string value "hello world"
For your second example, where you need to set a value in the caller scope in addition to pipeline output, use the -Scope option with Set-Variable:
function MyTest {
    [CmdletBinding()]
    param([string]$AnotherVariable)

    if([string]::IsNullOrWhiteSpace($AnotherVariable)){
        Set-Variable -Name $AnotherVariable -Value 'more data' -Scope 1
    }

    return "hello world"
}

MyTest -AnotherVariable myvar

$myvar in the caller scope now contains the string value "more data". The 1 value passed to the Scope parameter means "1 level up"

A: @Mathias R. Jessen propose solution, which work well, when not defined in module. But not, if you put it in module. So, I provide another solution, which works, when put in module.
In advanced function (one which use [CmdletBinding()] attribute) you can use $PSCmdlet.SessionState to refer to SessionState of a caller. Thus, you can use $PSCmdlet.SessionState.PSVariable.Set('Name' ,'Value') to set variables in caller's SessionState.
Note: this solution will not work if not defined in module or if called from the same module, where it defined.
New-Module {
    function MyTest1 {
        [CmdletBinding()]
        param([string]$outvar)
        $PSCmdlet.SessionState.PSVariable.Set($outvar, 'Some value')
    }
    function MyTest2 {
        [CmdletBinding()]
        param([string]$outvar)
        # -Scope 1 not work, because it executed from module SessionState,
        # and thus have separate hierarchy of scopes
        Set-Variable -Name $outvar -Value 'Some other value' -Scope 1
    }
    function MyTest3 {
        [CmdletBinding()]
        param([string]$outvar)
        # -Scope 2 will refer to global scope, not the caller scope,
        # so variable with same name in caller scope will hide global variable
        Set-Variable -Name $outvar -Value 'Some other value' -Scope 2
    }
} | Out-Null

& {
    $global:a = 'Global value'
    MyTest1 a
    $a
    $global:a
    ''
    MyTest2 a
    $a
    $global:a
    ''
    MyTest3 a
    $a
    $global:a
}


text:
Q: Draw a simple graph in VB.NET / C# I am going insane with this, i've spent weeks trying to get it right and I think I am just burned out. Every time I get a working model and I change the HighestNumber / LowestNumber, it breaks and things are off screen.
I deleted all my actual running code a million times, so this is psuedo code, but roughly what i'm doing and I know the answer is so absolutely obvious.
I need the numbers to scale inside the client area and stay within bounds whether they're max (max 9,999,000 and min 0.01) or (max 1.00 and min 0.98)
The highest number should be on top, and the lowest number on bottom.
I will always know the Highest and Lowest numbers before iteration, those are basically to be used to scale the the graph as the high/low/cur can be ANY value.

DIM HighestNumber as double = 1.33
DIM LowestNumber as double = 0.99
DIM GraphClientArea as single = 400
DIM HalfClientArea as single = GraphClientArea / 2

FOR x = 1 to 50 ' roll X for 500px total
    DIM r as new Random
    DIM CurX as single = X * 10 ' 10px blocks horiz
    DIM CurrentNumber as double = 1.02 + r.Next(-0.10,0.10) ' make up a random number in range

    DIM Spread as double = HighestNumber - LowestNumber
    DIM SpreadPercentage as Double = (LowestNumber / HighestNumber)

    DIM Y as double = (HalfClientArea * SpreadPercentage) - (SpreadPercentage * CurrentNumber)

    g.FillEllipse(Brushes.White, New Rectangle(x, y, 2, 2))

NEXT

I know the above isn't right, I just can't figure out what the right algorithm is to accomplish what I need.

A: Solved it.
Output:

The algebra to solve for Y is

(clientArea - (clientArea * (Cur / Max)))

While arguing with a non-contributor, I likened the values I have to a progress bar, when the math finally hit me. All you're doing is making a progress bar and instead of drawing X,Y; you're drawing Y,X to make it vertical.
Test code for anyone who needs it
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

        Dim clientArea As Single = PictureBox1.Height

        Dim Max As Single = 1207.43

        Dim g As Graphics = e.Graphics

        Dim LastPoint As New Point(0, 0)

        Dim prices As New List(Of Double)
        prices.Add(1207.43)
        prices.Add(1107.2)
        prices.Add(1203.33)
        prices.Add(807.12)
        prices.Add(607.21)
        prices.Add(907.53)
        prices.Add(607.61)
        prices.Add(1000.43)

        For i = 0 To prices.Count - 1
            Cur = prices(i)

            Dim col = i * 100
            Dim y As Single = (clientArea - (clientArea * (Cur / Max)))

            g.FillRectangle(Brushes.Black, New Rectangle(col, y, 10, 10))
            g.DrawString(Cur.ToString, Me.Font, Brushes.Black, New Point(col + 12, y))

            g.DrawLine(Pens.Blue, LastPoint, New Point(col, y))

            LastPoint = New Point(col, y) ' cur vector becomes prev vector for next iteration

        Next

    End Sub

A: This is my best guess as to what you are asking for. It is an update display routine, which has a new current value created based upon a timer and random values.
private void updateDisplay(bool clipToMaxMin)
{
    // get the graphics context for the panel
    var g = pnlCanvas.CreateGraphics();
    g.Clear(BackColor);

    // get the min and max width
    var minWidth = g.VisibleClipBounds.Left;
    var maxWidth = g.VisibleClipBounds.Right;
    // get the current width to use
    var curWidth = minWidth + ((maxWidth - minWidth) / 2.0f);

    // get the min and max height
    var minHeight = g.VisibleClipBounds.Bottom;
    var maxHeight = g.VisibleClipBounds.Top;

    // Have to decide if we are going to update max and min or
    // clip the values to max and min
    if(clipToMaxMin)
    {
        current = (current < min) ? min : (current > max) ? max : current;
    }
    else
    {
        if (current > max) max = current;
        else if(current < min) min = current;
   }

   var curScaled = (current - min) / (max - min);
   var curHeight = minHeight + ((maxHeight - minHeight) * (curScaled));

   g.FillEllipse(Brushes.Blue, new RectangleF(curWidth, curHeight, 20, 20));
}


text:
Q: Generate non-fixed length large random number (bigint) How can I generate a non-fixed length large random number? (e.g. within the range of MySQL's bigint). The mt_rand() function does not support such large numbers.

A: Use multiple random functions:
const max_limit=10000;
a=mt_rand()*max_limit*max_limit + mt_rand()*max_limit + mt_rand();

A: MySQL's BIGINT is 8 bytes large. Let's asume an unsigned BIGINT.
echo unpack('H*', mcrypt_create_iv(8))[1];

or for php versions < 5.4 that do not support function array dereferencing
echo current(unpack('H*', mcrypt_create_iv(8)));

see:
http://docs.php.net/function.mcrypt-create-iv
http://docs.php.net/function.pack


text:
Q: Steady state error due to disturbance I was trying to solve a question from the  2004 GATE IN paper,

I solved it this way,

Now, the book is giving a different solution, I'm pretty sure my way is correct since they pulled the "standard form" out of nowhere. I don't think that formula is applicable here. But please tell me if I am wrong.

Also while I understand that I performed those algebraic manipulations to find how the disturbance and error is related in the frequency domain, I am not comfortable with the fact that I had to assume input R(s) was 0. I mean practically we would care about how the disturbance D affects the output C or error E in the presence of some non zero input R right? If I don't take input to be zero I can't seperate terms and find the transfer function. So I was wondering if the superposition principle is strong enough such that this result is useful even in the case of both D and R bring present?


text:
Q: Remove comments when running rspec When I test my rails app using rspec, a bunch of long comments appear.
How can I remove them ?
 ActionController::RoutingError:
   No route matches [GET] "/events"
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:36:in `call_app'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `block in call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:22:in `call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/runtime.rb:22:in `call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/sendfile.rb:111:in `call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:522:in `call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:68:in `block in call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:53:in `each'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:53:in `call'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/mock_session.rb:30:in `request'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/test.rb:244:in `process_request'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/test.rb:58:in `get'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:61:in `process'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:36:in `process_and_follow_redirects'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:22:in `visit'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/driver.rb:43:in `visit'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/session.rb:233:in `visit'
 # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/dsl.rb:52:in `block (2 levels) in <module:DSL>'
 # ./spec/features/list_movies_spec.rb:5:in `block (2 levels) in <top (required)>'

A: That's not comments that's a stack trace, to help you resolve the problem that rspec encountered.
A stack trace shows you each nested call that was made up to the point that the error was encountered, so that you can trace back to which line in your code a command was run that led to the error.
your spec/features/list_movies_spec.rb on line 5 it's performed a method that at some point is tryng to do `GET /events' but you don't have such a route in your route.rb
Fix the problem, and the "comments" will disappear.


text:
Q: QJSEngine cause a crash at exit when having accessed to pointer to C++ object I am trying to make part of my application scriptable.
I have an object "GraphLogic" which contains a table of pointer on "Block" objects. I want to have access to this object in my script.
#include <QObject>
#include <QString>

class Block;

class GraphLogic: public QObject
{
    Q_OBJECT
public:
    explicit GraphLogic( int Heads, int Rows)
    virtual ~GraphLogic();
…
Q_INVOKABLE int getLines() const;
Q_INVOKABLE int getColumns() const;

Q_INVOKABLE Block* getBlock(int Col, int Row);
QString exportSeq(const QString& rScript);
…

QList< QList< Block*> > m_BlockTable;
};

implementation (graphlogic.cpp):
#include "graphlogic.h"
#include "block.h"

#include <QJSEngine>
#include <QQmlEngine>

GraphLogic::GraphLogic(int Col, int Rows){
for(int ColIndex = 0; ColIndex < Col; ++ ColIndex)
{
   m_BlockTable.append(QList<Block*>());
   for(int Index = 0; Index < Rows; ++Index)
   {
       m_BlockTable[ColIndex].append(nullptr);
   }
}
}

GraphLogic::~GraphLogic()
{
for(int ColIndex = 0; ColIndex < m_BlockTable.size(); ++ ColIndex)
{
   for(int Index = 0; Index < m_BlockTable[0].size(); ++Index)
   {
       if(m_BlockTable[ColIndex][Index])
       {
           delete m_BlockTable[ColIndex][Index];
           m_BlockTable[ColIndex][Index] = nullptr;
       }
   }
}
}

int GraphLogic::getLines() const
{
return m_BlockTable[0].size();
}

int GraphLogic::getColumns() const
{
return m_BlockTable.size();
}

Block* GraphLogic::getBlock(int Col, int Row)
{
if(Col < 0 || Col >= m_BlockTable.size() || Row < 0 || Row >=       m_BlockTable[0].size())
{
    return nullptr;
}

 return m_BlockTable[Col][Row];
}

bool GraphLogic::addBlock(Block* pBlock, int Row, int Col)
{
if(Col < 0 || Col >= m_BlockTable.size() || Row < 0 || Row >=    m_BlockTable[0].size())
{
    return false;
}

 m_BlockTable[Col][Row] = pBlock;
}

QString GraphLogic::exportSeq(const QString& rScript)
{
QJSEngine engine;
qmlRegisterType<Block>();

//this ->Logic object
QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);

QJSValue LogicValue = engine.newQObject(this);
engine.globalObject().setProperty("Logic", LogicValue);

QJSValue SeqStr = engine.evaluate(rScript);
QJSValue Res = SeqStr.call();
return Res.toString();
}

I have made Block::GetLabel() method scriptable as well.
Here is Block class
block.h:
#include <QObject>

class Block: public QObject
{
Q_OBJECT
public:

Block(const QString &rLabel);
virtual ~Block();

Q_INVOKABLE QString getLabel() const;
private:

QString m_Label;
};

and block.cpp:
#include "block.h"

Block::Block(const QString &rLabel)
    : m_Label(rLabel)
{

}

Block::~Block()
{

}

QString Block::getLabel() const
{
    return m_Label;
}

I can make my "GraphLogic" object available to script, it works fine.
When I try to access block object, I can get block labels, script goes to the end and exits fine.
Macro.qs (passed as parameter to GraphLogic::export):
(function logicToString()
{
    var Out;
    var i, j;
    for(i = 0; i < Logic.getColumns(); ++i)
    {
        for(j = 0; j < Logic.getLines(); ++j)
        {
            if(Logic.getBlock(i,j) != null)
            {
               // b is Block* !
               var b = Logic.getBlock(i,j);
               Out += b.getLabel();
            }
            Out += ";";
        }
        Out += "\n";
    }
return Out;
})

But when I try to access Block objects again, it crashes. Here is the example, main.cpp:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include "graphlogic.h"
#include "block.h"

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

GraphLogic Logic(3,3);
Block* pNewBlock = new Block("first");
Logic.addBlock(pNewBlock, 0,0);
pNewBlock = new Block("second");
Logic.addBlock(pNewBlock, 1,1);

QString JSFile("./Macro.qs");
QFile ScriptFile(JSFile);
if(ScriptFile.open(QIODevice::ReadOnly))
{
    QTextStream Stream(&ScriptFile);
    QString ExportScript = Stream.readAll();

    //output:
    //"first;0;0;\n0;second;0;\n0;0;0;\n"
    qDebug() << Logic.exportSeq(ExportScript);

}
ScriptFile.close();

Block* pBlock = Logic.getBlock(0,0);
if(pBlock)
{
    //crash SEG FAULT
    qDebug()<< pBlock->getLabel();
}
return a.exec();

}
Probably because they have been destroyed from QJSEngine?
I said that because same issue happened when I forgot to explicitely declare the ownership of GraphLogic object to be QQmlEngine::CppOwnership.
So, I suppose I have to find a way to prevent QJSEngine to destroy the Block object. Same as QQmlEngine::setObjectOwnership but in javascript, because I have no acess to current block outside of script.
Any idea on how can I achieve that?
Thanks,


text:
Q: How to make the note of ComBoBox in Delphi in my project I want to make some note when user move mouse over the ComboBox Item,
Ex : I have a ComboBox and the Items are : Bob's phone,Robert's phone,...
When user move mouse over Bob's phone then the label will appear at the Position of Mouse in ComboBox and Label's content is : 05498762,.
Please help me and thanks much!!!

A: If you want to display a hint while the user is actively moving the mouse over the TComboBox items, you can do the following:

If the TComboBox.Style property is set to csSimple, the ComboBox's ListBox is always visible.  However, the OnMouseMove event is not exposed, and even if you assign it manually, it is not triggered when moving the mouse over the ComboBox's ListBox, only its Edit field.  However, you can use the TApplication.OnShowHint event instead, or subclass the TComboBox itself to intercept the CM_HINTSHOW message directly.  Either way will provide you with a reference/pointer to a THintInfo record.  You can use the THintInfo.CursorPos field to determine the ListBox item that is currently under the mouse:

*

*call GetComboBoxInfo() to get the ComboBox's ListBox HWND.

*then call MapWindowPoints() to translate the CursorPos coordinates from ComboBox client coordinates to ListBox client coordinates.

*then send a LB_ITEMFROMPOINT message to the ListBox with the translated coordinates.
That will give you the index of the item that is closest to the coordinates.  You can then set the THintInfo.HintStr field with the desired text.  You should also set the THintInfo.CursorRect field with the rectangle returned by sending a  LB_GETITEMRECT message to the ListBox (use MapWindowPoints() to convert the rectangle from ListBox client coordinates to ComboBox client coordinates).  When the mouse moves outside of the rectangle, a new OnShowHint/CM_HINTSHOW will be issued, and you can then update the THintInfo with details from the ListBox item that is now under the mouse.

If the TComboBox.Style property is not set to csSimple, the ListBox is only visible when it is dropped down.  The OnShowHint/CM_HINTSHOW trick will not work in this situation.  However, you can use the TComboBox.OnDropDown event to manually subclass the ListBox directly (and the OnCloseUp event to remove the subclass), using SetWindowLongPtr() or SetWindowSubclass().  That will allow you to intercept WM_MOUSEMOVE messages that are sent directly to the ListBox, and then you can send LB_ITEMFROMPOINT to the ListBox with the provided mouse coordinates.
However, to actually display a hint, it is not enough to just set the TComboBox.Hint property in this situation (it won't be displayed, as the dropped-down list is basically acting as a modal window and is blocking the normal hint mechanism). You will have to display your own hint window manually, such as by using the THintWindow class directly.

A: This will work on mouse move after selection after you set ShowHint to true:
procedure TForm1.ComboBox1Select(Sender: TObject);
begin
case ComboBox1.ItemIndex of
  0: ComboBox1.Hint := '05498762';
  1: ComboBox1.Hint := '';
  .
  .
  .
end;
end;


text:
Q: Access denied on aws lambda function when getObject from S3 bucket I'm using the default code for a lambda function:
console.log('Loading function');

var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = function(event, context) {
    //console.log('Received event:', JSON.stringify(event, null, 2));

    // Get the object from the event and show its content type
    var bucket = event.Records[0].s3.bucket.name;
    var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    var params = {
        Bucket: bucket,
        Key: key
    };

    s3.getObject(params, function(err, data) {
        if (err) {
            console.log(err);
            var message = "Error getting object " + key + " from bucket " + bucket +
                ". Make sure they exist and your bucket is in the same region as this function.";
            console.log(message);
            context.fail(message);
        } else {
            console.log('CONTENT TYPE:', data.ContentType);
            context.succeed(data.ContentType);
        }
    });
};

However i get an access denied error:
2016-02-24T14:21:21.503Z    kvyo1midvc2r69gm    Loading function
START RequestId: baf9049b-db01-11e5-bc34-791df91353a9 Version: $LATEST
2016-02-24T14:21:22.500Z    baf9049b-db01-11e5-bc34-791df91353a9    { [AccessDenied: Access Denied] message: 'Access Denied', code: 'AccessDenied', region: null, time: Wed Feb 24 2016 14:21:22 GMT+0000 (UTC), requestId: '215CD9BB4094E209', extendedRequestId: '0kDBEyMiJYbMApEqJuAtKct2SKLI7Z7tCBVyW6QJsYwMHROvtCEDynbGSsBdqbwFcX+YrSlGnsg=', statusCode: 403, retryable: false, retryDelay: 30 }
2016-02-24T14:21:22.539Z    baf9049b-db01-11e5-bc34-791df91353a9    Error getting object {"originalFilename":"c12eaadf3d3b46d9b5ded6c078534c11","versions":[{"Size":1024,"Crop":null,"Max":false,"Rotate":0}]} from bucket xmovo.originalimages.develop. Make sure they exist and your bucket is in the same region as this function.
2016-02-24T14:21:22.539Z    baf9049b-db01-11e5-bc34-791df91353a9
{
    "errorMessage": "Error getting object {\"originalFilename\":\"c12eaadf3d3b46d9b5ded6c078534c11\",\"versions\":[{\"Size\":1024,\"Crop\":null,\"Max\":false,\"Rotate\":0}]} from bucket xmovo.originalimages.develop. Make sure they exist and your bucket is in the same region as this function."
}
END RequestId: baf9049b-db01-11e5-bc34-791df91353a9
REPORT RequestId: baf9049b-db01-11e5-bc34-791df91353a9  Duration: 723.44 ms Billed Duration: 800 ms Memory Size: 128 MB Max Memory Used: 34 MB

My lambda function and my S3 bucket are in the same region 'US Standart' and 'us-east-1' which are the same
IAM permission are ok for lambda function, allowing to GetObject Action,(it is set with the wizard that create the lambda function)
with all that check i have no clue why i still getting the Access Denied Error
Thanks in advance

A: Looking at your log output, I can see that the key variable contains the following string:
{\"originalFilename\":\"c12eaadf3d3b46d9b5ded6c078534c11\",\"versions\":[{\"Size\":1024,\"Crop\":null,\"Max\":false,\"Rotate\":0}]}

I'm guessing you intended that variable to contain the string "c12eaadf3d3b46d9b5ded6c078534c11".
S3 will return a 403 error response if you don't have access, or if the key doesn't exist. Returning "access denied" in both cases is a security feature to prevent attackers from finding out what keys actually exist in your bucket.
I think you need to change this line:
decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));

to something like this:
decodeURIComponent(event.Records[0].s3.object.key.originalFilename.replace(/\+/g, ' '));

A: Check the IAM permissions of the role you want to use, maybe there are deny permissions above allow permissions.


text:
Q: Jetpack Compose Text and Image get overlapped inside Column layout issue I am using Jetpack Compose for designing dynamic Layout inside android app. Column layout is used to place elements like Vertical layout. This kind of behaviour is achieved using LinearLayout orientation Vertical usage without compose. Inside Column I have added one Image on top and one text I want to display below it. But after placing the Text inside the Compose Column layout it is getting overlapped. How to resolve this.
The code for adding Image and Text is as follows
@Composable
fun GreetingSectionExperimental(
    name: String = "Philipp"
) {
    //var text by remember { mutableStateOf(TextFieldValue("")) }
    Column(
        verticalArrangement = Arrangement.Top,
        modifier = Modifier.fillMaxSize()
    ) {
        Image(
            painterResource(id = R.drawable.ic_launcher_background),
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp).offset(0.dp,35.dp),
            alignment = Alignment.Center,
            contentDescription = ""
        )
        Text(
            text = "Login / Sign Up",
            Modifier.padding(10.dp).align(CenterHorizontally),
            color = textColor, fontSize = 18.sp,
            fontWeight = FontWeight.SemiBold
        )
    }
}

I am getting output as

How to resolve this ? Inside the current what is missing or Column does not support different kind of elements.

A: You need to remove the property "Offset" from your image
the code should looks like
@Composable
fun GreetingSectionExperimental(
    name: String = "Philipp"
) {
    //var text by remember { mutableStateOf(TextFieldValue("")) }
    Column(
        verticalArrangement = Arrangement.Top,
        modifier = Modifier.fillMaxSize()
    ) {
        Image(
            painterResource(id = R.drawable.ic_launcher_background),
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp), //Remove the offset here
            alignment = Alignment.Center,
            contentDescription = ""
        )
        Text(
            text = "Login / Sign Up",
            Modifier.padding(10.dp).align(CenterHorizontally),
            color = textColor, fontSize = 18.sp,
            fontWeight = FontWeight.SemiBold
        )
    }
}

A: Best solution is to use Spacer(modifier = Modifier.height(20.dp)). It will create space between the those Elements this in between this is added.


text:
Q: Reflection : How to get the result (and do foreach on it) from method invoked using Reflection? I would like to invoke some methods from different repository and having the same type List<> as result but I don't know how to cast the result without hard code and also how to use foreach on this result, here the example below :
class Person
{
    public string Name { get; set; }
}

class Animal
{
    public string Name { get; set; }
}

class PersonRepository
{
    public List<Person> GetPersons()
    {
          List<Person> list = new List<Person>();

          //Some processing...

          return list;
    }
}

class AnimalRepository
{
    public List<Animal> GetAnimals()
    {
        List<Animal> list = new List<Animal>();

        //Some processing...

         return list;
    }
}

public class ReflectionClass
{
    public List<T> GetResultFromMethodInvoked<T>(string entityName, string repositoryName, string methodName)
    {
        List<T> lists = new List<T>();
        Type entity_type = Type.GetType("Entities." + entityName + " ,Entities");
        Type repository = Type.GetType("Crud." + repositoryName + ", Crud");
        MethodInfo method = repository.GetType().GetMethod(methodName);

        var r= method.Invoke(repository, parameters);

        Convert.ChangeType(r, typeof(List<>).MakeGenericType(new Type[] { entity_type }));

        lists = (List<T>)r;

        return lists;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ReflectionClass reflection = new ReflectionClass();
        /* Should have List<Person> as RESULT */
        reflection.GetResultFromMethodInvoked("Person", "PersonRepository", "GetPersons");

        /* Should have List<Animal> as RESULT */
        reflection.GetResultFromMethodInvoked("Animal", "AnimalRepository", "GetAnimals");
    }
}

A: In your code you use generics public List<T> GetResultFromMethodInvoked<T>(string entityName, string repositoryName, string methodName) so:
ReflectionClass reflection = new ReflectionClass();
/* Should have List<Person> as RESULT */
List<Person> result = reflection.GetResultFromMethodInvoked<Person>("Person", "PersonRepository", "GetPersons");

A: You can´t do this as the compiler as no knowledge that your runtime-string "Person" means the Person-type. You can´t expect the compiler to infer a type provided at runtime (e.g. via its name).
So you have three options.

*

*You allready mentioned this, cast to the actual list-type, e.g. List<Person>.

*alternativly let all your types that your list may contain inherit from a common interface and cast to a list of the interface-type
interface MyInterface
{
    public string Name { get; set; }
}
class Person : MyInterface
{
    public string Name { get; set; }
}
class Animal : MyInterface
{
    public string Name { get; set; }
}

Now use the interface for your list:
var result = reflection.GetResultFromMethodInvoked<MyInterface>("Person", "PersonRepository", "GetPersons");
foreach(var o in result)
    Console.WriteLine(o.Name);

*omit strong typing at all and go with the non-generic Enumerable-class and iterate this:
var result = (Enumerable) reflection.GetResultFromMethodInvoked("Person", "PersonRepository", "GetPersons");
foreach(var o in result) ...

For this to work your method should of course be non-generic also, as you can´t really use the generic type anyway outside that method.


text:
Q: Multiple filters using FIrebase Functions (Server Side) - React JS I'm trying to create an application where you have multiple blogs about lost, found and up for adoption pets. You can filter this blogs by:
'Categories (Lost, found, up for adoption)',
'Animal type (Dog, cat, bird, rabbit, etc)',
'Hair type (no hair, short, medium, long)',
'Gender (Female, male)',
'Eyes type (...)',
'HasCollar(yes, no)'
I've done a working filter but it was on the client side and since I'm going to handle a large amount of data, that solution won't work.
I've also tried to solve this problem using queries provided by firestore but I've come across with the limitation where I couldn't compare more than two categories.
This was the code
    if (activeCategory !== 'All' && activeGender === 'All' && activeAnimal === 'All') {
    q = query(
        collection(db, "blogs"),
        where("category", "==", activeCategory),
        where("gender", "!=", activeGender),
        where("animal", "!=", activeAnimal),
        )

    onSnapshot(
        q,
        async (snapshot) => {

         let list = []

    snapshot.docs.forEach((doc) => {
        list.push({id: doc.id, ...doc.data()})
    })

 lastDoc = await snapshot.docs[snapshot.docs.length - 1]
 firstDoc = await snapshot.docs[0]

    list.sort((a, b) => (a.timestamp < b.timestamp) ? 1 : -1)

    setBlogs(list)
    setFilters(list)
    setLoading(false)
    setActive("home")
    setLastDoc(lastDoc)
    setFirstDoc(firstDoc)
        }, (error) => {
            console.log(error)
        }

    )

} else if{...} }

useEffect(() => {
  fetchData()
}, [activeCategory, activeGender, activeAnimal])

So my only option is to use Firebase functions. I've talked to a friend and he told me that I needed to have endpoints like this, for example
https/firebase.adoptar.com/api/filter? activeCategory=adopcion

The thing is, I don't know how to do it or where to search information in order to learn about this. It has an structure resembling node js, right?
So I'm trying to come up with a solution using firebase functions. Can someone help me or tell me where to search so I can learn how to do it? Or how a query should look like in order to multifilter and update the page's info according the filter?
I've read firebase functions documentation but at best it tells you how to do a CRUD operation, nothing about filtering or creating an endpoint like the one above.


text:
Q: What happens to matter in extremely high gravity? Though I am a software engineer, I have bit interest in sciences as well. I was reading about black holes and I thought if there is any existing research results on How matter gets affected because of extremely high gravity. I tried searching but these long equations really didn't help me. Can someone please put it in layman terms?
More specifically if I ask Why the infinite gravity doesn't tear down the atoms in to quarks and does it have enough potential that it can affect something a Planck scale?

A: Extreme gravity essentially equates to extreme pressure. We see a progression in stellar evolution.
The high pressures of the huge gravitational pull of a star is at first counteracted by electromagnetic/thermal interactions between gas particles. However, at a certain point (with enough gravitational pull) these interactions are not enough and the gravitational force overwhelms electromagnetic forces. Positively charged nuclei collide into positively charged nuclei and hydrogen fusion occurs. The star is supported from further collapse via electron degeneracy pressure, where two electrons cannot occupy the same quantum state.
As elements bind into heavier elements, fusion becomes more and more difficult and requires more energy. Eventually the nuclear forces are not sufficient and the star collapses further, allowing carbon to fuse. This carbon fusion is much more energetic than the proceeding fusion and the star explodes. If there is sufficient mass, a supernova occurs and the remnant could be a neutron star (if the star exceeds the Chandrashankar limit of about 1.44 solar masses) or a black hole (if the star exceeds the Tolman-Oppenheimer-Volkoff Limit of 3 solar masses).
In a neutron star, fermi-degeneracy pressure keeps the particles from collapsing down to a gravitational singularity. Essentially there is enough pressure to force electrons into protons and form neutrons (inverse beta decay), and the neutrons are only stopped from colliding with each other by neutron degeneracy pressure. With a large enough mass though, even this is not enough to stop collapse, to either a theoretical quark star or even to a black hole.
So essentially we see as pressure increases, the various forces that keep matter matter-like get overcome. First electromagnetic interactions, then electron degenerecy pressure, then neutron degenercy pressure, and finally a collapse into a singularity/black hole (or something like that).
Edit: In response to the original poster's question, they can theoretically condense further to a quark degenerate matter. The specifics at this level get more fuzzy, since the strong force is difficult to model accurately due to asymptotic freedom. Unless there are particles that make up quarks, this is the lowest level of possible degeneracy.

A: Tidal disruptions
The single most distinctive feature of the gravitational field around massive compact objects such as black holes is the presence of strong tidal forces. These forces arise when the gravitational pull on one portion of an object differs significantly in strength from the pull on another portion of an object. Mathematically, tidal forces arise from the presence of sizable second derivatives of the gravitational potential (or, strictly speaking from the perspective of general relativity, second derivatives of the metric tensor).
As is well discussed in many other answers on this site and elsewhere on the Internet, an object falling directly toward a black hole will be stretched and ripped apart from the tidal forces acting on it. If the object is a person falling feet first, the gravitational attraction will be stronger on the feet than on the head, which is what causes the stretching.
A current hot topic in astrophysical research is the tidal disruption of stars orbiting compact objects. Only within the last year or two, such events have begun to be directly observed.
Accretion-powered luminous objects
The gravitational field of a massive compact object provides a tremendous potential energy well. This potential energy can be released as electromagnetic radiation when objects fall into hot accretion disks surrounding the compact object. A quasar is the brightest example of an accretion-powered luminous source - indeed, quasars are the among the most energetic light sources in the universe and are among the most distant objects we can observe on earth.
Accretion into a gravitational potential well is the universe's most efficient mechanism for releasing energy. On average, 10% of the total mass-energy ($m c^2$) that falls into quasars gets radiated away as light. In extreme cases, especially when the black hole has a large amount of angular momentum, this efficiency can rise even closer to unity. Compare to this to efficiency of hydrogen fusion into helium in the sun, which only converts 0.7% of the mass-energy into radiation.
Wrapping up magnetic fields
Einstein's theory of general relativity interprets gravity as curvature in four-dimensional spacetime. An example of a purely relativistic gravitational effect is a type of 'twisting' or wrapping up of space known as frame-dragging. Frame dragging can have a number of interesting effects. One of the most dramatic is the wrapping of magnetic fields into coils which can then launch matter from an accretion disk at relativistic speeds. The details of this magnetic jet-launching are explained either by the so-called Blandford-Znajek mechanism or the Penrose process.
Emission of gravitational waves
When two massive objects such as black holes get close to each other, as often happens to the central super-massive black holes in galaxies following a major galaxy merger, their orbital motion can send out waves of stretching and compression of spacetime called gravitational radiation. Very soon (it is June 2012 as of the time of this writing), scientists can expect to detect these gravitational waves directly at the Laser Interferometer Gravitational-Wave Observatory (LIGO).

A: Let us separate the matter into two branches:
a)Black Holes, which are governed by those equations you are loath to delve into
b)matter in high gravity fields , if the mass is low enough so that a black hole cannot form, according to the equations.

Gravitational collapse is at the heart of structure formation in the universe. An initial smooth distribution of matter will eventually collapse and cause a hierarchy of structures, such as clusters of galaxies, stellar groups, stars and planets. For example, a star is born through the gradual gravitational collapse of a cloud of interstellar matter. The compression caused by the collapse raises the temperature until nuclear fuel reignites in the center of the star and the collapse comes to a halt. The thermal pressure gradient (leading to expansion) compensates the gravity (leading to compression) and a star is in dynamical equilibrium between these two forces.
Gravitational collapse of a star occurs at the end of its lifetime, also called the death of the star. When all stellar energy sources are exhausted, the star will undergo a gravitational collapse. In this sense a star is in a "temporary" equilibrium state between a gravitational collapse at stellar birth and a further gravitational collapse at stellar death. The end states are called compact stars.
The types of compact stars are:
White dwarfs, in which gravity is opposed by electron degeneracy pressure;
Neutron stars, in which gravity is opposed by neutron degeneracy pressure and short-range repulsive neutron–neutron interactions mediated by the strong force;
Black holes, when the mass is high enough, and where the  the physics at the center is unknown.

The link from which the quote is taken can inform further.


text:
Q: Where does git clone stores temporary files ,when cloning remote repository to local? I am trying to clone repository,with size 500MB. When we run command

git clone https://repository.com/repo dir

It will show status cloning, speed and how much data cloned (250MiB|2MiB/s ). But actual directory where it is being cloned will remain empty(except .git) until clone completes. Where does it will store cloned files meanwhile?

A: The repository consists of two parts:

*

*Refs (name-to-hash mappings) – they're small, so they are kept in memory while downloading, then saved to .git/packed-refs and/or .git/refs/* afterwards.

*Pack (compressed history archive) – written to .git/objects/pack/tmp_pack_<random> while downloading, later renamed to .git/objects/pack/pack-<id>.pack once the download is complete.
Worktree files on a brand-new clone are always identical to the topmost commit's contents, so they aren't downloaded separately – they're simply extracted from .git/objects/* using the same packfile that was just downloaded.


text:
Q: Problems using broadway.js and raspi-camera over websocket What I wanna do is use the PI to control a small vehicle I build. I want to control this over a webinterface and also want to use the PI-camera to get a livestream when driving.
I am using nodejs on the PI with this module: https://www.npmjs.com/package/raspivid-stream to get the stream from the PI-camera. Here is my nodejs-code:
var raspividStream = require('raspivid-stream');
var stream = raspividStream();

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  stream.on('data', (data) => {
    ws.send(data, { binary: true }, (error) => { if (error) console.error(error);
  });
});

and here the index.html:
...htmlstuff...
<canvas id="stream"></canvas>
<script src="decoder.js"></script>
<script src="player.js"></script>
<script>
    var connection = new WebSocket('ws://raspberrypi:8443');
    var p = new Player();
    p.canvas = document.getElementById("stream"); // the canvas - p$
    connection.onopen = function () {
      connection.send('Ping'); // Send the message 'Ping' to $
    };

    connection.onerror = function (error) {
      console.log('WebSocket Error ' + error);
    };

    connection.onmessage = function (e) {
      console.log(e.data);
      p.decode(e);
    };
</script>
...htmlstuff...

So far I get this errors in the browser console:
wasm streaming compile failed: TypeError: Failed to execute 'compile' on 'WebAssembly': Incorrect response MIME type. Expected 'application/wasm'.
falling back to ArrayBuffer instantiation
failed to asynchronously prepare wasm: CompileError: AsyncCompile: Wasm decoding failed: expected magic word 00 61 73 6d, found 3c 21 44 4f @+0
CompileError: AsyncCompile: Wasm decoding failed: expected magic word 00 61 73 6d, found 3c 21 44 4f @+0
 Uncaught (in promise) abort({}). Build with -s ASSERTIONS=1 for more info.

Anybody got an idea how to solve this?

A: There's a static file asset in the latest version of Broadway called avc.wasm. You need to get your server to deliver it with the correct MIME Content-type, application/wasm so the decoder can load it.
Or you can try an older version of broadway using asm.js rather than WebAssembly. It's here.


text:
Q: SVN Replace command for particular file There is file text.jsp in my branch. I want to commit this file into trunk.
I have done check out for trunk folder and i navigated to text.jsp file location in trunk folder.
What is the command to replace. I tried below command
svn replace text.jsp https://mybranch/text.jsp
What is right command in svn command prompt.

A: The best way is to do it with svn merge command as it will keep the full commit log/history of your text.jsp file in trunk
svn merge --accept theirs-full https://mybranch/text.jsp https://mytrunk/text.jsp
If there are merge conflicts you are forcing to ignore them with --accept theirs-full option as you want to replace the file.

If you don't want to keep the full commit log of text.jsp file in trunk do it like this. (Note that this way the commit log will be started newly)

*

*svn delete https://mytrunk/text.jsp

*svn copy https://mybranch/text.jsp https://mytrunk/text.jsp

*svn commit
This way you'll avoid unnecessary hassle with branch/trunk checkout, exporting, moving and committing the file manually.

Alternatively you can do it also like this

*

*Navigate to directory where your original text.jsp is (trunk version)

*Export the "new" file svn export https://mybranch/text.jsp

*As the name of your "new" file is the same as the one in your repository
svn will automatically detect it as a modification. So you just
need to commit it with svn ci text.jsp


text:
Q: Add Image For UIBarButtonItem From xib File- Objective C I am trying to add an image for my UIBarButtonItem from the xib file itself. However, I am getting a grey coloured button which is of the same size and shape as that of my image. How can I display the image correctly and directly from my xib file itself without going into the writing of code manually ?? The button is present on a toolbar. Thanks and Regards.

A: Use UIButton beside of barButtonItem. It will automatically make a barButton and a Button inside of that.
then you need to change batButtonItem text to "" and change the Image of UIButton
as I tested it will work and show your pic beside of barButtonItem


text:
Q: Can I prevent MQXR clients reading other clients publications We're using MQXR for MQTT and the scenario is this.
Many clients publish with topic AAA/BBB/clientid/otherinfo
The ISB (ACEv12) subscribes to AAA/BBB/+/+ in order to process all such publications.
If Client01 publishes with AAA/BBB/client01/otherinfo,
Is there any way we can prevent Client02 subscribing to AAA/BBB/+/+ and receiving CLient01's publications.


text:
Q: How To Get Selected Item From Menu Button javaFX? i have just started javaFX and i have made a ButtonMenu with few options. i want to get what user selects from menu.
here is my code so far ->
controller class >
@FXML
private JFXTextField locF;
private File file;
private Set<String> extensions;
@FXML
private MenuButton format;

public void openFileBrowser(ActionEvent event){

    DirectoryChooser chooser = new DirectoryChooser();
    chooser.setTitle("JavaFX Projects");
    chooser.setInitialDirectory(new File("c:/"));
    File selectedDirectory = chooser.showDialog(Main.stage);
    locF.setText(selectedDirectory+"");
    extensions=getFileTypes(selectedDirectory.listFiles());//just gets all different types format present in the folder and later add it to menu
    Iterator<String> it=extensions.iterator();
    while (it.hasNext()){
     format.getItems().addAll(new MenuItem(it.next()));
    }
}

private Set<String> getFileTypes(File[] list){
    Set<String> ext=new HashSet<>();
    for (File i:
         list) {

        if (i.isFile()){

                ext.add(i.getName().substring(i.getName().lastIndexOf(".")));

        }

    }

    return ext;
}

}
FXML ->

<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.MenuButton?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.102" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <top>
      <GridPane BorderPane.alignment="CENTER">
        <columnConstraints>
            <ColumnConstraints hgrow="SOMETIMES" maxWidth="295.0" minWidth="10.0" prefWidth="57.0" />
            <ColumnConstraints hgrow="SOMETIMES" maxWidth="295.0" minWidth="10.0" prefWidth="93.0" />
          <ColumnConstraints hgrow="SOMETIMES" maxWidth="564.0" minWidth="10.0" prefWidth="311.0" />
          <ColumnConstraints hgrow="SOMETIMES" maxWidth="575.0" minWidth="0.0" prefWidth="77.0" />
            <ColumnConstraints hgrow="SOMETIMES" maxWidth="575.0" minWidth="10.0" prefWidth="69.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <JFXTextField fx:id="locF" focusColor="#47c64d" unFocusColor="#821dda" GridPane.columnIndex="2" GridPane.rowIndex="1" />
            <JFXButton fx:id="browse" mnemonicParsing="false" onAction="#openFileBrowser" prefHeight="78.0" prefWidth="123.0" ripplerFill="#2de823" text="Browse" GridPane.columnIndex="3" GridPane.rowIndex="1" />
            <Label fx:id="locL" prefHeight="48.0" prefWidth="143.0" text="Enter Location" GridPane.columnIndex="1" GridPane.rowIndex="1" />
         </children>
      </GridPane>
   </top>
   <right>
      <GridPane BorderPane.alignment="CENTER">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" maxWidth="95.0" minWidth="10.0" prefWidth="61.0" />
          <ColumnConstraints hgrow="SOMETIMES" maxWidth="139.0" minWidth="10.0" prefWidth="139.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints maxHeight="98.0" minHeight="0.0" prefHeight="17.0" vgrow="SOMETIMES" />
          <RowConstraints maxHeight="227.0" minHeight="10.0" prefHeight="227.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <MenuButton fx:id="format" mnemonicParsing="false" prefHeight="29.0" prefWidth="109.0" text="Format" GridPane.columnIndex="1">

            </MenuButton>
         </children>
      </GridPane>
   </right>
</BorderPane>

i have tried going to oracle but haven't found any info. Any help is appreciated.

A:
As i can :

A  MenuButton  control looks like a button and behaves like a menu.
  When it is activated (by clicking or other  means), it shows a list of
  options in the form of a pop-up menu. The list of options in the menu
  is maintained  in an  ObservableList  whose reference is
  returned by the  getItems()  method. To execute a  command when a menu
  option is selected, you need to add the  ActionEvent  handler to the
  MenuItems.

So it has not build in mechanism for detecting which MenuItem is selected...
Except if you are using RadioMenuItemor CheckMenuItemwith groups,that is other story..In that case you can get the selected item from the ToggleGroup you are using to group those buttons.

Solution:
For each MenuItem you have added into the MenuButton ObservableList add an actionListener:
 while (it.hasNext()){
     MenuItem item = new MenuItem(it.next());
     item.setOnAction(a->{ //lambda expression
        //..code logic here for each extension
     });
     format.getItems().add(item);
 }

A: I found this solution by doing a Google search.
Override
public void start(Stage stage) {
    Group root = new Group();
    Scene scene = new Scene(root);
    stage.setScene(scene);

    ChoiceBox<String> cb = new ChoiceBox(FXCollections.observableArrayList("item1", "item2", "item3"));
    cb.getSelectionModel().selectedIndexProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
        String selectedItem = cb.getValue();
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Example");
        alert.setContentText("You clicked " + cb.getItems().get((Integer)newValue));
        alert.showAndWait();
    });

    root.getChildren().add(cb);
    stage.show();
}

You can play around with this until you get your desired results.


text:
Q: Couldn't make POST request from iPhone to ColdFusion API I am having a strange problem while making an application in iPhone. The problem is in making a POST request to the server API in ColdFusion. We have two servers: one is for Testing and other for Production. The app works perfectly on the Testing server, but when we do a POST request in Production server the API couldn't read the request variable and gives error as Element xxxxx is undefined in ATTRIBUTES, but actually it is there. One reason could be different User-Agents, but after trying many combinations it does not work.
Any help would be very appreciated.

A: I don't understand why you're talking about different user-agent? It's iPhone to test server or iPhone to production server, no? Is the configuration exactly the same including the Application.cfc (or Application.cfm)?
Web app or native app calling cfc's?

A: I don't think user-agents make any difference. Try to submit request directly through browser to make sure it is really working. Best way to do that NSLog url request and paste it in browser.

A: I figured out the problem. It was the "LINK" I was using. The API worked with adding "www" to the link, where as I was using the link without "www". Hope it helps someone.
Thanks.


text:
Q: Observable vs Promise for single values Typescript (and now also ECMAScript 2017) gives you great asynchronous tools to use in the form of async/await. However, working with Angular 4, I get the feeling that using Observables is preferred. My question is: When I have a function which returns a single value once (ex: confirmation modal), are there any big advantages with using observables, or would promises (async/await) be preferred/just as good? Is it not weird to use observables? Do they not represent a stream of values?
Tl;dr:
async showDialog(msg: string): Promise<DialogResult>

vs.
showDialog(msg: string): Observable<DialogResult>

A: It doesn't matter which one you use. Promises and Observables can be freely interchanged. Have a look at this https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875
I personally find it easier to work with Observables even when you need to return just one value.
With Promises you often need to keep three properties:
class Whatever {
  resolve: Function;
  reject: Function;
  promise = new Promise((resolve, reject) => {
    this.resolve = resolve;
    this.reject = reject;
  });

  method() {
    return this.promise;
  }

  otherMethod() {
    this.resolve();
  }
}

With Observables you can keep just an instance of Subject:
class Whatever {
  subject = new Subject();

  method() {
    return this.subject.toPromise();
  }

  otherMethod() {
    this.subject.next(...);
    this.subject.complete();
  }
}


text:
Q: Rigorous definition of generalized coordinates In Goldstein's classical mechanics and in many other books I haven't seen a rigorous definition of generalized coordinates.
In a system of $N$ particles described by $\textbf{r}_1, \dots, \textbf{r}_N$ It is said that some variables $q_1, \dots , q_n $ are generalized coordinates if we can express:
\begin{equation}\label{eq1}
\begin{array}{ccc}
\textbf{r}_1 & = & \textbf{r}_1(q_1,\dots,q_n,t)\\
& \vdots & \\
\textbf{r}_N & = & \textbf{r}_N(q_1,\dots,q_n,t)\\
\end{array} \tag{1.38}
\end{equation}
and viceversa, we can express $q_1,\dots,q_n$ in terms of $\textbf{r}_1,\dots,\textbf{r}_N$ i.e., this transformation must be bijective.
Nevertheless nothing is said about the regularity of this transformation.
Does this transformation need to be a diffeomorphism, just a differentiable homeomorphism or what do we need to ask for?

A: The configuration space of $N$ points  is obtained by assuming that the $C< 3N$ constraints are functionally independent at every fixed time. The implicit function theorem (or regular value theorem) implies that the configuration space is a $n$ dimensional manifold, an embedded submanifold of $R^{3N}$, where $n= 3N-C$. Lagrangian coordinates are nothing but any local coordinate patch.
If the constraint equations are expressed by means of functions of regularity class $C^k$, the arising manifold has the same degree of regularity. Hence the Lagrangian coordinates are of class $C^k$ as well.


text:
Q: Get all records for Top N Distinct values I have a BookAuthor table like below (SQL Server 2008 R2 Ent):
BookID  AuthorID
------  --------
43      676
43      76
43      354
71      89
71      76
99      71
64      50
64      39
64      354

I want to get all records for top 2 distinct BookID. So, expected output will be as below:
    BookID  AuthorID
    ------  --------
    43      676
    43      76
    43      354
    71      89
    71      76

I tried the below simplest query and it is only returning 2 rows.
Select top 2 * from BookAuthor order by BookID ASC

So, how can I proceed here ? Any help is appreciated.

A: You can use the following to get the TOP 2 DISTINCT BookIds:
select t1.bookid, t1.authorid
from BookAuthor t1
inner join
(
  select distinct top 2 bookid
  from BookAuthor
  order by bookid
) t2
  on t1.bookid = t2.bookid

See SQL Fiddle with Demo
You stated that you want the Books with the id's 43, 71 returned because those are the top 2 book ids but data in a table is not inherently ordered. Unless you have another column that you can get the rows in that order, if you order by bookid ascending then you will return 43, 64.

A: What about below query:
Select * from BookAuthor where BookID in(
select Distinct top 2 BookID from BookAuthor order by BookID asc)

It's working fine for me


text:
Q: __raw_readl() always returns 0x00 for Freescale i.MX 6 PXP Registers I am working with a Freescale i.MX6DualLite processor on a custom board. The imx camera HAL supports the SoC's Pixel Pipeline module to convert pixel formats of USB cameras. Therefore, I ported the following kernel driver into my kernel:
https://github.com/boundarydevices/linux-imx6.git
Branch: boundary-imx-o8.0.0_1.0.0-ga
Unfortunatly, accessing the PXP does not work. The ioctl() calls PXP_IOC_CONFIG_CHAN, PXP_IOC_START_CHAN and PXP_IOC_WAIT4CMPLT fail because the PXP interrupt is not triggered.
Therefore I added several printk() statements to check PXP registers:
[67221.574349] pxp: HW_PXP_CTRL 0x0
[67221.574352] pxp: HW_PXP_STAT 0x0
[67221.574355] pxp: HW_PXP_OUT_CTRL 0x0
[67221.574357] pxp: HW_PXP_OUT_BUF 0x0
[67221.574360] pxp: HW_PXP_AS_CTRL 0x0
[67221.574363] pxp: HW_PXP_AS_BUF 0x0
[67221.574365] pxp: HW_PXP_PS_CTRL 0x0
[67221.574368] pxp: HW_PXP_PS_BUF 0x0

Every relevant register is 0x00. I triple checked clocking mechanism and CCM registers: The PXP has a clock signal. So I assume this is not the problem. I also verified the PXP register address specified in the DTS. It is correct and successfully remapped into my kernel memory. I also played with ioremap_no_cache() but it did not help.
So my question is: Has anyone experienced the same kind of problem with any Freescale i.MX6 module? Is there some kind of enable signal I am missing?