text:
Q: Is there a proven way to manage a collection of atoms in Recoil? I'm testing Recoil and I need to manage a list of posts to display in the homepage.
My first idea was to make a big Atom with all the posts, but this seems a bit violent as we can edit posts directly on the homepage.
My second idea was to dynamically generate atoms with a prefix:
const onePost = (postId: string) => atom({
  key: 'post_' + postId,
  default: null,
  effects_UNSTABLE: [localStorageEffect('@post_' + postId)],
});

Then I realized that I was pretty a rookie playing with fire and that I shall ask people who are knowledgeable about Recoil on StackOverflow...

A: You can use atomFamily to manage your posts. You can use another atom to manage the post ids, if you want to add and delete posts.
const postsFamily = atomFamily({
  key: 'postsFamilyKey',
  default: [0, 0],
});

function PostListItem({postID}) {
  const post = useRecoilValue(postsFamily(postID));
  return (
    <div>
      Post ID: {postID}
      Post: {post}
    </div>
  );
}

A: You can just use an array:
const postIds = atom({
  key: 'postIds',
  default: [],
  effects_UNSTABLE: [localStorageEffect('postIds')],
});

This way you manage the list of ids in one atom and those ids can refer to different atomFamilys that hold the content data of the posts.


text:
Q: How do you assign "null" to a Delphi.net Nullable How do you assign null to a Delphi.net Nullable? I have a field which previously contained a value , I need to clear its value back to null.
depth : Nullable<Double>;

Procedure ClearDepth;
begin
    depth := Nil;
end;

The above creates the error Error: E2010 Incompatible types : 'Nullable<System.Double>' and 'Pointer'. using Null in place of Nil gives the same error with Variant in place of Pointer. I wondered if I should be using a special constructor to generate a null nullable but I couldn't see one in the documentation?
The following works but doesn't seem like a great solution, can anyone suggest a better way?
Procedure ClearDepth;
var
    uninitialisedValue : Nullable<Double>;
begin
    depth := uninitialisedValue;
end;

A: You need this syntax:
depth := Default(Nullable<Double>);

A: The type Nullable<T> is a struct. That means it has a public parameterless constructor. In the case of this type, that's the value that represents null. In C#, you would use:
new Nullable<Double>()

Another way to get the same value in C# would be
default(Nullable<Double>)

In both cases, I don't know the syntax for Delphi. In the second case, I don't know whether something like this can be even represented there.
EDIT: Apparently, you can use the second version in Delphi, but not the equivalent of the first one. That's quite surprising to me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: String from xml which is an anchor tag not showing list of browser when clicking it I have a paragraph in the xml file. in that paragraph I have some string as a link like below:
which can be located at `<a href="https://www/tutorial.html">https://www.tutorial.com </a>.` this is

When clicking on it, it should launch the URL in the browser.
Is the implementation correct?

A: There are two ways of doing it.
You need to call setMovementMethod:
textView.setMovementMethod(LinkMovementMethod.getInstance());

2nd
textView.setLinksClickable(true);

in XML should be
<TextView
    android:id="@+id/textView"
    android:autoLink="web"
    android:linksClickable="true"
/>

Make sure you set your text using Html.fromHtml in this way it will read the html anchor tags as anchor and clicking on it will open the browser.
you can also create a WebView and pass the String of the link as a URL to open it in your Application not using external browser.
I hope it helps.

A: You are using an html tag in String if you want to href tag to be clicked you need to load this string into a webView and then you it'll be clickable and function exactly what you want.
But if you want to show in a TextView then just put your url in the String like https://www/tutorial.html.

A: Write this in your string.xml file
<string name="link">Google</string>

((TextView) findViewById(R.id.link)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.link)).setText(Html.fromHtml(getResources().getString(R.string.link)));


text:
Q: WebGL framework - what's the best choice? X3DOM? I'm about to start a Web application that will use interactive generated 3D content. Aim is to let it run natively in the browser, i.e. no Flash is allowed, only JavaScript + HTML5.
Apart from using pure WebGL it's better to use a lib that will offer a more high level interface.
The approach of X3DOM looks great for me - and it looks like it's supposed to become native in the browser and the lib will pave the road.
But after my first impressions I'm not sure if it's lightweight enough. Apart from the 400kb JS-File it slows down Firefox.
The features I need are not many. The whole scene set up could be easily done by "hand". But I need user interaction including to figure out where the user clicks. And later I want to be able to load and insert 3D objects in a common file format.
PS: Browsers of choice are Firefox and Webkit based ones. Desktop and Mobile ones. I don't care about IE.
PPS: Yes, I know the question: WebGL Framework

A: X3DOM is great when you come from an X3D background (and developed by great people), but if you have no preference watsoever, Three.JS would be my pick.

A: I looked at most WebGL frameworks just last week, and it indeed seems almost every one of them is in the 300kB range. That's too heavy for me, too. Luckily I found lightgl.js which has everything you need to get started in 28kB, MIT license.
The main thing for me is just abstracting canvas, shader and texture initialization. But lightgl.js does also have some mouse handling and model loading etc.

A: i think the decision boils down to:
do you want to have a more design or programmer approach.
x3dom: its leveraging of x3d for describing the scene lends itself to a more designer approach, with just the adding of the x3dom css and js one can do this :
<X3D><Scene><Shape><Box/></Shape</Scene></X3d>

three.js: only allows for scene generation through javascript, and a lot of additional code is necessary just to set up the canvas. view the source of this simple box example: http://stemkoski.github.com/Three.js/Template.html
neither way is wrong, i prefer designing the scene and then using js when needed for any computations.


text:
Q: select bind in Blazor When I change the select item, why GetSelectedVariant function is called also?

@page "/product/{id:int}"
@inject IProductService ProductService

@if (product == null)
{
    @message
}
else
{

@product.Ttile

@product.Description

            @if(product.Variants != null && product.Variants.Count > 1)
            {

                    <select class="form-select" @bind="currentTypeId">
                        @foreach(var variant in product.Variants)
                        {
                            <option value="@variant.ProductTypeId">@variant.ProductType.Name</option>
                        }
                    </select>

            }
            @if (@GetSelectedVariant() != null)
            {
                if (@GetSelectedVariant().OriginalPrice > GetSelectedVariant().Price)
                {

                        $@GetSelectedVariant().OriginalPrice

                }

                    @*$@product.Price *@
                    $@GetSelectedVariant().Price

            }

}

@code {
    private Product? product = null;
    private string message;
    private int currentTypeId = 1;

    [Parameter]
    public int Id { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        //product = ProductService.Products.Find(p => p.Id == Id);

        message = "Loading Product...";

        var result = await ProductService.GetProduct(Id);

        if (!result.Success)
        {
            message = result.Message;
        }
        else
        {
            product = result.Data;
            if (product.Variants.Count > 0)
            {
                currentTypeId = product.Variants[0].ProductTypeId;
            }
        }
    }

    private ProductVariant GetSelectedVariant()
    {
        var variant = product.Variants.FirstOrDefault(v => v.ProductTypeId == currentTypeId);
        return variant;
    }
}

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa


text:
Q: How to create a compound view behaving like one component is ViewGroup in layout.xml I want to build a compound view that has a ScrollView and a LinearLayout as its base.
Inside that LinearLayout there are multiple Views and also an empty layout ConstraintLayout, which I want to fill in a layout.xml file.
Example:
CompoundView:
<ScrollView>
    <LinearLayout>
        <!-- Some views that come first -->

        <ConstraintLayout
            android:id="@+id/fillableViewGroup">

            <!-- This is the part that I want other Views to be able to fill -->

        </ConstraintLayout>
    </LinearLayout>
</ScrollView>

And I want it to be used like this:
UsingView:
<CompoundView>
    <TextView/>
    <TextView/>
    <TextView/>
</CompoundView>

So that it behaves like this, including all of the constraints I have defined in UsingView:
<ScrollView>
    <LinearLayout>
        <!-- Some views that come first -->

        <ConstraintLayout
            android:id="@+id/fillableViewGroup">
            <TextView/>
            <TextView/>
            <TextView/>
        </ConstraintLayout>
    </LinearLayout>
</ScrollView>

Is there maybe some function that would allow me to do something like this?:
class CompoundView() {
    override fun viewGroupContainer() : ViewGroup {
        return fillableViewGroup
    }
}

Or maybe something else that would allow me to assign a ViewGroup to be populated via layout.xml?
I have tried googeling for a solution but basically all I find is tutorials for basic compound views.
PS:
I do understand that I might be able to write a function in the class declaration of my CompoundView that would allow me to add a view to one if its children, however, I specifically want it to be able to do so in layout.xml.


text:
Q: Weak symbol aliases on OS X similar to those on Linux, or a closest equivalent? What I do
When writing shared libraries for Linux, I tend to pay attention to relocations, symbol visibility, GOT/PLT etc.
When applicable, I am trying to avoid calling PLT stubs when functions from the same library call each other. For example, let's say a shared object provides two public functions - foo() and bar() (either of those can be called by user). The bar() function, however, also calls foo(). So what I do in this case is this:

*

*Define _foo() and _bar() functions that have private visibility.

*Define foo() and bar() weak aliases for _foo() and _bar() respectively.

That way, the code in shared object never uses weak symbols. It only invokes local functions, directly. For example, when _bar() is invoked, it calls _foo() directly.
But users are not aware of _* functions and always use corresponding weak aliases.
How I do it
In Linux, this is achieved by using the following construct:
extern __typeof (_NAME) NAME __attribute__(weak, alias("_NAME"));

The problem
Unfortunately, this does not work for OS X. I have no deep knowledge of OS X or its binary formats, so I poked around a bit and found a few examples of weak functions (like this one), but those don't quite do the same as you can have a weak symbol, but not a weak symbol that is an alias for DSO's local function.
Possible solution...
For now, I have just disabled this feature (that is implemented using macros) so that all symbols are global and have default visibility. The only way I can think of to achieve the same for now is to have all _foo functions with private visibility and have corresponding foo functions with default visibility and calling their "hidden" counterparts.
A better way?
That, however, requires a good chunk of code to be changed. Therefore I would prefer not to go there unless there is really no other way.
So what is the closes OS X alternative or the easiest way to get the same semantics/behavior?

A: On OS X, calls made within the library are automatically direct calls and do not go through the dyld stub. The evidence to the fact is that if you want to be able to inject alternative functions to service a call, you'll need to use interposable to force indirect access to the symbols and force execution of the call through the dyld stubs. Otherwise, by default, local calls will be direct and will not incur the overhead of running through dyld.
Thus, your optimization on Linux is already the default behavior and the alias is not needed.
Still, if you want to do this just to make your platform compatible code simpler, you can still make the aliases. You just need to use "weak_import" or "weak" (if you want coalesced) as your attribute name.

extern typeof (_NAME) NAME __attribute(weak_import, alias("_NAME"));

Apple reference on Weak Linking: Marking Symbols for Weak Linking

Apple reference on Mach-O runtime binding : Scope and Treatment of Symbol Definitions


text:
Q: How can I track how many times an "answer" is shown/called through my jquery? I have a script that works fine. It is a question and answer type of page and the script shows different answers/output based on the selected options.
I want to track how many times a particular answer is called. There are four answers. Here's a script for one of the outputs:
$(document).ready(function() {
    $("span[id^='answer']").hide();
    $("span[id^='loading']").show();

    $("input[name^='options']").change(function() {
        $("span[id^='answer']").hide();
        if ($("#q1_option1").is(':checked')) {
            if ($("#q2_option1").is(':checked')) {
                if ($("#q3_option3").is(':checked')) {
                    if ($("#q4_option1").is(':checked')) {
                        $("#answer4").show();
                        $("#answer11").show();
                        $("#loading").hide();
                    }
                }
            }
        }
    });
});

I'm not sure if I'm making any sense but I hope someone can help. Thank you!!

A: You can use sessionStorage.setItem() and .getItem
if ( ! sessionStorage.getItem('answer1_count') ) {

  sessionStorage.setItem('answer1_count',1);

} else {

  var value = sessionStorage.getItem('answer1_count');
  sessionStorage.setItem('answer1_count',parseInt(value) + 1);

}

And you insert that after or before the line that shows the Answer. And so you can retrieve the count by calling sessionStorage.getItem() anywhere on your script.


text:
Q: Creating a Batch to change a line (find and replace text) I'm trying to create a batch file that replaces a line in a text file.
The line is:
Window Resolution:
Depending on some settings in my program, this line can look like this:
Window Resolution: 1
Window Resolution: 2
Window Resolution: 3
I need to replace Window Resolution: (number) with Window Resolution: 1 using a batch.
My first guess would be to create something like this:
@echo off
setlocal enableDelayedExpansion

:Variables
set InputFile=configfile.txt
set OutputFile=tempconfigfile.txt
set "_strFind=Window Resolution:"
set "_strInsert=Window Resolution: 1"

:Replace
>"%OutputFile%" (
  for /f "usebackq delims=" %%A in ("%InputFile%") do (
    if "%%A" equ "%_strFind%" (echo %_strInsert%) else (echo %%A)
  )
)

DEL %InputFile%
MOVE %OutputFile% %InputFile%

ENDLOCAL

But I can't get this working... Any advice would be awesome. Thank you.

A: Your problem is if "%%A" equ "%_strFind%": Window Resolution: x will never be equal to Window Resolution:. Replace your if approach with:
echo %%A|findstr /bc:"Window Resolution:" >nul &&echo %_strInsert%||echo %%A


text:
Q: ParserError: Expected '{' but got '(' function stake() public payable () pragma solidity >=0.6.0 <0.7.0;

import "hardhat/console.sol";
import "./ExampleExternalContract.sol";

contract Staker {

    ExampleExternalContract public exampleExternalContract;
    mapping(address => uint256) public balances;
    uint256 public constant treshold = 1 ether;
    event Stake(address staker, uint256 amount);

    constructor(address exampleExternalContractAddress) public {
        exampleExternalContract = ExampleExternalContract(exampleExternalContractAddress);
    }

    function stake() public payable () {
        balances[msg.sender] = msg.value;
        emit Stake(msg.sender, msg.value);
    }
}

I am getting a parse error Expected '{' but got '(', when I try to deploy this code. Any thoughts on what's going on?

A: You have an extra pair of parentheses in the stake function definition.
Replace this
function stake() public payable () {

with this
function stake() public payable {


text:
Q: Why hibernate session save update row instead of insert row? I have installed Postgres version 10.1 on windows7x64. I have got a database "postgres" with one table "dbuser" and columns "user_id" and "username". I am using Intelij and Maven. I am using Session from hibernate to try to insert a row into a table.
App.java
package com.hibernateTest;

import org.hibernate.Session;

public class App {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    dbuser dbuser = new dbuser();
    dbuser.setUser_id(556);
    dbuser.setUsername("waaagr");
    session.save(dbuser);
    //session.merge(dbuser);//my mistake---old code
    session.getTransaction().commit();
    }
}

HibernateUtil.java
package com.hibernateTest;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }

}

dbuser.java:
    package com.hibernateTest;

import javax.persistence.*;

@Entity
@Table(name = "dbuser")
public class dbuser implements java.io.Serializable {

    @Id
    //@GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "user_id")
    private long user_id;

    @Column(name = "username")
    private String username;

    public dbuser() {
    }

    public dbuser(long user_id, String username) {
        this.user_id = user_id;
        this.username = username;
    }

    @Column(name = "username")
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "user_id")
    public long getUser_id() {
        return user_id;
    }

    public void setUser_id(long user_id) {
        this.user_id = user_id;
    }
}

Hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/mydb</property>
        <property name="connection_pool_size">1</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>
        <mapping class="com.hibernateTest.User"/>
    </session-factory>
</hibernate-configuration>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong.common</groupId>
    <artifactId>HibernateExample</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>HibernateExample</name>
    <url>http://maven.apache.org</url>
    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4-1203-jdbc4</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.3.Final</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>
    </dependencies>
</project>

The problem is that when I run my application I got:
Hibernate: select dbuser0_.user_id as user1_0_0_, dbuser0_.username as username0_0_ from dbuser dbuser0_ where dbuser0_.user_id=?
Hibernate: insert into dbuser (username, user_id) values (?, ?)

The first thing which is strange is that there is values with (?, ?) in the Terminal. And data in the table in the database is only update, but I would like to insert a new row not update a row?
I don't why this code update a row instead of insert a new one, a new row?
Thank you very much.

A: dbuser dbuser = new dbuser();
dbuser.setUser_id(556);
dbuser.setUsername("waaagr");
session.merge(dbuser);

So what you are doing here, is telling the hibernate that some user with id=556 probably exists in the database, and you want to merge your changes into the DB. This is so called detached entity.
What merge is doing, is fetching given entity by provided id (thus SELECT), check if there are some differences between data in database and in your object, and commits UPDATE operation on "dirty fields". In the same time, merge will return managed entity. This is how merge according to JPA specification works in general.
In your case, you have lied to hibernate that such entity already exists, but Hibernate know about this (becouse of empty results set for ID fetch) and it performs INSERT insteed of UPDATE.
So to wrap it up: By providing ID you are indicating that given entity should alredy exist in the database and merge is possible. If you would like to create new user (even with given id) use save insteed of merge


text:
Q: Magento error log How to fix these error log
exception 'Mage_Core_Exception' with message 'Invalid block type: Mage_Dailydeals_Block_Widget' in /var/www/html/domain/app/Mage.php:595
Stack trace:
#0 /var/www/html/domain/app/code/core/Mage/Core/Model/Layout.php(495): Mage::throwException('Invalid block t...')
#1 /var/www/html/domain/app/code/core/Mage/Core/Model/Layout.php(437): Mage_Core_Model_Layout->_getBlockInstance('dailydeals/widg...', Array)
#2 /var/www/html/domain/app/code/core/Mage/Core/Model/Layout.php(472): Mage_Core_Model_Layout->createBlock('dailydeals/widg...', 'c5d44ba0ab3a891...')
#3 /var/www/html/domain/app/code/core/Mage/Core/Model/Layout.php(239): Mage_Core_Model_Layout->addBlock('dailydeals/widg...', 'c5d44ba0ab3a891...')
#4 /var/www/html/domain/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->_generateBlock(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#5 /var/www/html/domain/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#6 /var/www/html/domain/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#7 /var/www/html/domain/app/code/core/Mage/Core/Controller/Varien/Action.php(269): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#8 /var/www/html/domain/app/code/core/Mage/CatalogSearch/controllers/ResultController.php(77): Mage_Core_Controller_Varien_Action->loadLayout()
#9 /var/www/html/domain/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_CatalogSearch_ResultController->indexAction()
#10 /var/www/html/domain/app/code/local/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')
#11 /var/www/html/domain/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#12 /var/www/html/domain/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#13 /var/www/html/domain/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#14 /var/www/html/domain/index.php(89): Mage::run('', 'store')
#15 {main}

A: Find in your app/etc/modules folder some xml file which name ends on Dailydeals.xml (for example Blabla_Dailydeals.xml)
Edit this file and put there
        <active>false</active>

Upd.1
Try to search in your app/design folder for the word dailydeals in layout xml files. Most probably e.g. in local.xml you forgot to remove it.
Or maybe you have CMS page with such block type which need to be disabled or removed.
Upd.2
Create sql dump of your magento DB with following command:
mysqldump -u USER -pPASSWORD DATABASE > /path/to/file/dump.sql

Then search in this file for the word dailydeals and show us where did you find it.


text:
Q: How to pivot rows into columns in Athena when you dont have the entire list of values or if the list is too long Like below in amazon Athena.
DATA
ID , CODE
a  , 123
b  , 345
a  , 123
a  , 345
c  , 246
d  , 678

Grouped Data
I have grouped above data with ID and CODE to get the frequency/count of the combination as below.
ID , CODE ,FREQ
a  , 123  , 2
a  , 345  , 1
b  , 345  , 1
c  , 246  , 1
d  , 678  , 1

Required Transformation
Required Transformation of the data : I am trying to get pivot the rows in CODE column into header row and create a matrix/data frame.
ID , 123 ,345 ,246, 678
a  ,   2 ,  1 , 0 , 0
b  ,   0 ,  1 , 0 , 0
c  ,   0 ,  0 , 1 , 0
d  ,   0 ,  0 , 0 , 1

On smaller data set I have successfully used R "Table" command and it works okay. But Now I have 27M unique IDs with 300 unique columns, with 220 M rows. so my ultimate matrix will have 27Mrows X 350 columns
My questions:

*

*Is there a query in Athena that I can write to achieve this result.

*Can I use R ? But Table command wont support it need to find a library to parallelize the data.Then use reshape2 package. Even that I am not sure how to go about.

*Is spark a better solution.If so how do i do it. I have already set up spark on a EC2 instance and downloaded the grouped data from S3 to EC2 tmp folder as a CSV its 8GB data file.

*Should I operate on the original data set or use the grouped by data set.

Kindly give me pointers. I am a newbie in all these technologies and figuring this out.


text:
Q: how to run python command line I have pycharm installed and do my class assignment in it and things work well. The teacher wants on to now run some of the programs in command prompt. Given that my programs and the path is here: "C:\Python27\python.exe C:/Users/sz5062/PycharmProjects/untitled1/main.py", how can I run a program that is saved the above path in command line? So, example, how would I run the main.py in command line, not shell prompt?
I have searched and searched for answers here, but I can't fine one. Thanks very much for your help.
This is the full instruction: Install Python and a programming text editor and write a program that prints one line other than 'hello world', then take two screen shots and upload them below. You should use the command line to execute the Python program you wrote in the text editor. Please do not use the IDLE Python Shell, the Python Interpreter (>>>), or a shortcut in your text editor to run the code.
When i run "python main.py", I get an error message "python is not recognized as inernal or external command".

A: On you Commandline enter:
C:\Python27\python.exe C:\Users\sz5062\PycharmProjects\untitled1\main.py

The above command should work from every directory.
First part is the program you start (python.exe). Second part is the argument you pass to the program(C:\Users\sz5062\PycharmProjects\untitled1\main.py). This is the path to your python code so that python.exe knows what you want to execute.
If you add C:\Python27\ to your PATH variable, you can navigate to your directory C:\Users\sz5062\PycharmProjects\untitled1\ and start your programm with:
python main.py

A: I'd recommend making sure that python is on your PATH (if you type python does it open a shell?) and then navigate to the C:/Users/sz5062/PycharmProjects/untitled1 directory. Once there you can do:
python main.py
and that should work.

A: I think I made this hard. since python was in installed on C:\python27, all I needed to run the command line was simply to write the code in a text editor, save it in the same directory and call it from there. So, essentially, c:\python27\code.py


text:
Q: Using twig to set HTML inline style I am new to using twig HTML and getting there slowly. I am trying to set the style in a widget as follows:
div class="progress xs">

However the % character gives the error: unexpected character sequence, expected a selector for the style rule, and the progress bar does not show the correct percent. Can someone explain what I am doing wrong here.
thanks
Derek


text:
Q: error while Live Search using Ajax Unable to get the results from database..!
This is my Index.html

    <title>Live Search</title>

        Enter The Name: <input type="text" onkeypress="findName(this.value)">

This is names.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");

$name=$_POST['partialName'];
$result=mysql_query("SELECT fname FROM name where fname LIKE '%$name';")or die(mysql_error());

while($list=mysql_fetch_array($result))
{
    echo "
".$result['fname']."
";
}

?>
And the error i am getiing while inspecting the element is:
Uncaught ReferenceError: findName is not definedonkeypress @ (index):16

A: this line $.POST("names.php",{partialName:str},function(data)); will throw an error (check console)

SyntaxError: expected expression, got ')'
ReferenceError: findName is not defined

check jQuery POST to see it
Here's a quick fix (added name to input too):

HTML:
<input type="text" name="str" onkeypress="findName(this.value)" />

A: So it should work ..
function findName(str){
      $.post("names.php",{partialName:str},function(data){
        $("#result").html(data);
    });
  }

A: Edit Your Function:


text:
Q: Fade Header on Scroll I am working on a website for a friend (https://www.nicoledavis.org) and have not been able to get the code right in order to make the top photo fade to black when scrolled. The idea is to have the entire top photo completely fade to black before the "Background Info" appears on the screen. Any help is much appreciated!
I used the exact code setup (copy/pasted) from here: https://jsfiddle.net/KCb5z/21 or see below:
jQuery:
    $(function () {
        $(window).scroll(function () {
            var currentScrollTop = $(window).scrollTop();
    $('#blackOverlay').css('opacity',
            currentScrollTop/$('#blackOverlay').height());
        });
    });

CSS:
    #blackOverlay {
      background-color: #000;
      opacity: 0.0;
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
    }

HTML:

The effect I'm seeing in the JSFiddle example is exactly what I'm hoping the website header does on the website I'm working on, but the code doesn't seem to have the same effect on my site. I'd also like for the speed of the fade effect to be increased, but have not yet been successful.

A: Is this what you're looking for?

header

You say you've tried some code, but it didn't work. May I take a look at it?


text:
Q: my deleted items is deleting from my to do list page ui but it deleting the wrong item in my local storage  Links.splice(Links.indexOf(linkIndex),1);

it is not finding the indexOf the element i clicked on in local storage
and it is deleting local storage from the back
what am i doing wrong please
ulEl.addEventListener("click",function(e) {
     const item = e.target;

     if(item.classList.contains("bin-img")){
         const link = item.parentElement.parentElement.parentElement;
         link.remove()
         function removeLocalLink(link) {
             let Links;
             if (localStorage.getItem("Links") === null) {
                 Links = [];
             } else {
                 Links = JSON.parse(localStorage.getItem("Links"));
             }
             const linkIndex = link.children[2].textContent;
             console.dir(linkIndex)
             Links.splice(Links.indexOf(linkIndex),1);
             console.dir( Links.splice(Links.indexOf(linkIndex),1))

             localStorage.setItem("Links", JSON.stringify(Links));
         }
         removeLocalLink(link)
    }
}


text:
Q: Firebase Auth - User locked after how many attempts for how long? I can't find documentation anywhere on how many failed attempts it takes for a user to get locked out with Firebase Authentication, nor how long the user is locked out for.
Where is this information documented for Firebase Authentication?


text:
Q: DrawText works in Windows, empty in Linux (Synology armv7l) I'm having a strange issue where SkiaSharp (2.80.0) mostly works in my Synology environment. It can draw shapes and resize and write images. It just never displays text.
The same code renders text just fine when run in Windows.
Here's a code sample just to demonstrate.
//In Windows, this produces blue TEST text on top of the resized source image as expected.
//In the Synology environment, the text is missing, but the image is still successfully resized.

float scale = (float)(RESIZE_WIDTH / originalImage.Width);
using (SKBitmap resizedImage = originalImage.Resize(new SKImageInfo((int)Math.Round(originalImage.Width * scale), (int)Math.Round(originalImage.Height * scale)), SKFilterQuality.High))
{
  using (SKCanvas canvas = new SKCanvas(resizedImage))
  {
    var paint = new SKPaint
      {
        Color = SKColors.Blue,
        IsAntialias = true,
        Style = SKPaintStyle.Fill,
        TextAlign = SKTextAlign.Center,
        TextSize = 90,
        Typeface = SKTypeface.CreateDefault()
      };
      var coord = new SKPoint(resizedImage.Width / 2, (resizedImage.Height + paint.TextSize) / 2);
      canvas.DrawText("TEST", coord, paint);
      canvas.Flush();

      using (var image = SKImage.FromBitmap(resizedImage))
      {
       using (var data = image.Encode())
       {
         using (var stream = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
           data.SaveTo(stream);
       }
     }
  }
}

Is there something I need to configure programmatically in SkiaSharp to get DrawText to work in the Synology environment that's just automagic in Windows?
Edit 1: I have now tested this on a Ubuntu install, and DrawText and everything else works fine there.
Edit 2: Add explicit Typeface to sample code

A: The solution that worked for me is to embed font(s) with the app and use SKTypeface.FromStream to load them if the system is unable to provide one.
Thanks to the advice provided by the SkiaSharp community on GitHub:
https://github.com/mono/SkiaSharp/issues/1564#issuecomment-748581747


text:
Q: Windows 10 refuses to install on certain drive A couple days ago I bought new notebook without OS. At first I installed Windows 10 on stock HDD drive - everything went ok. Then I decided to replace it with with SSD from my old laptop which is Samsung 840 EVO and which were working fine for years. Now goes the bad part...
During windows installation I unable to format SSD disk drive with error code 0x80070057. The stock drive and another HDD drive have no this problem with same bios settings and same windows distributive. The SSD drive itself is fully workable on old laptop and able to format disk during installation without problem. Moreover: if install Windows 10 on SSD on old laptop and after that insert it into new laptop - I have message at boot "Disk read error. Press Ctrl-Alt-Delete...", but the same operation with HDD goes just fine and system loading ok.
So the short summary: all the disks has the same SATA interface and all of them working ok on old laptop, but one of them not working on new laptop. And questions are:

*

*How is that possible?

*How to fix this on new laptop?

*Is that SSD problem or controller incompatibility?

*May be I'm stupid somewhere?

For now, I have to use stock HDD drive which turns new laptop into a pumpkin ((


text:
Q: Vue.js Update template from component method I want to update a components template when a certain method of the component is called. Just like the resolve function, or the Vue.compile render option, or the v-html binding option (but then with actually compiling the template).
How can i call the resolve function from the component method.
Is this possible and how should I do this with Vue.js?

A: You define what's to be updated in the component's data function's return object's variable like so. Data has to be a function if you are using a Component (eg. Vue.extend)
You then define a method and change this.whateverYouNamedYourVariable in the method, like so.
And then you call the method either in v-on or programmatically. Here's a link to v-on event binding aswell: Vue docs
And a quick example using webpack.
<template>
    {{me}}
    <button v-on:"changeMe">Click to change!</button>
</template>

<script>
 import 'vue' from 'vue';
 export default {
    name: 'VueEventBindDemo',
    data: function() {
        return { me: 'isMe'}
    },
    methods: {
        changeMe: function() {
           this.me = "isYou";
        }
    }
 }
</script>


text:
Q: How can someone calculate distance between Earth and Moon using a laser? I have a book stating:

When astronauts of the Apollo missions visited the moon, they placed a mirror on its surface, facing the earth. Then scientists on the earth sent a strong laser beam, which was reflected by the mirror on the moon and received back on the earth. The size of the reflected laser beam and the time taken for the round trip were measured. This allowed a very accurate determination of (a) the extremely small divergence of a laser beam and (b) the distance of the moon from the earth.

I am quite okay with (a), but (b) confuses me a lot, I am not able to understand, how:

*

*They directed the laser directly on the mirror (may be the mirror was a gaint)

*They kept the mirror perfectly adjusted and stationary (well, this one is probably easy)

*(Hardest one, I think) They were present at the location where laser returned

A: Two key facts provide an answer to your question.  The first is that we know the speed of light, so if we know how long it takes for a pulse of light to travel from a telescope on the Earth to a retroreflector on the Moon, then back to the telescope, we know how far the light traveled.
The second important fact is that the Moon's surface is not highly retroflective. If we shine a laser at the Moon and look for scattered light that returns to us, we receive practically zero light back.  The retroreflector placed on the Moon by astronauts is highly efficient at sending light back to its source, and allows us to receive enough light back at the telescope to actually detect it.


text:
Q: How Can I pass the value of select list to a form by url? I am trying to send a value of select list with the form URL with the following HTML markup.
<select class="form-select" name="field_with_contact[und]" id="edit-field-with-contact-und"><option value="_none">- None -</option><option value="26">Rawhi Pharmacy</option></select>

The form URL is http://www.example.com/node/add/deal.
How can I send the value 26 to the form?
Thank you

A: You can use the Prepopulate module which is thought for exactly this purpose.
As shown in the project page, a URL like http://example.com/node/add/blog?edit[title]=this%20is%20the%20title would pre-populate the title with this is the title.
The module can be used with every form, and it has an official release that is used (on August 6, 2017) from 5004 sites.
Before January 1, 2013, the usage of the module was the following.

As of August 18, 2017, the usage of the module for Drupal 6 decreased, since Drupal 6 is not officially supported anymore, but the total usage slightly increased thanks to its usage in Drupal 7 and Drupal 8 sites.

A: If you go to "www.mysite.com/node/add/deal/26" the following code will print The number passed in url was: 26
Here is the code:
function my_module_menu()
{
    $items = array();

    $items['node/add/deal/%'] = array(
        'title'           => 'Add deal',
        'page callback'   => 'drupal_get_form',
        'page arguments'  => array('node_add_deal_form', 3),
        'access callback' => array(TRUE),
        'type'            => MENU_CALLBACK,
    );

    return $items;
}

function node_add_deal_form($form, &$form_state, $number)
{
    $form = array();

    $form['number'] = array(
        '#markup' => '
The number passed in url was: '. $number. '
',
    );

    return $form;
}


text:
Q: Creating a ContextProvider for a Form Component in ReactJS I have created some context for a form component that I have created.  Right now, I have created a Provider for that context at the root of my app.  But I am wondering if this is the best way to do things.
There are many pages that do not have forms on them.  Why should I provide uneeded code on those pages?  Or is it not really that big a deal?
If it's better NOT to do it, then any ideas on how I can add the provider ONLY on those pages that use the form component?

A: What you can do is create a HOC with that Provider, and use that only in the components you want.
const withForm = Component => {
    return (
        <Provider>
            <Component />
        <Provider>
    )
}

// other file
export const MyComponentWithForm = withForm(MyComponent)

This example is very simplified, but it's only so you can understand how it should work (there is alot of missing pieces in this HOC).
Also notice that you can also do this for Consumer if you are using class components.


text:
Q: Android inflate view not honoring dynamically set width I'm trying to generate a bitmap to show in the notification. The layout is a bit complex, however, I need to set the width according to the screen size. In the XML, I have a LinearLayout in the root and I inflate the view with
  LinearLayout v = (LinearLayout) i inflater.inflate(R.layout.notification_expanded_detail, null, false);

This layout has quite a bunch of elements which I need to fill. And their width depends on the width of the layout itself and the width of the layout varies with phone. I set the width for the inflated layout with
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) available_width, LinearLayout.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(params);

However, when I try to generate a bitmap from this, it appears that the size set with the setLayoutParams is not affecting the child views of the inflated layout. There are many questions around i in SO, however, all of them deals with inflating a layout that already has a rootView and nothing worked for me. A couple of answers suggested that I call the measure() method on the view. However, after calling the measure method, the getMeasuredWidth returns a width lesser that what I had set with the setLayoutParams call.
Update
A little more context about the problem. I was trying to show a notification that had a placeholder ImageView which I would later fill in with a bitmap generated from a view inflated from an XML. The remote view layout is
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sliderViewBottom"
android:layout_width="match_parent"
android:layout_height="256dp"
android:background="@color/detail_page_blue"
android:clickable="true"
android:focusable="false"
android:orientation="vertical"
android:gravity="center"
android:padding="10dp"
>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@color/white"
        >

        <ImageView
            android:id="@+id/progressImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#D05757"
            android:gravity="center"
            android:paddingBottom="8dp"
            android:paddingTop="8dp"
            >

            <TextView
                android:id="@+id/overAllDelay"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Delayed by "
                android:textColor="@color/white"
                />

            <TextView
                android:id="@+id/overAllDelayVal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/overAllDelay"
                android:text="-"
                android:textColor="@color/white"
                />
        </RelativeLayout>

    </LinearLayout>

The layout that I was trying to inflate and generate a bitmap from to set in the progressImage was
<RelativeLayout
    android:id="@+id/swipe_page_track_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="10dp"
    android:paddingLeft="@dimen/swipe_layout_info_card_track_margin"
    android:paddingRight="@dimen/swipe_layout_info_card_track_margin"
    >

    <ImageView
        android:id="@+id/fromGreenCircle"
        android:layout_width="10dp"
        android:layout_height="10dp"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="1dp"
        android:src="@drawable/from_green_circle"/>

    <ImageView
        android:layout_width="10dp"
        android:layout_height="10dp"
        android:layout_alignParentRight="true"
        android:layout_marginTop="1dp"
        android:src="@drawable/station_end"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="4.5dp"
        android:background="@drawable/swipe_page_empty_track"
        />

    <ImageView
        android:id="@+id/fromGreenTrack"
        android:layout_width="105dp"
        android:layout_height="3dp"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="4.5dp"
        android:src="@drawable/from_green_track"
        />

    <ImageView
        android:id="@+id/trackNavigationIcon"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_marginLeft="100dp"
        android:src="@drawable/ic_track_detail_card_current_station_pointer"
        />

    <TextView
        android:id="@+id/currentStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/trackNavigationIcon"
        android:layout_marginTop="10dp"
        android:textColor="@color/black"
        />
</RelativeLayout>

I was trying to inflate this second layout with
  LinearLayout v = (LinearLayout) i inflater.inflate(R.layout.notification_expanded_detail, null, false);

And then was using
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) available_width, LinearLayout.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(params);

This available_width was computed dynamically. However, when I later tried to generate a Bitmap from this inflated view by using v.layout(), it kep t generating an image which was not honouring the width that I set.
Later, I came across this SO thread where I noticed that while inflating, instead of specifying null as the parentView, new LinearLayoutParams(contex) was specified. I tried that and now, the dynamically set width is being honoured.

A: I came across this SO thread where I noticed that while inflating, instead of specifying null as the parentView, new LinearLayoutParams(contex) was specified. I tried that and now, the dynamically set width is being honoured


text:
Q: RabbitMQ starts on a different port every time? I am running rabbitmq servers over Ec2. I am trying to create a cluster, and have the ports: 4369 and 25672 and 5672 open as specified in the rabbitmq docs : https://www.rabbitmq.com/clustering.html
Whenever I start my rabbitmq server:
rabbitmq-server -detached

The server starts on a different port. Output of epmd -names gives:
epmd: up and running on port 4369 with data:
name rabbit at port 50696

Where '50696' changes each time I stop the server and start it again. This is making it impossible for me to cluster my instances without allowing all ports inbound on my aws firewall rules.
Any ideas on what is going on?

A: Take a look at RABBITMQ_DIST_PORT here: https://www.rabbitmq.com/ec2.html

A: rabbitmq.config:
[
    {kernel,
    [
        {inet_dist_listen_min, 55555},
        {inet_dist_listen_max, 55560}
    ]}
].

epmd -names
epmd: up and running on port 4369 with data:
name rabbit at port 55555


text:
Q: Getting difference between value and its lag in Spark I have a SparkR DataFrame as shown below. I want to create a monthdiff column that is the months between dates, grouped by each name. How can I do this?
#Set up data frame
team <- data.frame(name = c("Thomas", "Thomas", "Thomas", "Thomas", "Bill", "Bill", "Bill"),
  dates = c('2017-01-05', '2017-02-23', '2017-03-16', '2017-04-08', '2017-06-08','2017-07-24','2017-09-05'))
#Create Spark DataFrame
team <- createDataFrame(team)
#Convert dates to date type
team <- withColumn(team, 'dates', cast(team$dates, 'date'))

Here's what I've tried so far, all resulting in errors:
team <- agg(groupBy(team, 'name'), monthdiff=c(NA, months_between(team$dates, lag(team$dates))))
team <- agg(groupBy(team, 'name'), monthdiff=months_between(team$dates, lag(team$dates)))
team <- agg(groupBy(team, 'name'), monthdiff=months_between(select(team, 'dates'), lag(select(team, 'dates'))))

Expected output:
name    | dates     | monthdiff
-------------------------------
Thomas  |2017-01-05 |  NA
Thomas  |2017-02-23 |  1
Thomas  |2017-03-16 |  1
Thomas  |2017-04-08 |  1
Bill    |2017-06-08 |  NA
Bill    |2017-07-24 |  1
Bill    |2017-09-05 |  2

A: Based on this post, I adapted the code for SparkR to get the answer.
#Create 'lagdates' variable with lag of dates
window <- orderBy(windowPartitionBy("name"), team$dates)
team <- withColumn(team, 'lagdates', over(lag(team$dates), window))

#Get months_between dates and lagdates
team <- withColumn(team, 'monthdiff', round(months_between(team$dates, team$lagdates)))

name  | dates      | lagdates  | monthdiff
------------------------------------------
Bill  | 2017-06-08 |null       | null
Bill  | 2017-07-24 |2017-06-08 |    2
Bill  | 2017-09-05 |2017-07-24 |    1
Thomas| 2017-01-05 |null       | null
Thomas| 2017-02-23 |2017-01-05 |    2
Thomas| 2017-03-16 |2017-02-23 |    1
Thomas| 2017-04-08 |2017-03-16 |    1


text:
Q: Explanation of p-value in ols_step_forward_p function of olsrr package Consider the following example:-(taken from the e.g. of R documentation)
model <- lm(y ~ ., data = surgical)
ols_step_forward_p(model)

The documentation says that it will be employing the Forward Stepwise method to select the final model. If I am not wrong, doesn't this forward selection is based on observing the p values of the following test statistic:-

where we are considering a model with K predictors all total. RSS denotes the residual sum of squares and the subscript p and K denote the RSS of a model with p and K predictors respectively.
If I do not give the command penter in ols_step_forward_p function what default p-value is chosen?

A: ols_step_forward_p has documentation here (also via ?olsrr::ols_step_forward_p if you have the package installed)
The second entry ("S3 method for default") says

ols_step_forward_p(model, penter = 0.3,
    progress = FALSE, details = FALSE, ...)

(emphasis added).
This means that the default value of penter is 0.3.
To see in more detail what's going on, you can look at the code for olsrr::ols_step_forward_p.default. Here's the relevant code export::
for (i in seq_len(len_p)) {
            predictors <- c(preds, all_pred[i])
            m <- lm(paste(response, "~", paste(predictors, collapse = " + ")),
                l)
            m_sum <- Anova(m)
            pvals[i] <- m_sum$`Pr(>F)`[ppos]
        }

So you can see that the p-value is based on the F-test from car::Anova. See ?car::Anova.lm for more details ...


text:
Q: Regarding an exercise of Hatcher (fundamental group of $\mathbb{R}^3$ with $n$ lines removed)
tl;dr I am not asking for a solution, that I already have. What do the generators for $\mathbb{R}^3 - \{n\text{ lines through the origin}\}$ look like explicitly, without making reference to any deformation retraction or homeomorphism?

Exercise 1.2.4 of Hatcher asks you to compute $\pi_1(\mathbb{R}^3 - X)$ where $X$ is $n$ lines through the origin. I have been able to solve it (it should be the free group on $2n - 1$ letters), and while I am comfortable with the argument (deformation retract to $S^2$ with $2n$ points removed, homeomorphism to $2n - 1$ points removes in $\mathbb{R}^2$, induction $+$ van Kampen), I originally wanted to do this directly without retracting the space, however I do not see how the generators should look like explicitly in this case.
For $n = 1$ this is not a problem; given a fixed based point any loop is only dependent on (up to homotopy) how many time it goes around the removed line, and is therefore the integers. For $n = 2$ things start getting weird; I believe there should be four generators, not three. Consider the following illustration:
here I assume that the two removed lines are the $x$ and $y$ axes. Wouldn't all four of these loops act as generators for the fundamental group of $\mathbb{R}^3$ minus these two axes removed? (If the illustration is unclear: each loop loops around the removed line once, not looping around any of the other removed lines. Hence for each line we have two loops, one for each side of the origin.) Of course, I do know this claim is incorrect (as I have proved it to be). I am asking for an explicit description of the generators of this space for $n = 2$, without making any changes to the space, i.e. no homeomorphisms, no deformation retractions. Given a basepoint on this exact space, what will the three generators look like?

A: The $n$ lines that you remove can be seen as $2n$ half lines starting from the origin. Choose any $2n-1$ of those. For each one take a loop from a fixed basepoint which winds once around that half line (and "only" that). The homotopy classes of these loops generate freely the fundamental group of your space.
Let $a_1,\dots,a_{2n-1}$ be the generators described above.
The homotopy class of a loop that winds once around the half line that you didn't choose (and around "only" that) is $a_{\rho(1)}^{k_1}\cdots a_{\rho(2n-1)}^{k_{2n-1}}$ for some $k_i \in \{1,-1\}$ and some permutation $\rho$ of $\{1,\dots,2n-1\}$.
You can see this more easily if you first apply a deformation retract to $S^2$.
EDIT:
Let's put orientation and labels to the loops of your example ($\mathbb{R}^3$ with the $x$ and $y$ axes removed):

Then $d \simeq abc$.


text:
Q: How to create a menu bar in vaadin 10 I am a beginner of vaadin 10 and I am going to create a menu bar. I am not sure what components to be used to make it exactly look like a sidebar and simple menu options vertically.
I can create this using buttons and navigations but not sure what the best way is.
P.S. I am a backend java developer, not a front-end guy, it's highly appreciable if you can explain it as simply as possible.

A: MenuBar component has been removed from v10 :-(
https://vaadin.com/docs/v10/flow/migration/5-components.html


text:
Q: How to store a private key in Github and VSTS Continuous Integration? I have a private API key that I am using in my public Github project. I would like to keep this key private. Currently, I am doing this using an Environment Variable.
The problem I'm running into is that this project is also integrated into VSTS Continuous Integration environment. So when my code runs there, the key is not available since it's only on my local machine.
I've tried using Azure Key Vault as recommended by Microsoft here. But that code didn't work for me. I downloaded the Nuget package that they recomended. However, when I tried to use this code the compiler had no idea what IWebHost or Startup is:
public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((ctx, builder) =>
        {
            var keyVaultEndpoint = GetKeyVaultEndpoint();
            if (!string.IsNullOrEmpty(keyVaultEndpoint))
            {
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                var keyVaultClient = new KeyVaultClient(
                    new KeyVaultClient.AuthenticationCallback(
                        azureServiceTokenProvider.KeyVaultTokenCallback));
                        builder.AddAzureKeyVault(
                        keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
                    }
                })
                .UseStartup<Startup>()
                .Build();

Does anyone have an idea of how to do this?

A: You can use Azure Key Vault task to download the private keys to the agent machine firstly, and then use key by related variable in VSTS build.
Assume there has an priavte key mykey in Azure key vault, after Azure Key Vault task, you can use the variable $(mykey) to get the key value.


text:
Q: How to split a polygon and fill areas along skew values? I know how to split and fill areas of a polygon along a horizontal line, if the values are quite simple.
x <- 9:15
y1 <- c(5, 6, 5, 4, 5, 6, 5)

plot(x, y1, type="l")
abline(h=5, col="red", lty=2)

polygon(x[c(1:3, 5:7)], y1[c(1:3, 5:7)], col="green")
polygon(x[3:5], y1[3:5], col="red")

y2 <- c(5, 6, 4, 7, 5, 6, 5)

plot(x, y2, type="l")
abline(h=5, col="red", lty=2)

But how to get the result if the values are a bit more skew?
Expected output (photoshopped):

A: As pointed out by @Henrik in comments we can interpolate the missing points.
If the data is centered around another value than zero – as in my case – we need to adapt the method a little.
x <- 9:15
y2 <- c(5, 6, 4, 7, 5, 6, 5)

zp <- 5  # zero point
d <- data.frame(x, y=y2 - zp)              # scale at zero point

# kohske's method
new_d <- do.call(rbind,
                 sapply(1:(nrow(d) - 1), function(i) {
                   f <- lm(x ~ y, d[i:(i + 1), ])
                   if (f$qr$rank < 2) return(NULL)
                   r <- predict(f, newdata=data.frame(y=0))
                   if(d[i, ]$x < r & r < d[i + 1, ]$x)
                     return(data.frame(x=r, y=0))
                   else return(NULL)
                 })
)

d2 <- rbind(d, new_d)
d2 <- transform(d2, y=y + zp)              # descale
d2 <- unique(round(d2[order(d2$x), ], 4))  # get rid of duplicates

# plot
plot(d2, type="l")
abline(h=5, col="red", lty=2)

polygon(d2$x[c(1:3, 5:9)], d2$y[c(1:3, 5:9)], col="green")
polygon(d2$x[3:5], d2$y[3:5], col="red")

Result


text:
Q: Scala - create a generic type taking another generic type I'm refactoring a Java interface which defines all the concrete types inside the interface (the types that the methods are receiving and returning). I don't want to enforce those type constraints and wish to keep the interface generic, the input and output value types should themselves be generic. Some of the methods in the interface are recursive in the sense that they return generic type defined inside a different generic type defining the trait itself. I need to reference the generic types inside the trait.
For instance:
trait Product[ID,GROUP] {
  def getProductId : ID // the product ID could be an Int,String, or some other type
  def getGroup : GROUP
}

// define a generic reader for the generic products
trait Reader[Key,Prod <: Product[What should I write here?] {
  def getProduct(key: Key) : Product
  def getProductsInGroup(group : Prod.getGroupType) : Seq[Prod] << How do I reference the Prod.GROUP type parameter?
}

A: You need another type parameter:
 trait Reader[Key, Group, Prod <: Product[Key, Group]] {
     def getProduct(key: Key): Prod
     def getProductIdsInGroup(group: Group): Seq[Prod]
 }

For the record, I am not sure what it is you don't like about inner type definitions as an alternative BTW. Don't know what "constraints" you are talking about.
 trait Product {
   type Id
   type Group
 }

 trait Reader[Prod <: Product] {
    def getProduct(key: Prod#Id)
    def getProductIdsInGroup(group: Prod#Group): Seq[Prod]
 }


text:
Q: why stll need to use Serializable attribute when the type already implements ISerializable? I know [Serializable] marks a type to be serializable and ISerializable makes you can do custom serialization/deserialization by implementing GetObjectData, so you can see code like this below:
[Serializable]
public class MyType : ISerializable {
   ...
   void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { ... }
}

My question is, when a type implements ISerializable, it implicitly indicates this type is "serializable", because the logic is, if you can have control over doing a thing as you wish, then you are "capable" to do this thing, so I think it isn't it better to omit [Serializable] when a type implements ISerializable ?

A: Yes omit it!
With ISerializable you can define custom sterilizing behavior through the GetObjectData  override.
Using the attribute is better for single properties on an fields.
Here's a more detailed example of each use this example of a custom serialization here on StackOverflow


text:
Q: HTMLPurifier removes target="_blank" I'm using HTMLPurifier and even thou I have :
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');

it removes all 'target' attribues from the links.
Any idea why is it doing it?

A: The list of allowed frame targets is not enabled by default. You have to enable it manually.

A: In a Yii2 application, inside of a DetailView, I configured HtmlPurifier as follows:
[
    'label' => 'Document PDF',
    'format'=> 'raw',
    'value' => HtmlPurifier::process(DocumentFunctions::viewDocumentPdfInView($model->document_id), [
    'Attr.AllowedFrameTargets' => ['_blank'],
    ]),
],

Here is a simpler way I found:
[
    'label' => 'Document PDF',
    'format'=> ['html', 'config' => ['Attr.AllowedFrameTargets' => ['_blank']]],
    'value' => DocumentFunctions::viewDocumentPdfInView($model->document_id),
]


text:
Q: Crew launched to comet where contact with organism starts their metamorphosis Contemporary time period.  At the start, the crew is being launched (by NASA?) to rendezvous with a comet.  An X15 is launched at the same time to try to stop them, but fails.  Mission makes it to comet but find organisms cause some to metamorphosis.  Earth politics start a disaster.  Seem to remember the cover looking like an Apollo capsule

A: Based on the X-15 this is probably a blurry memory of Stephen Baxter's Titan.
In this incredibly dumb book, the USAF hates the shuttle program so much, that when NASA launches a shuttle mission to Saturn (don't ask), they get an X-15 out of the museum and try to use it to shoot down the shuttle during its launch.
I threw the book against the wall after this episode, but the plot summary in the Wikipedia article does mention global disaster, Earth politics, and the crew being transformed "through some unspecified alien process".


text:
Q: does a zero fill format "heal" a drive? I have an old Maxtor hard disk with problems on its blocks, I've run the seatools for dos tool and it' ve found several back blocks.
I launched a zero fill format from seatools, then redo a short test and this time, the hdd passed it, my question is: is the hard drive reliable now ? I don't mean to save very important files on it, but I wonder if I run the risk to power on the pc in a week and see the hard drive is not recognized from BIOS.

A: Those particular blocks were marked as bad by the drive when it couldn't write zeroes to them.  So, in that sense, yes, that problem is resolved and the drive won't try to write to those blocks again.
However, odds are there may be more bad blocks in your future.  It's safe to use the drive for non-critical stuff, but understand that you may run into the same problem again.

A: If it has had the kind of problems you describe, I wouldn't use it for anything at all critical.

A: Sometimes, I have repaired bad sectors using the GRC Spinrite program....then I get as much information off as quickly as possible.  In one case, the disk was actually ok for a couple of years.


text:
Q: How do I construct ajax request handling drop down change event in MVC 4 ASP.NET I have a bit of a scenario here using ASP.NET MVC 4. I have 2 dropdown lists whose contents are loaded via ViewBags within a controller. However, I want one to be loaded based on what is selected on another one above it (very simple when it comes to ASP.NET :D). Now I'm very new to MVC and was told I have to use ajax on different forums. The problem is that none of the snippets I customized for my use worked. Here is the controller code that should handle the Ajax request and the ajax script in the cshtml view that the drop downs are on:
First the View code:

        @Html.LabelFor(model => model.UserLevel)

        @Html.DropDownListFor(model => model.UserLevel, (SelectList)ViewBag.ListOfUserLevels)
        @Html.ValidationMessageFor(model => model.UserLevel)

        @Html.LabelFor(model => model.UserGrade)

    @{
        if (ViewBag.ListOfUserGrades == null)
        {
            ViewBag.ListOfUserGrades = new SelectList(new List<string>() { "", ""});
        }
    }

        @Html.DropDownListFor(model => model.UserGrade, (SelectList)ViewBag.ListOfUserGrades)
        @Html.ValidationMessageFor(model => model.UserGrade)

Now for the Controller Code that handles the ajax request.
    [HttpGet]
    public JsonResult SelectedIndexChanged(string value)
    {
        UserBL bl = new UserBL();
        var grades = new UserGradeBL();
        if (grades.RetrieveAll().Count == 0)
        {
            grades.CreateDefaults();
        }
        var source = grades.RetrieveAll().Where(g => g.UserLevel.Trim() == value.Trim());
        var list = new SelectList(source, "Grade", "Grade");
        ViewBag.ListOfUserGrades = list;

        //List<string> gradelist = new List<string>();
        List<myObj> gradelist = new List<myObj>();
        foreach (var item in source)
            gradelist.Add(new myObj() { label = item.Grade, value = item.Grade });

        var levels = new UserLevelBL();
        if (levels.RetrieveAll().Count == 0)
        {
            levels.CreateDefaults();
        }
        list = new SelectList(levels.RetrieveAll(), "Level", "Level");
        ViewBag.ListOfUserLevels = list;

        var types = new  UserTypeBL();
        if (types.RetrieveAll().Count == 0)
        {
            types.CreateDefaults();
        }
        list = new SelectList(types.RetrieveAll(), "Type", "Type");
        ViewBag.ListOfUserTypes = list;

        return Json(new { grade = gradelist  }, JsonRequestBehavior.AllowGet);
        //return View();
    }

By the way it is inside a controller called HomeController. I have tried putting the script in a separate file in Scripts folder that comes with the MVC project and registerd it in App_Start folder file bundleConfig.cs as follows:
bundles.Add(new ScriptBundle("~/bundles/dropdown").Include(
                    "~/Scripts/dropdown.js"));

And then I called the script in this view page at the bottom like this
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/dropdown")

all to no avail. By the way, I am using VS2012 on Win 8. I hope I supplied all the necessary information. Thanks in advance for you help,

A: Finally, I found the answer. Funny enough it was very simple. Here is the script first:
 $(document).ready(function () {
            $("#UserLevel").change(function () {
                  var model = $('#UserGrade');
                    model.empty();

                    $.getJSON('/Home/IndexChanged', { value:  $("#UserLevel").val() }, function(data) {
                        $(data.grade).each(function() {
                            $("<option value='" + this.value + "'>" + this.label + "</option>").appendTo(model);
                    });

                })
                .error(function () {
                    alert("replace operation failed");
                });
                return false;
            });
        });

This is the action in Home controller
   [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult IndexChanged(string value)
    {

        UserBL bl = new UserBL();
        var grades = new UserGradeBL();
        if (grades.RetrieveAll().Count == 0)
        {
            grades.CreateDefaults();
        }
        var source = grades.RetrieveAll().Where(g => g.UserLevel.Trim() == value.Trim());
        var list = new SelectList(source, "Grade", "Grade");
        ViewBag.ListOfUserGrades = list;

        //List<string> gradelist = new List<string>();
        List<myObj> gradelist = new List<myObj>();
        foreach (var item in source)
            gradelist.Add(new myObj() { label = item.Grade, value = item.Grade });

        ...
        return Json(new { grade = gradelist }, JsonRequestBehavior.AllowGet);
       //return View();
    }

And that's it! Here is my source of info:
http://www.schwammysays.net/cascading-select-lists-with-mvc-and-jquery/


text:
Q: Порционное чтение большого Xml файла с известной структурой Есть файл xml-файл вида:
<?xml version="1.0" encoding="utf-8" ?>
<config>
  <file>
    <name>test.log</name>
    <sourcePath>C:/</sourcePath>
    <targetPath>C:/copy/</targetPath>
  </file>
  <file>
    <name>Win8.iso</name>
    <sourcePath>C:/</sourcePath>
    <targetPath>C:/copy/</targetPath>
  </file>
  <file>
    <name>TemplateNew.xlsx</name>
    <sourcePath>C:/</sourcePath>
    <targetPath>C:/copy/</targetPath>
  </file>
  ...
  ...
  ...
</config>

под тегами скрыто: имя файла, исходный путь к файлу и путь, по которому данный файл требуется скопировать.
Решил парсить файл в список структур:
var document = new XmlDocument();
        document.Load(configPath);

        XmlNode root = document.DocumentElement;

        string name = "";
        string source = "";
        string target = "";
        int iCount = 0;

        foreach (XmlNode nodes in root.ChildNodes)
        {
            foreach (XmlNode tagname in nodes.ChildNodes)
            {
                if (tagname.Name == "name")
                {
                    name = tagname.InnerText;
                }
                if (tagname.Name == "sourcePath")
                {
                    source = tagname.InnerText;
                }
                if (tagname.Name == "targetPath")
                {
                    target = tagname.InnerText;
                }
            }
            collect.Added(name, source, target);
            iCount++;
        }

        Console.WriteLine("заполнено {0} элементов", iCount);

Но вот загвоздка, если предположить что файл будет размером, близким к бесконечности, то список превысит допустимые размеры оперативной памяти и я словлю исключение о её чрезмерном размере.
Каким образом можно организовать порционное чтение данных, скажем, по 100 записей?
Подходит ли данный способ чтения файла под эту задачу?

A: Вариант с ленивым чтением, xml не будет загружаться в память полностью, как в вашем случае, т.е. можно сделать поточную обработку, можно читать и пачками, если написать Extension, который читает IEnumerable<> и разбивает его на порции заданного размера IEnumerable>
public class FileModel
{
    public string Name { get; set;}
    public string SourcePath { get; set; }
    public string TargetPath { get; set; }
}

public static IEnumerable<FileModel> ReadXml(string path)
{
    using (var fileStream = File.OpenRead(path))
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    using (var reader = XmlReader.Create(streamReader))
    {
        while (reader.Read())
        {
            if (reader.NodeType != XmlNodeType.Element || reader.Name != "file")
            {
                continue;
            }

            XElement el = XElement.ReadFrom(reader) as XElement;
            var fileModel = new FileModel
            {
                Name = (string)el.Element("name"),
                SourcePath = (string)el.Element("sourcePath"),
                TargetPath = (string)el.Element("targetPath"),
            };

            yield return fileModel;
        }
    }
}

A: Нужно использовать потоковый XmlReader. Загружать сразу все данные в коллекцию нельзя, т. к. по условию файл потенциально очень большой. Будем читать по 100 записей.
Создадим класс для данных:
class File
{
    public string Name { get; set; }
    public string SourcePath { get; set; }
    public string TargetPath { get; set; }
}

Метод, возвращающий список с указанным количеством записей (или меньше в самом конце):
IEnumerable<List<File>> ReadFiles()
{
    using (var reader = XmlReader.Create(fileName))
    {
        var files = new List<File>();

        while (reader.ReadToFollowing("name"))
        {
            var file = new File();
            file.Name = reader.ReadElementContentAsString();

            reader.MoveToContent();
            file.SourcePath = reader.ReadElementContentAsString();

            reader.MoveToContent();
            file.TargetPath = reader.ReadElementContentAsString();

            files.Add(file);

            if (files.Count % 100 == 0)
            {
                yield return files;
                files = new List<File>();
            }
        }

        if (files.Count > 0)
            yield return files;
    }
}

Использование этого метода:
foreach (var files in ReadFiles())
{
    // работаем с коллекцией files

    foreach(var file in files)
    {
        // работаем с одним экземпляром file
    }
}


text:
Q: How to Trigger event to change value in Input Box? I am attempting to learn HTML and Javascript, and with this, I am working on building a simple calculator device, where all of the numbers and operators are buttons that are clicked, and the results are displayed in an input box. However I have had issues with, when clicking on the buttons, having the events trigger to display the selected numbers value in the box.
Here is my HTML and JS:

var numString = "";

$('.number').click(function() {
  numString += $(this).val().toString;
  $('input[name=display]').val(numString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="display" name="display" disabled></input>
<button id="button1" class="number" value="1">1</button>

A: Try with the below code . it should be .toString() instead of .toString

var numString = "";
$('.number').click(function() {
     numString += $(this).val().toString();
     $('input[name=display]').val(numString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="display" name="display" disabled></input>

<button id="button1" class="number" value="1">1</button>

A: You have a type in $(this).val().toString
toString is a function, I believe the intention was to call it like this $(this).val().toString()
After fixing toString, your code would produce 1 -> 11 -> 111...


text:
Q: divs in PHP, not working I'm trying to use my css in my php script, this is what I tried:
    ....
    else
    {
     echo"

    <link href='styles.css' rel='stylesheet' type='text/css' />

Wrong Username or Bad Password.

Click Here to try again.

   ";
    }
   ?>

its my else statement of my login script, when I take away the divs the html shows fine, but leaving them in causes an error.
what am I doing wrong? do I put my css on the page??
thanks

A: yau'll have to correct your quotation-signs as you cant use " insite of "" without escaping it. do one of these:
echo "this is a \"test\" ... ";
echo "this is a 'test' ... ";
echo 'this is a "test" ... ';
echo 'this is a \'test\' ... ';

A: It's PHP, dude. No need to use echo at all
<?
else
{
?>

    <link href='styles.css' rel='stylesheet' type='text/css' />

Wrong Username or Bad Password.

Click Here to try again.

<? } ?>

A: It's bad practise to do these kinds of echos full of HTML (let's let it slip that even the below isn't MVC--that's another topic entirely). You should come out of PHP and then echo your HTML like so:
<?php function echo_menu() { ?>

    Home

<?php }

A:

change to

A: else
    {
     echo '

             <link href="styles.css" rel="stylesheet" type="text/css" />

                 ....
          ';
    }
   ?>

But I would suggest the answer of @Col. Shrapnel.

A: The syntax highlighting in your question gives it away, there's a conflict with the double quotes. The solution? echo with single quotes!
echo '

    <link href="styles.css" rel="stylesheet" type="text/css" />

Wrong Username or Bad Password.

Click Here to try again.

   ';

You could also use the heredoc syntax:
echo <<<HTMLBLOCK
Double quotes
..and single quotes!
HTMLBLOCK;

A: Use quotation marks consistently. Now you use single quotes with link but double quotes with all the other tags. Change your link tag to
<link href="styles.css" rel="stylesheet" type="text/css" />

Then you can use single quotes around the whole string like:
....
else
{
 echo '

...

';
}

A: Old fun method
echo <<< OUT

<link href="styles.css" rel="stylesheet" type="text/css" />
...
OUT;

everyone forgot it, right? :)

A: You already got all the good answers. But for completeness: Another option is to keep lengthy HTML snippets in separate files. Then just do this instead of the echo:
else
{
  include("template/head+div+block.html");
}

If you have lots of html output like this, you will thank yourself later for making it manageable.

A: Besides using another type of quotation marks, escaping and so on, I would highly recommend to separate your concerns: Why not using a html-file (or a template)?

A: escape double quotes in div attributes

like this

A: You are having quotes in there that end your echoed string.
Either escape them with a backslash, or use one single quotes to quote the string and double quotes in it, or vice versa.
However, if you do not use any PHP variables or code in the block, you could also enter non-PHP mode by using ?> before the HTML and reenter PHP mode afterwards with <?php.
This has the benefit that many editors can syntax-highlight both PHP and HTML properly.


text:
Q: SignalR in Layout and partial page I want to use a SignalR hub in a layout and in a partial page. Here it is described to use hub.start and done functions.
So I have two script blocks in my html page where i want to use SignalR:
<script>
    $(document).ready(function () {
        window.hubReady = $.connection.hub.start();
        window.hubReady.done(function () {
            ...
        });
</script>

<script>
    $(document).ready(function(e) {
        window.hubReady.done(function() {
            ...
        });
    });
</script>

In the second script block it says that windows.hubReady.done can't be executed because it's undefined.
EDIT: block 2 is executed before block 1. But why?

A: My guess is that the second callback is executed before the first, and if that's the case then window.hubReady is null since it's the first callback that initializes window.hubReady.
I would suggest that you don't create a global reference to your hub and instead reference it directly, ie:
<script>
    $(document).ready(function(e) {
        $.connection.hub.connected(function() {
            ...
        });
    });
</script>

(If this doesn't work then I suspect your hub named "hub" isn't defined on the server, but that's a different issue)

A: i solved the problem by not calling $(document).ready(function(e) but  $(window).load(function() in my partial html.    $(window).load(function() is called second then.


text:
Q: typedef stuct problem in C (illegal use of this type as an expression)
Possible Duplicate:
typedef stuct problem in C

Hello there
I am facing I have defined I a structure in a C header file:
typedef struct iRecActive{

    char iRecSID[32];
    unsigned char RecStatus;
    int curSel;

}iRecAcitve_t;

but when I use the same structure in another file, the compiler gives some error:
error C2275: 'iRecActive_t' : illegal use of this type as an expression
        d:\project\project original\mirec2pc v1.0\httpapp\httpapplication.h(15) : see declaration of 'iRecActive_t'
I would be obliged if anyone could help me out
Regards
Umair

A: Well, you could check you spelling, both in the question and in the code. You seem to have declared it as iRecAcitve_t but use iRecActive_t

A: It means that you've used the typename where the compiler expects...something else.
For example:
iRecActive_t *thing = iRecActive_t; // compiler expects new iRecActive_t()

if (iRecActive_t) {} // compiler expects an expression

As others have said, you need to post the line it's complaining about (line 15 of httpapplication.h)
Edit
iRecActive_t iRecActiveObj[4]; appears to be legal, in which case it's probably the line before that's got the compiler confused. For example:
if (thingOne ==                     // oops
    iRecActive_t iRecActiveObj[4];


text:
Q: reading data from socket - no performance I am creating an android service which is always running and listening messages from socket. But it doesn't work with good performance and i am looking for some nio alternative or tutorial.
What is the best way for listening a socket for all time ?
Does AndroidAsync support standart sockets ? https://github.com/koush/AndroidAsync
Is there anyone used Apache Mina ? I am having character problem with Mina. http://mina.apache.org/
Or how can i do this job with good performance using standart sockets
Waiting for your experiences.
Thanks

A: The normal way to get decent performance from a socket (for int read() and write(int)) is to use a buffered stream / reader / writer.  That reduces the number of system calls and makes byte or character at a time I/O much faster.
I don't expect that using NIO will make a significant difference.  If the problem is not buffering, then (IMO) it is probably a network bandwidth and/or latency issue.  If that is the case, there is little that you can do in Java that would make much difference.

A: I have some convenience methods for writing strings with java.nio:
private static Charset charset;
static
{
    charset = Charset.forName("UTF-8");
}

public static void writeString(SocketChannel sc, String string) throws IOException {
    CharBuffer c = CharBuffer.wrap(string);
    ByteBuffer b = charset.encode(c);
    b.compact();
    b.flip();
    sc.write(b);
}

public static String readString(SocketChannel sc) throws IOException {
    ByteBuffer bbuf = ByteBuffer.allocate(8096);
    sc.read(bbuf);
    bbuf.flip();
    CharBuffer cbuf = charset.decode(bbuf);
    return cbuf.toString();
}

All you need to do is establish your SocketChannel connections and you can use these all you want. java.nio is really not that difficult once you get used to it :)


text:
Q: How to update attribute frontend labels programmatically? I have the code:
 $attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
        ->get(\Magento\Eav\Model\Attribute::class)->load($id);

And I have to create/update frontend labels of $attributeModel for another stores (French & German)
Or maybe I should use another methods?

A: Try this code, it will change  default label

$attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
      ->get(\Magento\Eav\Model\Attribute::class)->load(140);

  $attributeModel->setData('frontend_label',{Your_value});
  $attributeModel->save();

For  store wise label set
$currentdata= $attributeModel->getStoreLabels();
$currentdata[{StoreID}] = {New Label for store};
$attributeModel->setData('store_labels',$currentdata);
$attributeModel->save();

A: I've found the solution:
  $attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
    ->get(\Magento\Eav\Model\Attribute::class)
    ->load($id);
  $storeLabels = $attributeModel->getStoreLabels();
  $storeLabels[$storeId] = $labelTitle;
  $attributeModel->setStoreLabels($storeLabels);

  \Magento\Framework\App\ObjectManager::getInstance()
     ->get($attributeModel->getResourceName())
     ->save($attributeModel);

A: On Magento 2.4.2 this works:
$attribute = $this->attributeFactory->create()->loadByCode('catalog_product', $attributeCode);
$storeLabels = [
    0 => $attribute->getDefaultFrontendLabel(),
    1 => 'Updated name on store PL',
    2 => 'Updated name on store DE'
];

$attribute->setData('frontend_label', $storeLabels);
$this->productAttributeRepository->save($attribute);

Check _beforeSave method on vendor/magento/module-eav/Model/ResourceModel/Entity/Attribute.php
     * Validate attribute data before save
     *
     * @param EntityAttribute|AbstractModel $object
     * @return $this
     * @throws LocalizedException
     */
    protected function _beforeSave(AbstractModel $object)
    {
        $frontendLabel = $object->getFrontendLabel();
        if (is_array($frontendLabel)) {
            $this->checkDefaultFrontendLabelExists($frontendLabel, $frontendLabel);
            $object->setFrontendLabel($frontendLabel[0])->setStoreLabels($frontendLabel);
        } else {
            $this->setStoreLabels($object, $frontendLabel);
        }
        $attribute->setData('frontend_label', $storeLabels);
        $this->productAttributeRepository->save($attribute);


text:
Q: Why do lambda and pi go together? In measure theory, we have "lambda systems" and "pi systems".  Pearl's message passing algorithm has "lambda messages" and "pi messages".  Is there a reason that lambda and pi go together?

A: The measure theory ideas of $\pi$-system and $\lambda$-system were introduced by Dynkin in his book Die Grundlagen der Theorie der Markoffschen Prozesse (1961 German translation of 1959 Russian original); a note at the end of the book mentions they are new, but doesn't explain why they are so called.  My guess has been that $\pi$ is for "product" and $\lambda$ is for "limit," or some Russian cognates thereof; I'm not sure there's any connection between the letters themselves.  Although Professor Dynkin has recently retired, he still has an office here at Cornell; if I see him and I think of it, I may ask him about it.
Unfortunately I don't know anything about message passing, so I can't say whether Pearl's terminology is related or a coincidence.


text:
Q: Edit pdf document tool? Form will not render without Adobe I would like to download the pdf application form on this page.
When I download and open with document viewer app, I get this message when I open the doc:

I went to the Ubuntu software center and typed 'pdf' in the search box. There are several results:

Before I try some trial and error with those apps, is there an app for Ubuntu (18.04) that anyone knows of that could render this document?

A: Wow, that is super scummy of your council to force citizens into using Adobe.
You can try using suggestions provided here
Alternatively, you can install an older version of adbobe reader. I was able to install it with these 3 simple steps :
sudo apt install gdebi-core libxml2:i386 libcanberra-gtk-module:i386 gtk2-engines-murrine:i386 libatk-adaptor:i386
wget ftp://ftp.adobe.com/pub/adobe/reader/unix/9.x/9.5.5/enu/AdbeRdr9.5.5-1_i386linux_enu.deb
sudo dpkg -i  AdbeRdr9.5.5-1_i386linux_enu.deb
For some wierd reason the installation puts the executables under /opt/Adobe/Reader9/bin  and not in the common locations like /usr/bin /usr/local/bin. So, you will need to run acroread from /opt/Adobe/Reader9/bin .

A: Try Foxit Reader, there is a Linux version available. I have seen Foxit Reader (although on Windows) properly display files which even Adobe Reader can't handle correctly... :)

A: MuPDF reads those council PDF's none of the others do, I tried.


text:
Q: ¿Como hago esta petición con cURL en Php? Estoy implementando un servicio de pagos en mi web, y uno de los ultimos es hacer una peticion http con curl, pero no entiendo del todo como hacerlo.
La documentación dice que la petición debe tener la siguiente forma:
https://sandbox.affirm.com/api/v2/charges
     -X POST
     -u "<public_api_key>:<private_api_key>"
     -H "Content-Type: application/json"
     -d '{"checkout_token": "<checkout_token>","order_id": "JKLM4321"}'

La forma en que tengo que llevar a cabo esto con curl, seria la siguiente:
// Iniciar curl
$curl = curl_init();
$headers[]  = 'Content-Type: application/json';
// Agregar las opciones y datos
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://sandbox.affirm.com/api/v2/charges',
    CURLOPT_POST => 1,
    CURLOPT_HEADER => $headers,
    CURLOPT_POSTFIELDS => [
        checkout_token => 'value',
        order_id => 'value2'
    ]
]);
// Enviar la petición y obtener la respuesta
$resp = curl_exec($curl);
// Cerrar la peticion
curl_close($curl);

Pero, como se observa, no tengo idea de como incluir las llaves publicas y privadas (que ya tengo, eso NO es el problema) en la petición con curl, y tampoco se que significa ese "-u" que describen en la documentación. ¿Alguna idea?

A: La u por la que preguntas, corresponde a la opción CURLOPT_USERPWD de cURL, como podrás verificar en el ejemplo de código más abajo.
En la página de la API tienes un ejemplo de código PHP usando cURL:
<?
php $checkout_token = $_REQUEST['checkout_token'];

//These are sandbox credentials
// $public_key = "ARQBLCL7NAMBTZ7F";                  //descomentar y poner tus credenciales
// $private_key = "RkHBmVSP5ayC2rCUujwhArpGWPxpuTtv"; //descomentar y poner tus credenciales
//This is the sandbox API URL
$url = "https://sandbox.affirm.com/api/v2/charges/";

$data = array("checkout_token" => $checkout_token);
$json = json_encode($data);
$header = array('Content-Type: application/json','Content-Length: ' . strlen($json));

$keypair = $public_key . ":" . $private_key;

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, $keypair);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

curl_close($curl);

http_response_code($status);
echo $response;
?>

Sólo tienes que descomentar y cambiar esto por tus credenciales reales y debería funcionar:
// $public_key = "ARQBLCL7NAMBTZ7F";
// $private_key = "RkHBmVSP5ayC2rCUujwhArpGWPxpuTtv";


text:
Q: Get data from API using jquery I really need your help, i cant get all data from this API: http://datahub.virk.dk/api/2/rest/package/smiley-kontrolrapporter
this is my code

please help me. thank you.

A: The url is empty in that link. You most likely mean the url in the resources array items. But since it is an array you need to iterate or target the specific index you want. The same goes for the description. It is not part of the resources, it is part of each item in the resources.
Something like


text:
Q: Is there a small classic ASP server like ASP.NET Development server that comes with Visual Studio? I would like to hear if there is a small classic ASP server, similar to the ASP.NET Development server that comes with Visual Studio?
We are a small group that supports a legacy (classic) ASP site, and would therefore like to have a small server that easily can be executed on a Windows XP machine. Currently we're stuck with IIS 5.1 on our development machines (and because we're running XP Pro, we cannot update to IIS 6 or 7).
I've tried installing the Cassini web server, but that doesn't seem to work with classic ASP either.

A: You're not going to get anything extra from ASP by running on IIS 6 or 7.  Are you having any specific issues with being stuck on IIS 5.1?

A: The short answer is No, there is no small web server that runs classic ASP. There are many alternatives, as mentioned here, such as IIS or Apache plug-ins, but none that has a similar small footprint like the ASP.NET Development Server that comes with Visual Studio and that supports debugging.

A: Have you tried Baby Web Server? - http://www.pablosoftwaresolutions.com/html/baby_web_server.html

A: There is a small footprint web server that runs Classic ASP.
Its called Abyss Web server. Abyss Web server is produced by Aprelium software and can be downloaded free of charge. Abyss Web server can be configured to run with ASP.net OR Classic ASP.
The Server can be configured to run ASP.net without any addition downloads.
To run Classic ASP on the server a program called ActiveHTML written by Selisoft must be downloaded and configured to allow Classic ASP to run on the Abyss web server. Active HTML is on a 45 day free trial and if you like it the purchase price is currently around 30 to 40 euros depending  on whether you need a client or server version.
Hope this helps.
Anthony

A: Abyss web server http://www.aprelium.com/ supports classic ASP (also ASP.Net, Ruby, and PHP) with a 3rd party extension that cost $$$.  But at one point there was a free version of the third party component, you MIGHT be able to find a copy of that still floating around.  Not sure about debugging.

A: Baby ASP Web Server can take care of things for you, PLUS you don't have to install it, so it doesn't plop all sorts of crazy settings into your registry.
Get it here

A: Your only real choice is to either run Windows server or Vista in order to get the latest version of IIS.
Cassini doesn't support classic asp.

A: According to this post it is not possible to run ASP on Cassini. A couple of google searches later I have still not been able to find any other alternatives either.
What functionality is it that you're after? If it is the quick-and-easy running features of VS, you can quite easily make the IDE debug on IIS (although ASP cannot technically be "debugged" - what you really do is just run it with the Ctrl+F5 command).

A: Here is a web site that allows you to run classic ASP pages from any web server (including IIS and Apache), but it costs money:
http://www.selisoft.com/en/ahtml/index.phtml


text:
Q: Cannot create index for new Firestore query feature "array-contains" I am using the new Firestore query feature
firebase.firestore().collection("articles").where("tags", "array-contains", tag)

to query all the article with specific tags.
The query works fine but the result is not sorted.
I understand how database indexes work and use them with other string fields before but not yet with array type.
When I do the query
firebase.firestore().collection("articles").orderBy("publishTime", "desc").where("tags", "array-contains", tag)

It prompts a link to create index. But that link does not work.
Is this because the new feature is still under development or is there any special step for "array-contains" query type?

A: This is now resolved by create the index field under ARRAY type


text:
Q: I am currently learning Python on codeacademy and I cant figure out what is wrong with this code I'm currently learning python on codeacademy, I'm trying to do the following in the last function of this code:

*

*Define a function called get_class_average that has one argument students.

*You can expect students to be a list containing your three students.
First, make an empty list called results.

*For each student item in the class list, calculate get_average(student) and then call results.append() with that result.

*Finally, return the result of calling average() with results.
But I keep getting this error anytime i try to run the code.

"Oops, try again. get_class_average([alice]) returned 80.55 instead of 91.15 as expected"

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    return 0.1 * homework + 0.3 * quizzes + 0.6 * tests

def get_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def get_class_average(students):
    students = [lloyd, alice, tyler]
    results = []
    for student in students:
        results.append(get_average(student))
        return average(results)
        print get_class_average(students)
        print get_letter_grade(get_class_average)

A: First: after return "F" you have a very inconsistent indentation. Move everything one tab left except for the first line (student =...)
Second: in the first line of get_class_average you erase students passed to function and write a new array. Either initialize students outside and pass them to function, or pass nothing and construct the array inside.
First is better.