text:
Q: CSS Set something to align differently depending on screen resolution Here is the website i am developing...
http://camerabeanbags.co.uk/test/
This is responsive so if you take the web browser window and change the width you can see the website alter. If you look at the 'Your Cart' button on the top right of the green bar you can see it is aligned on the right. If you change the width of the web browser window it aligns to the left.
How can i change the width the web browser has to be before it aligns this to the left as i want it to do it only when there is no space for them to be next to each other. As on an iPad it aligns to the left but i want it to align it to the right. I have tried with the CSS @media but can't figure it out for this certain element.
Please can you help me with the CSS i need so it only aligns to the left at a certain screen width.
Thanks,
Harvey

A: .kad-topbar-left{
    float: right !important;
}

This way it doesn't take full width on smaller window widths.

A: In the CSS for your site, there is already a media query in place, which is what is causing the cart to move to the left. It looks like this:
@media (max-width: 767px) {
  #topbar .kad-topbar-left, #topbar .kad-topbar-left .topbarmenu {
    float: none;
  }
}

Above 767px, the style for those two elements is float: left.
If we delete that rule, so that the elements continue to float left, we can see that the cart will still fit in one row with the search up through 417px wide. So I would recommend simply revising the value in the media rule (using a rounder number):
@media (max-width: 420px) {
  #topbar .kad-topbar-left, #topbar .kad-topbar-left .topbarmenu {
    float: none;
  }
}


text:
Q: GridLayout with CardView is not showing in lower OS version I was making a GridLayout of CardView for automatic orientation of cardview, height and width of cardview is set to 0dp it is working fine in nougart and oreo but not working in Lollipop and Kitkat.
Here is the Layout code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.help.MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:background="@drawable/bg"
        android:weightSum="10"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <RelativeLayout
        android:layout_weight="2"
        android:layout_width="match_parent"
        android:layout_height="0dp">

        <TextView
            android:id="@+id/textGrid"
            android:text="GRID LAYOUT"
            android:textSize="34sp"
            android:textColor="@android:color/white"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <GridLayout
        android:id="@+id/mainGrid"
        android:columnCount="2"
        android:rowCount="3"
        android:alignmentMode="alignMargins"
        android:columnOrderPreserved="false"
        android:layout_weight="8"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:padding="14dp"
        >

        <!-- Row 1 -->

        <!-- Column 1 -->
        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp"
            >

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/me_time"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:text="Me"
                    android:textAlignment="center"
                    android:textColor="@android:color/black"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </android.support.v7.widget.CardView>

        <!-- Column 2 -->
        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp"
            >

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/family_time"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:text="Family"
                    android:textAlignment="center"
                    android:textColor="@android:color/black"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </android.support.v7.widget.CardView>

        <!-- Row 2 -->

        <!-- Column 1 -->
        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp"
            >

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/lovely_time"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:text="Lovely"
                    android:textAlignment="center"
                    android:textColor="@android:color/black"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

        </android.support.v7.widget.CardView>

        ........

    </GridLayout>

    </LinearLayout>

</ScrollView>

Left side emulator is having android API-22(lollipop) and emulator on right side is having android API-26(oreo)

Please Help to solving this problem i have tried and search for solution but none of them worked. Also i have tried changing width and height to match_parent/wrap_content/fixedvalue but nothing worked correctly.

A: Got the solution after so much trying...
Changing <GridLayout> to <android.support.v7.widget.GridLayout>
and adding dependencies in app:gradle
dependencies {
    compile 'com.android.support:gridlayout-v7:26.1.0'
}

Also changing import statement in java file to
import android.support.v7.widget.GridLayout;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pygame sprite not turning accordingly to mouse I've been trying and trying, but basically I wanna make a tank game which has a tank that can turn itself by the mouse to fire bullets; when you turn your mouse to a direction, the sprite will follow exactly. the problem is, I can't turn the tank with any code, no matter what.
import os
import pygame
import math

pygame.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30)
icon = pygame.image.load('Sprite3.png')
pygame.display.set_icon((icon))
pygame.display.set_caption('DeMass.io')

class Tank(object):  # represents the bird, not the game
    def __init__(self):
        """ The constructor of the class """
        self.image = pygame.image.load('Sprite0.png')
        # the bird's position
        self.x = 0
        self.y = 0

    def handle_keys(self):
        """ Handles Keys """
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_DOWN] or key[pygame.K_s]:
            self.y += dist # move down

        elif key[pygame.K_UP] or key[pygame.K_w]:
            self.y -= dist # move up

        if key[pygame.K_RIGHT] or key[pygame.K_d]:
            self.x += dist # move right

        elif key[pygame.K_LEFT] or key[pygame.K_a]:
            self.x -= dist # move left

def draw(self, surface):
        """ Draw on surface """
        # blit yourself at your current position
        surface.blit(self.image, (self.x, self.y))

w = 1900
h = 10000
screen = pygame.display.set_mode((w, h))

tank = Tank() # create an instance
clock = pygame.time.Clock()
connection_angle = 90

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit() # quit the screen
            running = False

    screen.fill((255, 255, 255))
    tank.draw(screen)
    pygame.display.update()
    tank.handle_keys()
    clock.tick(100)

A: You can use the atan2 function from the built-in math module to calcualte the angle between two coordinates,
and then rotate your sprite accordingly:
import pygame
from math import atan2, degrees

wn = pygame.display.set_mode((400, 400))

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30, 40), pygame.SRCALPHA)
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect(topleft=(185, 180))

    def point_at(self, x, y):
        rotated_image = pygame.transform.rotate(self.image, degrees(atan2(x-self.rect.x, y-self.rect.y)))
        new_rect = rotated_image.get_rect(center=self.rect.center)
        wn.fill((0, 0, 0))
        wn.blit(rotated_image, new_rect.topleft)

player = Player()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.MOUSEMOTION:
            player.point_at(*pygame.mouse.get_pos())

    pygame.display.update()

Output:


text:
Q: PHP: Reference another static variable inside a static variable Either I'm too dumb or this is somehow not possible in php (which is really a basic functionality in any programming language...):
So here's the example for my problem:
class Test {
 private static $A = "test";
 private static $B = "This is a " . Test::$A . " to see if it works";
}

My expected result is the variable $B to have the value = This is a test to see if it works
But somehow I'm getting this error:

Parse error: syntax error, unexpected '$A' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS) in /.../class.Test.php on line 4

Is this something php is unable to do or is it just some stupid typo? I'm unable to find the error since like an hour...
Thanks in advance

A: *

*You can't assign dynamic value to class property. See manual

*You can try to define magic getter, BUT getters don't work with static properties. See manual

Property overloading only works in object context. These magic methods
  will not be triggered in static context. Therefore these methods
  should not be declared static. As of PHP 5.3.0, a warning is issued if
  one of the magic overloading methods is declared static.
In PHP 5.3, __callStatic has been added ; but there is no __getStatic
  nor __setStatic

*So only options that I see is to use __callStatic and access to you properties via static magic methods. See example below.
class A {

   public static $A = 'A';

   public static function __callStatic($name, $arguments)
   {
      if ($name== 'B') {
         return B::$B;
      }
   }

}

class B {
    public static $B = 'B';
}

echo A::B(); // return 'B'

A: Another solution if you don't want to have another clas
class TestStatic
{
    private static $A = 'test';
    private static $B;

    //if you want to instantiate the object
    public function __construct() {
        self::setB();
    }

    //if you don't want to instantiate the class
    public static function getB() {
        self::setB();
       return self::$B;
    }

    private static function setB() {
       if (!isset(self::$B)) {
        self::$B = 'This is a '.self::$A.' to see if it works';
    }
}

}
echo TestStatic::getB();


text:
Q: Cannot convert from one iterator type to another but both are the exact same I'm attempting to compile the ZipStream library, it is effectivley a C++ wrapper for zlib.
Right now I'm at the point where I'm getting two compile errors on these two lines:
std::set<file_info_32*, sort_by_offset>::iterator first  = _core->_entries_by_name.begin();
std::set<file_info_32*, sort_by_offset>::iterator last   = _core->_entries_by_name.end();

The errors are:

Error  15  error C2440: 'initializing' : cannot convert from
'std::_Tree_const_iterator<_Mytree>' to
'std::_Tree_const_iterator<_Mytree>'  c:\users\ahakeem\desktop\zipstream\ziparchive.cpp   423 1   zipstream
  Error   16  error C2440: 'initializing' : cannot convert from
'std::_Tree_const_iterator<_Mytree>' to
'std::_Tree_const_iterator<_Mytree>'  c:\users\ahakeem\desktop\zipstream\ziparchive.cpp   424 1   zipstream

So basically the compiler says it can't convert from 'std::_Tree_const_iterator<_Mytree>' to 'std::_Tree_const_iterator<_Mytree>'
Any ideas why it's happening and how to fix?
edit: after further investigating I've found that _core->entries_by_name.begin() is declared as 'std::set<file_info_32*, sort_by_offset>', which is obviously inconsistant with what its iterator is trying to be assigned to (std::set<file_info_32*, sort_by_offset>).
Switching it to _core->_entries_by_offset.begin(); works because _entries_by_offset is a type consistant with what the assignee is expecting to get.
Does this mean someone may have broken the code, didn't realize it and uploaded it to the source repo? Or can this scenario of erraneous assignment actually compile on some systems?

A: My best guess, the classes substituted for _MyTree are different.
Look for with _MyTree = SomeClass somewhere in your output just below the error.


text:
Q: Passing Textbox information from one form to another I'm trying to type a name (NameFirst)+(NameLast) store it in StudentName and transfer to the default form NameForm and then have that information displayed in StudentName once the submit button is pressed. The submit button also opens the main form, "frmMain"
I'm doing something wrong, obviously, as the StudentName textbox on the frmMain which is opened after pressing submit, is blank.
NameForm
Public Class NameForm

  Public StudentName As String

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        StudentName = (NameFirst.Text) + (NameLast.Text)

        Dim openForm As frmMain
        openForm = New frmMain()
        openForm.Show()
        openForm = Nothing

    End Sub

    Private Sub ButtonClear_Click(sender As Object, e As EventArgs) Handles ButtonClear.Click
        NameFirst.Text = ""
        NameLast.Text = ""
    End Sub

    Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
        Me.Close()
    End Sub

End Class

frmMain
Option Explicit On
Option Strict On
Option Infer Off

Public Class frmMain

    Private Sub ButtonCalc_Click(sender As Object, e As EventArgs) Handles ButtonCalc.Click

        Dim SumForum As Integer
        Dim SumAssign As Integer
        Dim FAverage As Double
        Dim AAverage As Double

        Dim Grades() As String = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}

        'Total and then average of Forum grades, displayed in Forum Average text box
        SumForum = CInt(Val(Forum1.Text) + Val(Forum2.Text) + Val(Forum3.Text) + Val(Forum4.Text) + Val(Forum5.Text) + Val(Forum6.Text) + Val(Forum7.Text) + Val(Forum8.Text))

        FAverage = (SumForum / 8)

        ForumAverage.Text = CStr((FAverage))

        'Total and then average of Assignment grades, displayed in Assignment Average text box
        SumAssign = CInt(Val(Assign1.Text) + Val(Assign2.Text) + Val(Assign3.Text) + Val(Assign4.Text) + Val(Assign5.Text) + Val(Assign6.Text) + Val(Assign7.Text) + Val(Assign8.Text))

        AAverage = (SumAssign / 8)

        AssignAverage.Text = CStr(AAverage)

    End Sub

    Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
        Me.Close()
    End Sub

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        NameForm.StudentName = Me.StuName.Text
    End Sub
End Class

A:
I changed the startup to frmMain just now. So when you click in the
  StudentName box on frmMain, the NameForm opens and the name can be
  entered there. Though getting the name from NameForm to frmMain is
  still perplexing me

Great.  In frmMain, you'd do something like this:
Dim nf As New NameForm
If nf.ShowDialog = DialogResult.OK Then ' <-- code stops here until "nf" is dismissed
    Me.StuName.Text = nf.StudentName
End If

Over in NameForm, once you set your StudentName field, you simply set DialogResult to OK:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    StudentName = NameFirst.Text & NameLast.Text
    Me.DialogResult = DialogResult.OK ' <-- returns execution back to frmMain
End Sub


text:
Q: Are e2e DL systems better than DNN-HMM models in speech recognition? End-to-end deep learning systems for automatic speech recognition (ASR) have been around for a while now since Deep Speech (2014), but I noticed that DNN-HMM based methods are still performing well and making it to the charts like here.
Does that mean it is still not settled which system is better? Or do they win based on conditions? Who is better when you just have speech training data in the order of hundreds of hours and not tens of thousands? Which system is better in real life and not on super clean data?

A:
Does that mean it is still not settled which system is better?

It is more or less clear which system is better in which condition and what are the downsides and advantages.

Or do they win based on conditions?

DNN-HMM is good for 1000-10000 hours of data and when you do not have too many GPUs (just 2-4 cards)
DNN-E2E is really good for huge amounts (10000 hours - 100000 hours) of data and if you really have extreme computing power (100 of GPUs/TPUs).
So unless you have resources like Google you still go with DNN-HMM.

Who is better when you just have speech training data in the order of hundreds of hours and not tens of thousands? Which system is better in real life and not on super clean data?

For hundred hours it is more effective to collect more data than to choose the algorithm. It really helps to get 1000-2000 hours.


text:
Q: Use php-cli to start, restart, and stop apache 2.4 and mariadb Problem:
I am wanting to use php-cli scripts to quickly start, restart, or stop Apache 2.4 as well as MariaDB 10.5 on Windows 10. Several years ago, I did this while running Debian:
#!/usr/bin/php
<?php
system('sudo /etc/init.d/apache2 start');
system('sudo /etc/init.d/mysql start');

I would then execute the file by typing something similar to 'php -f .server.start' where .server.start was the name of the file containing the above php code. I have had some luck getting this to work by opening a command line, changing directories to C:\Path\to\Apache24 and using
<?php
system('httpd -k start');

The issue with this is I still have to navigate to that directory to make this work. The purpose is then defeated as I could simply type httpd -k start || stop || restart. I am using this machine at home for a dev box. There are times when I am interrupted for lengthy spans of time and I feel that I need a simple and quick way to shutdown both Apache and MariaDB with a command or two while I am away from my desk.
Perhaps PHP isn't the best solution here? It's what I know and am comfortable with, though, if there are other methods, such as with a batch file, I would be willing to accept any comments/feedback/direction. I have scoured the web trying to get this task done.


text:
Q: lucene: space requirements for optimising the database? It is my understanding that there are several options when it comes to database optimisation in Lucene:

*

*optimise the whole thing into one segment, space hungry by at least 2× ?

*optimise into several segments

*remove deleted entries — expungeDeletes(), without changing the number of segments?

Consider that a database is not held on a platter disc (mfs is in use).  Do each of these operations have some bound on space requirements?
I noticed that expungeDeletes() is no longer documented for Lucene 4.6.0 — has it been removed?  I'm coming from Lucene 3.0.2 / December 2011, although I'm open to upgrading to 4.6 sometime.

A: Manual optimization methods have now been removed in favour of Tiered Merge Policy. You may read about this in the blog post of one of the authors of Lucene. In short, merge will happen automatically as it is believed that the algorithm (which knows the internal state of the index) will do a better job than the user.
p.s. I think you need to get the nomenclature right. There's no such thing as "database" in Lucene (you probably meant index?)


text:
Q: Running ASP.NET and SQL Server on WD my cloud ex2 I just bought a WD my cloud ex2.
The reason I bought this over the white original my cloud is that this machine can produce a public IP for FTP transfer, becoming a true cloud based storage. But i also want to free myself from the chains of expensive web-hosting and it makes me feel even more pathetic because I have a storage device and I'm still buying storage for my websites. I build asp.net websites using WebMatrix, and have a SQL Server Database. Can my storage device run ASP.NET? I don't know much about Windows Server, but does that have to be installed in the myCloud? Would there be any way to do so?
Thank you.

A: No.  Not an MS box.  But you can use MySQL and recode your asp.net to php.  Another great choice would be to get a free (for 1 year) Amazon Web Services EC2 instance.  You can run a small MS Server there and keep your stuff in ASP.net


text:
Q: declarative resource based requirement authorization not working with API Controller I am trying setup an authoriztion policy that I can use to decorate actions in API Controllers in .net core 3.1. I have been following these examples :
 https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-3.1
If i have an API action decorated like below my code does not hit the handlerequirementAsync method of the handler and I get a 403 Forbidden response from swagger. If i remove the document model from the handler/requirement it does work. Am I doing something wrong or is this not supported for api requests?
here is the other relevant code :
    public class DocumentAuthorizationHandler :
    AuthorizationHandler<SameAuthorRequirement, Document>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   SameAuthorRequirement requirement,
                                                   Document resource)
    {
        if (context.User.Identity?.Name == resource.Author)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

public class SameAuthorRequirement : IAuthorizationRequirement { }

[Authorize(Policy = "EditPolicy")]
public async Task<FileResult> RetreiveFile([FromRoute]Document model)

 {
 }

services.AddAuthorization(options =>
{
    options.AddPolicy("EditPolicy", policy =>
        policy.Requirements.Add(new SameAuthorRequirement()));
});

services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();

A: You should have to inject IAuthorizationService in the controller constructor
public class AbcController : Controller
{
   private readonly IAuthorizationService _authorizationService;

   public AbcController(IAuthorizationService authorizationService)
   {
      _authorizationService = authorizationService;
   }
   // No need to add this [Authorize(Policy = "EditPolicy")]
   public async Task<FileResult> RetreiveFile([FromRoute]Document model)
   {
      //add this below line which shall call the handler
       var authorizationResult = await _authorizationService.AuthorizeAsync(User, model, "EditPolicy");
   }


text:
Q: Is it possible to disable stack traceback in Lua? Is this possible?

A: To disable stack traceback in the standalone Lua interpreter, use debug.traceback=nil in your Lua program.

A: By calling the code in question via pcall or xpcall, you can handle errors however you want, including ignoring them completely.


text:
Q: woocommerce {{{ data.variation }}} as variable New Question:
Does anyone know how to work with {{{ data.variation }}} in the woocommerce template variation.php?
If I use: {{{ data.variation.variation_id }}} I get an ID printed as 55 (in variables.php, for a selected variation that actually has the ID of 55).
If I use: get_post_meta( '55', '_start_month', true ) I get the variation data that I am looking for.
But (and here is the confusion) if I use
get_post_meta( '{{{ data.variation.variation_id }}}', '_start_month', true )

I get null. I can't for the life of me figure out how to use the {{{ data.variation }}} values as numbers.
Argh!!
Previous Question:
I am working in the woocommerce template variation.php.
It has code that includes:

This renders the price for a product variation. I have modified it to pull another variation like this:

I am then able to pull this into php like this:
$var="{{{ data.variation.my_number }}}";
echo $var;

This shows me the variation value. In this case it is 14.
So, it would seem that I have a value that is accessible to php. But it isn't. I cannot do anything with the value. I can't turn it from a string into an integer or anything like that. For example.
$var=$var * 2;

Or:
$var= (int) $var;
$var=$var * 2;

Spits out '0';
To investigate, I did a var_dump.
var_dump($var);

This shows me that $var is 24 characters long. In other words, I was expecting the value of var_dump($var) to be 2 characters long (the value '14'), but instead var_dump($var) seems to be calculating 'data.variation.my_number' as the value.
So, while it looks like $var=14 it seems to actually be that $var='data.variation.my_number';
I have rewritten this question to try to be more clear. But I think it might still be confusing. The php variable value seems to be the variation name, not the variation value.
Is there any php syntax that I can use to separate one from the other?
Thanks for any insight. I'm hoping this is a quickie for someone who knows of the right method or syntax.

A: so I've just been faced with the same problem, wanting to control or have some conditional logic around the output of {{{ data.variation.checkbox }}} within variation.php and found that we can use this:
<# if ( data.variation.checkbox == 'yes') { #>

YOUR CONTENT HERE

<# } #>

the code uses the wp.template - works like a treat.
reference from where this was taken.
https://zao.is/blog/2017/03/22/how-to-use-wp-template/
hope it helps


text:
Q: how default arguments work in python I have just read an article: The 10 Most Common Mistakes That Python Developers Make. The problem #1 still puzzled me a lot. I will describe my problem with the codes below.
>>>def foo(bar=[]):
...    bar.append("baz")
...    return bar
>>> foo()
["baz"]
>>> foo()
["baz", "baz"]

It not works, the answer in the article says list is an multable type and the default value changes during the call.But when I try this one
def foo(bar=[]):
    if bar == []:bar=[]
...

it works, so what makes the difference?

A: Default arguments are created at function definition in Python. This means that when you provide a list as a default argument, that list will persist for all function calls in which that argument is not explicitly passed. In the second example, you are reassigning the argument to a different value. That creates a new list and will fix the problem. A more common solution to this "bug"/"feature" is to assign the default argument a value of None and then check it at the top of the function. That would look something like this:
def foo(bar=None):
    if bar is None:
        bar = []

However, the code that you wrote in the second example achieves the same effect.

A: In your code you assign a new list to bar instead using the default argument. Now if you modify the new list the changes of course aren't shown in the default argument which is different object.
The typical solution is to assign None to the default argument and explicitly check it at the beginning of function:
def foo(bar=None):
    if bar is None:
        bar = []

Note that although it looks a lot like your version there are differences:
def foo(bar=[]):
    if bar == []:
        bar = []
    bar.append(1)

def foo2(bar=None):
    if bar is None:
        bar = []
    bar.append(1)

l = []
foo(l)
print l # []

l = []
foo2(l)
print l # [1]


text:
Q: Find norm of the following operator Find norm of the following bounded linear $Ax(t)=\int_0^1e^{ts}x(s)ds$ where $x\in C[0,1]$ and $t\in [0,1]$. Help me. Many thanks.

A: DETAILED HINT: first you must show that $A$ is a bounded linear operator, that is, that map bounded sets to bounded sets, what is equivalent to say that $A$ is continuous.
Then the norm of $A$ exists and is defined as
$$\begin{align}\|A\|_{\mathcal L(C[0,1])}:&=\inf\{c\ge 0:\|Ax\|_\infty\le c\|x\|_\infty, x\in C[0,1]\}\\&=\inf\{c\ge 0:\|Ax\|_\infty\le c, \|x\|_\infty=1,x\in C[0,1]\}\\&=\sup\{\|Ax\|_\infty:\|x\|_\infty=1, x\in C[0,1]\}\end{align}$$
with $\|Ax\|_\infty=\sup_{t\in[0,1]}|x(1)t^2|$.

A: First, check your definition. I'm familiar with these three:
$$
\|A\|=\sup_{\stackrel{x\in C[0,1]}{\|x\|_\infty=1}}\|Ax\|_\infty
\\
\|A\|=\sup_{\stackrel{x\in C[0,1]}{\|x\|_\infty\leq1}}\|Ax\|_\infty
\\
\|A\|=\sup_{\stackrel{x\in C[0,1]}{\|x\|_\infty<1}}\|Ax\|_\infty
$$
Depending on the definition, you have to argue slightly different. I prefer to use the first (or second) one.
First, you have to find a constant $c$ such that $\|Ax\|_\infty\leq c$ for all $x\in C[0,1]$ with $\|x\|_\infty=1$, $\|x\|_\infty\leq 1$ or $\|x\|_\infty<1$ (depending on the definition...)
You have $$
\|Ax\|_\infty=\sup_{t\in[0,1]}|x(1)t^2|=\ldots \leq \ldots
$$
You can compute the supremum directly and then estimate the value using $\|x\|_\infty=\sup_{s\in[0,1]}|x(s)|$.
This yields $\|A\|\leq c$.
Second, you have to prove $\|A\|\geq c$. Here you need an explicit function $\tilde{x}\in C[0,1]$ such that $\|\tilde x\|_\infty=1$ and $\|A\tilde x\|_\infty=c$. Then you deduce
$$
\|A\|=\sup_{\stackrel{x\in C[0,1]}{\|x\|_\infty=1}}\|Ax\|_\infty\geq \|A\tilde x\|_\infty =c.
$$
The function $\tilde x$ is not hard to find. Consider the first step, where you do the estimation. You can think of an (very simple) function, where equality holds. This function can be used in the second step.
But if you have to use the third definition from above, than you have to be careful in the second step, since you can use a function $\tilde x$ with $\|\tilde x\|_\infty=1$. Instead you have to define a sequence of functions $(\tilde x_n)_n$ where $\tilde x_n\in C[0,1]$, $\|\tilde x_n\|_\infty<1$ and $\lim_{n\to\infty} \|A\tilde x_n\|_\infty=c$. Then you can say
$$
\|A\|=\sup_{\stackrel{x\in C[0,1]}{\|x\|_\infty<1}}\|Ax\|_\infty\geq \|A\tilde x_n\|_\infty
$$
for all $n\in\mathbb N$ hence
$$
\|A\|\geq \lim_{n\to\infty}\|A\tilde x_n\|_\infty=c.
$$

A: The $C[0,1]$ norm is the sup (or max) norm of the continuous function on $[0,1]$.
$$
   \|Ax\|=\|x(1)t^2\|=|x(1)| \le \|x\|.
$$
So $A$ is bounded with $\|A\| \le 1$. The norm is $1$ because $\|A1\|=1=\|1\|$.


text:
Q: How can I simulate hand rays on HoloLens 1? I'm setting a new project which is intended to deploy to both HoloLens 1 and 2, and I'd like to use hand rays in both, or at least be able to simulate them on HoloLens 1 in preparation for HoloLens 2.
As far as I have got is:

*

*Customizing the InputSimulationService to be gesture only (so I can test in editor)

*Adding the GGVHand Controller Type to DefaultControllerPointer Options in the MRTK/Pointers section.

This gets it to show up and respond to clicks both in editor and device, but it does not use the hand coordinates and instead raycasts forward from 0,0,0, which suggests that the GGV Hand Controller is providing a GripPosition (of course with no rotation due to HL1) but not providing a Pointer Pose.
I imagine the cleanest way to do this would be to add a pointer pose to the GGV Hand controller, or add (estimated) rotation to the GripPosition and use this as the Pose Action in the ShellHandRayPointer. I can't immediately see where to customize/insert this in the MRTK.
Alternatively, I could customize the DefaultControllerPointer prefab but I am hesitant to do so as the MRTK seems to still be undergoing frequent changes and this would likely lead to upgrade headaches.

A: You could create a custom pointer that would set the pointer's rotation to be inferred based on the hand position, and then like you suggested use Grip Pose instead of Pointer Pose for the Pose Action.
The code of your custom pointer would look something like this:
// Note you could extend ShellHandRayPointer if you wanted the beam bending,
// however configuring that pointer requires careful setup of asset.
public class HL1HandRay : LinePointer
{
    public override Quaternion Rotation
    {
        get
        {
            // Set rotation to be line from head to head, rotated a bit
            float sign = Controller.ControllerHandedness == Handedness.Right ? -1f : 1f;
            return Quaternion.Euler(0, sign * 35, 0) * Quaternion.LookRotation(Position - CameraCache.Main.transform.position, Vector3.up);
        }
    }

    // We cannot use the base IsInteractionEnabled
    // Because  HL1 hands are always set to have their "IsInPointing pose" field as false
    // You may want to do more thorough checks here, following BaseControllerPointer implementation
    public override bool IsInteractionEnabled => IsFocusLocked || IsTracked;
}

Then create a new pointer prefab and configure your pointer profile to use the new pointer prefab. Creating your own prefab instead of modifying MRTK prefabs has advantage of ensuring that MRTK updates will not overwrite your prefabs.

Here's some captures of the simple pointer prefab I made to test this with relevant changes highlighted:

And then the components I used:


text:
Q: Evaluate Sympy boolean expression in python I am using Python and Sympy.
I have the following:
x,y,z = Symbols('x,y,z')
doc = {x : False, y : True, z: True}
rule = Or(x, And(y,z))

I am looking for a function in Sympy that will return True on rule.eval(doc)?
Edit:
Currently I am using rule.subs and rule.xreplace both are performing slowly with about 0.0003 seconds per call. This makes it impractical.

A: A way to get better performance with minimal coding is to use lambdify:
X = tuple(doc.iterkeys())
f = lambdify(X, rule)

After this IPython gave me:
V = tuple(doc.itervalues())
%timeit f(*V)
The slowest run took 7.56 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 209 ns per loop

I am not sure how much the warning may impact the conclusion, but there is a clear improvement. On the same computer I had with the original code:
%timeit rule.xreplace(doc)
10000 loops, best of 3: 126 µs per loop

And subs was even slower.

A: Rather than using subs can you use direct evaluation?
>>> F = Lambda((x, y, z), Or(x, And(y, z)))
>>> F(0, 1, 1)
True

If not, could you create a toy class that will allow subs via the lambda form? This is not a class but it gives the idea:
>>> def sub(f, d):
...     F = Lambda(d.keys(), f)
...     return F(*[d[k] for k in d.keys()])
>>> sub(Or(x,And(y,z)),{x:0,y:1,z:1})

The class would create the Lambda form and have a subs method which would return the evaluated Lambda form.


text:
Q: Does the Low State in NE555 go to GND? Here is the first schematic that I created : .
The Vcc is at 5.1V and I a self made using the LM317, Works Fine.
When I checked the Output with the Multi-meter I use., I was getting a high state of around 3.9V(Which I guess was fair enough.), but the Low was was giving an out of 2.5 ~ 2.6V, which to me seems a concern because the NE555 datasheet shows low state going to 0V in one of the .
I even tried simulating the circuit afterwards and this is what it looks like in simulation and even in the hardware set up :
.
And what am I supposed to make out of this?

So now I am getting a High state of 3.6V(seems fine), but the low state is still around 2.6V.
How do I find out the root of the Issue and how should I debug it?

A: With that particular circuit yes the output should go close to ground.
If it is not, either

*

*the 555 is sick or

*you MUST be pulling current from somewhere else... or

*perhaps the oscillator is still oscillating at some higher frequency, or,

*Your 5V supply is not flat DC.

Using a scope would help a lot.
You could try lifting the output pin and see if it still does it and measure what the voltage is at the top of the LED to eliminate item 2.


text:
Q: How can I reduce this code to a single procedure I am relatively new to the whole .NET thing, coming from a VB classic background.
On my form I have a tabcontrol, with 4 tabs.  Most of the code is handled using a shared handler, but for the others I have to write a handler for each.
How can I optimize these routines into a single procedure?
    Private Sub cboCalc0_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCalc0.SelectedIndexChanged
    'Page 0
    If (Not (IsNothing(trvSignals0.SelectedNode)) And txtSignalName0.Enabled = True) AndAlso trvSignals0.SelectedNode.Level = 3 Then
        tempChannelProp(0, trvSignals0.SelectedNode.Tag).CalcVariant = cboCalc0.SelectedIndex
    End If
End Sub

Private Sub cboCalc1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCalc1.SelectedIndexChanged
    'Page 1
    If (Not (IsNothing(trvSignals1.SelectedNode)) And txtSignalName0.Enabled = True) AndAlso trvSignals1.SelectedNode.Level = 3 Then
        tempChannelProp(1, trvSignals1.SelectedNode.Tag).CalcVariant = cboCalc1.SelectedIndex
    End If
End Sub

Private Sub cboCalc2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCalc2.SelectedIndexChanged
    'Page 2
    If (Not (IsNothing(trvSignals2.SelectedNode)) And txtSignalName2.Enabled = True) AndAlso trvSignals2.SelectedNode.Level = 3 Then
        tempChannelProp(2, trvSignals2.SelectedNode.Tag).CalcVariant = cboCalc2.SelectedIndex
    End If
End Sub

Private Sub cboCalc3_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCalc3.SelectedIndexChanged
    'Page 3
    If (Not (IsNothing(trvSignals3.SelectedNode)) And txtSignalName3.Enabled = True) AndAlso trvSignals3.SelectedNode.Level = 3 Then
        tempChannelProp(3, trvSignals3.SelectedNode.Tag).CalcVariant = cboCalc3.SelectedIndex
    End If
End Sub

I have handled the other bits as follows, and it works great, but I just cannot figure out how to do it with code like that above.
    Private Sub trvSignals_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles trvSignals0.AfterCheck, trvSignals1.AfterCheck, trvSignals2.AfterCheck, trvSignals3.AfterCheck
    'Handles Page 0,1,2,3
    sender.SelectedNode = e.Node
    If e.Node.Level = 3 Then
        tempChannelProp(sender.tag, e.Node.Tag).Active = e.Node.Checked
    End If
End Sub

I use the tag property of the control of each page to hold either 0,1,2 or 3 as appropriate.
Thanks
Graham

A: Create control arrays that you can reference by index, and put the index in each controls' Tag.
Class MyForm

    Private ReadOnly cboCalcArray As ComboBox()
    Private ReadOnly trvSignalsArray As TreeView()
    Private ReadOnly txtSignalNameArray As TextBox()

    Public Sub New()
        InitializeComponent()
        cboCalcArray = new ComboBox() {cboCalc0, cboCalc1, cboCalc2, cboCalc3}
        trvSignalsArray = new TreeView() {trvSignals0, trvSignals1, trvSignals2, trvSignals3}
        txtSignalNameArray = new TextBox() {txtSignalName0, txtSignalName1, txtSignalName2, txtSignalName3}
    End Sub

    Private Sub cboCalcX_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) _
        Handles cboCalc0.SelectedIndexChanged,
                cboCalc1.SelectedIndexChanged,
                cboCalc2.SelectedIndexChanged,
                cboCalc3.SelectedIndexChanged
        Dim index As Integer = sender.Tag
        If (Not (IsNothing(trvSignalsArray(index).SelectedNode)) And txtSignalNameArray(index).Enabled = True) AndAlso trvSignals2.SelectedNode.Level = 3 Then
            tempChannelProp(index, trvSignalsArray(index).SelectedNode.Tag).CalcVariant = cboCalcArray(index).SelectedIndex
        End If
    End Sub
End Class

A: You can leverage a couple of features:
1) The VB Handles statement can hook multiple control events to the same method.
2) You can get the combobox from the sender, then extract the index.
3) From the index, you can find the other associated controls.
Private Sub cboCalc_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCalc0.SelectedIndexChanged, cboCalc1.SelectedIndexChanged, cboCalc2.SelectedIndexChanged, cboCalc3.SelectedIndexChanged

    Dim oCombo As ComboBox

    oCombo = DirectCast(sender, ComboBox)

    Dim wIndex As Integer
    Dim oTree As TreeView
    Dim oTextBox As TextBox

    wIndex = CInt(oCombo.Name.Substring(oCombo.Name.Length - 1))

    oTree = DirectCast(Me.Controls.Find("trvSignals" & wIndex.ToString, True)(0), TreeView)
    oTextBox = DirectCast(Me.Controls.Find("txtSignalName" & wIndex.ToString, True)(0), TextBox)

    If oTree.SelectedNode IsNot Nothing AndAlso oTextBox.Enabled AndAlso oTree.SelectedNode.Level = 3 Then
        tempChannelProp(wIndex, oTree.SelectedNode.Tag).CalcVariant = oCombo.SelectedIndex
    End If

End Sub

A: There is likely a more elegant solution to your problem somewhere. I find that, if I am defining the same controls and methods for multiplpe tabs on a tab control, it might be time to examine my design . . . Not always, though.  :-)
This might be a little less clumsy, although using Select Case to choose between otherwise identical configurations of UI elements gives me the heebie-jeebies (It DOES get all your code into one handler, however):
    Private Sub PerformCalcs(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles _
        cboCalc0.SelectedIndexChanged,
        cboCalc1.SelectedIndexChanged,
        cboCalc2.SelectedIndexChanged,
        cboCalc3.SelectedIndexChanged

        Dim cboCalc As ComboBox = DirectCast(sender, ComboBox)

        ' The Parent of the combo box is the TabPage, and the Parent of the TabPage is the TabControl:
        Dim t As TabControl = cboCalc.Parent.Parent

        Dim SelectedNode As TreeNode
        Dim TxtSignalName As TextBox

        ' The TabControl knows the index value of the currently selected tab:
        Select Case t.SelectedIndex
            Case 0 'Page 0
                SelectedNode = trvSignals0.SelectedNode
                TxtSignalName = txtSignalName0
            Case 1 ' Page 1
                SelectedNode = trvSignals1.SelectedNode
                TxtSignalName = txtSignalName1
            Case 2 ' Page 2
                SelectedNode = trvSignals2.SelectedNode
                TxtSignalName = txtSignalName2
            Case 3 ' Page 3
                SelectedNode = trvSignals3.SelectedNode
                TxtSignalName = txtSignalName3
            Case Else ' Ooops! Something horrible happened!
                Throw New System.Exception("You have passed an invalid Control as a parameter")
        End Select

        If (Not (IsNothing(SelectedNode)) And TxtSignalName.Enabled = True) AndAlso trvSignals3.SelectedNode.Level = 3 Then
            tempChannelProp(3, SelectedNode.Tag).CalcVariant = cboCalc.SelectedIndex
        End If

    End Sub


text:
Q: Difficulty in plotting graphs from data webread from a url The activity I am working on involves webreading weather forecast data from a url and plotting it as graphs. I am plotting the pressure, temperature, humidity and wind speed. The pressure and temperature graphs plot just fine, however the humidity and windspeed do not plot at all. I am not sure if there is a problem with my for loop or some other issue. This is my code:
%% Project API

clear;
clc;
api = 'https://api.openweathermap.org/data/2.5/onecall/timemachine?lat={lat}&lon={lon}&dt={time}&appid={b5904b7602f68fcca1d8886d36b36c4e}';

%api = 'api.openweathermap.org/data/2.5/forecast?q=London&appid=b5904b7602f68fcca1d8886d36b36c4e';
url = 'http://api.openweathermap.org/data/2.5/forecast?q=London&APPID=b5904b7602f68fcca1d8886d36b36c4e';
London_Data = webread(url);
London_Data.list{1, 1}.main.pressure;
London_Data.list{1,1}.main.humidity;
London_Data.list{1, 1}.dt_txt;

%day = [Data.list{1, 1}.dt_txt:Data.list{40, 1}.dt_txt];
%pressure = [Data.list{1, 1}.main.pressure:Data.list{3, 1}.main.pressure];

%Pressure
for i = 1:40
  %i = i+1;
  figure(1)
    plot([i+1 , London_Data.list{1, 1}.main.pressure : London_Data.list{40, 1}.main.pressure]);
    title('Pressure Forecast In London')
    xlabel('Days')
    ylabel('Pressure[hPa]')

end

%Temperature
for i=0:1:40
     figure(2)
 plot([i+1 , London_Data.list{1, 1}.main.temp]);
 i = i+1;
     title('Temperature Forecast In London')
    xlabel('Days')
    ylabel('Temperature[C]')
end

%Humidty
for i = 0;1:40
  figure(3)
    plot([i+1 , London_Data.list{1, 1}.main.humidity : London_Data.list{40, 1}.main.humidity]);
    %i = i + 1
    title('Humidity Forecast In London')
    xlabel('Days')
    ylabel('Humidity[Units]')
end

%Wind Speed
for i = 1:40
  %i = i+1;
  figure(4)
    plot([i+1 ,London_Data.list{1, 1}.wind.speed : London_Data.list{40, 1}.wind.speed]);
    title('Wind Speed Forecast In London')
    xlabel('Days')
    ylabel('Wind Speed[m/s]')

end

A: Your code had a few problems, please let me know if you have any questions about the way I changed it.
%% Project API

    clear;
clc;
api = 'https://api.openweathermap.org/data/2.5/onecall/timemachine?lat={lat}&lon={lon}&dt={time}&appid={b5904b7602f68fcca1d8886d36b36c4e}';

%api = 'api.openweathermap.org/data/2.5/forecast?q=London&appid=b5904b7602f68fcca1d8886d36b36c4e';
url = 'http://api.openweathermap.org/data/2.5/forecast?q=London&APPID=b5904b7602f68fcca1d8886d36b36c4e';
London_Data = webread(url);

len = size(London_Data.list,1);

%Pre-allocates array size (can be skipped)
P = zeros(1,len);
T = zeros(1,len);
Hum = zeros(1,len);
V = zeros(1,len);
%Puts the data in arrays
for i = 1:len
    P(i) = [London_Data.list{i, 1}.main.pressure];
    T(i) = [London_Data.list{i, 1}.main.temp];
    Hum(i) = [London_Data.list{i, 1}.main.humidity];
    V(i) = [London_Data.list{i, 1}.wind.speed];
end

%Pressure

figure(1)
plot(1:len, P)
title('Pressure Forecast In London')
xlabel('Days')
ylabel('Pressure[hPa]')

%Temperature

figure(2)
plot(1:len, T)
title('Temperature Forecast In London')
xlabel('Days')
ylabel('Temperature[C]')

%Humidty

figure(3)
plot(1:len, Hum)
title('Humidity Forecast In London')
xlabel('Days')
ylabel('Humidity[Units]')

%Wind Speed

figure(4)
plot(1:len, V)
title('Wind Speed Forecast In London')
xlabel('Days')
ylabel('Wind Speed[m/s]')


text:
Q: Weird Excel bar diagram behaviour I have a very simple question. I wanna have a diagram with the
following table
Apple   30  40  50
Pears   200 300 400
Bananas 10  20  30

The weird thing, when I try to draw a bar diagram the order of the bars
change. So Excel draws me first the Bananas, the the pears and finally the apple
bar... Is there anyway to tell Excel 2003 that it keeps the order?
Thank you very much

A: Click on the vertical axis to select it. Right-click on it and select "Format Axis...".
In the "Axis Options", check the "Categories in reverse order".


text:
Q: How to find why my application becomes unresponsive at unaccessible customer sites My application is deployed at customer sites, that I can not access, and has no internet connection.
There are complains that in several sites, once in a week or so, the application become unresponsive, so that the operators need to kill and restart it.
We were unable to observe it in our site.
Is there something I can do that may help me find the problem?
It is a VC2008 Win32 MFC applications.
The application is quite complex, and includes many threads, synchronization mechanisms, database access, HMI, communication channels...
Note: The custmer can send us log files.
Note: The application does not crash. It just hangs. Since I don't know what is the nature of the problem, I have no way to know programmatically that something went wrong (or do I?)

A: I have had great success with ADplus and WinDBG in the past. You may check it out. Especially check out the Hang mode in ADplus.

A: I would start with some questions - is the CPU hogged during these unresponsive times? Is there a specific process that's hogging it? (You can use PerfMon to get the answers). Depending on the answers I would probably proceed by taking a dump of the process at this stage (ProcDump by sysinternals is great for these purposes) and investigate it offline.

A: In similar situation on a non-windows platform we have the capability to gather system dumps. Get a thread dump of the entire system for off-site analysis. This enables us to find deadlocks quite easily. For slow problems rather than stop a single dump is not enough. Then we need a sequence of dumps, and some good luck.
Another, rather messier technique is to have enough trace, and enough fine-grained control of trace in the app. Then turn on some trace and hope to spot where the delays are happening.

A: My experience with finding bugs in installations on the other side of the planet shows three helpful techniques: Logging, logging, and logging.
What do those log files say your customers sent you? If they aren't detailed enough, send them a version that logs more. Use binary approximation to home in on the error.

A: To know where the process is hung is better to start with the stack trace at that instant.
Now since your program is installed remotely and you can't access it, you can write a monitoring program which can periodically check the stack of your program and log it. This information along with your logging mechanism will make things easier to identify and debug.
Since I am not a windows programmer, i don't know much about such tools availability in windows, however i think you need something similar to this http://www.codeproject.com/KB/threads/StackWalker.aspx


text:
Q: If $A$ is positive semi-definite, how to determine the positive definiteness of $B^TA B$? If $A$ is a positive semi-definite matrix and $B$ has a arbitary rank, how to determine the the positve definiteness of $B^TAB$ ? ($B^T$ is the transpose matrix of $B$)
I found that this product $B^TAB$ can be positive definite or positive semi-definite. So I think the positve definiteness may depend on the rank of $B$, but I cannot give a rigorous derivation.

A: Hint:
You know that the matrix $|M$ is positive definite if, for all $x\neq 0$, you have $$x^T Mx > 0$$ and it is positive semidefinite if you replace "$>$" above with "$\geq$".
Now, taking $M=B^TAB$, you can rewrite $x^TMx$ as
$$x^T(B^TAB)x = (x^TB^T) A (Bx) = (Bx)^T A (Bx).$$
Can you continue from here?

A: Let $y=Bx$.  Then $x^T B' A B x = y^T A y \geq 0$ since $A \geq 0$.  Since this is true of all $x$, $B' A B$ is positive semidefinite.


text:
Q: Sql Subquery result I have 3 tables, A, B,C

*

*Table A,Columns: latlong, name

*Table B, columns : code, name

*Table C, Columns : latlong, code
I want to update table A,column Name with the values from Table B, Column Name, something like:
update A set A.name =
(select b.name
 from B where code = c.code)
where a.latlong = c.latlong

Note that all the columns are not related.
Would appreciate the right direction to go about it.
Have tried Sub queries with inner joins, but no good.

A: You can do this with an update using join:
update a
    set name = b.name
    from a join
         c
         on c.latlong = a.latlong join
         b
         on b.code = c.code;

A: Try update with INNER JOIN
update A set
    A.name = B.name
FROM A
INNER JOIN C on C.latlong = A.latlong
INNER JOIN B on B.code = C.code

A: Last condition is missing where Table A.Latlong = C.Latlong to pick up the correct code!

A: You have mentioned in your question the following:

I want to update table A,column Name with the values from Table B, Column Name

But what I can see from your query is that actually , you need only those values of the column Name of table B which has same value of code as in table C, and that your latlong in A should be the same as latlong in C, if I'm not mistaken.
Based on that, I can say you need an SQL JOIN operation for Tables B and C with table A. Something like this:
UPDATE A SET A.name = B.Name
FROM A
JOIN C
ON C.latlong = A.latlong
JOIN B
ON B.code = C.code

No need to create a SUBQUERY


text:
Q: How to repeat a list of functions in haskell I want to have an infinite list of functions that cycles through some pattern. For example: [(+), (-), (+), (-), ...]
If I do something like
fmap repeat [(+), (-)]

then I get nested lists [[a -> a -> a]]. What's the best way to get a single infinite list of functions following a pattern like this?

A: What you are looking for is cycle :: [a] -> [a]:
cycle [(+),(-)]
The type of this expression is:
Prelude> :t cycle [(+),(-)]
cycle [(+),(-)] :: Num a => [a -> a -> a]

cycle takes a list [a] and produces a list where the given list is repeated over and over again. So cycle [1,2,3] produces [1,2,3,1,2,3,1,2,3,1,...]


text:
Q: How to identify input and output arrays of a tensoflow model for the process of ".tflite" conversion? I am trying to generate quantized .tflite model from .pb file. For the #process I require the 'input_arrays' and 'output_arrays' of the model.
I've tried using the below methods to identify the input array and output array. But none of them worked.
method 1:
import tensorflow as tf
frozen='/output/freeze/frozen_inference_graph.pb'
gf = tf.GraphDef()
gf.ParseFromString(open(frozen,'rb').read())
[n.name + '=>' +  n.op for n in gf.node if n.op in ('Softmax','Placeholder')]
[n.name + '=>' +  n.op for n in gf.node if n.op in ( 'Softmax','Mul')]

method 2:
import tensorflow as tf
gf = tf.GraphDef()
m_file = open('/output/freeze/frozen_inference_graph.pb','rb')
gf.ParseFromString(m_file.read())
for n in gf.node:
    print( n.name )

tflite conversion query:
import tensorflow as tf
graph_def_file = "new/barun/frozen_inference_graph.pb"
input_arrays = ['image_tensor']
output_arrays = ['BoxPredictor_5/ClassPredictor/act_quant/FakeQuantWithMinMaxVars']

converter = tf.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file, input_arrays, output_arrays,input_shapes={"image_tensor":[1,300,300,3]})
converter.inference_type = tf.lite.constants.QUANTIZED_UINT8
tflite_model = converter.convert()
open("frozen_inference_graph_fd2819_2.tflite", "wb").write(tflite_model)

How to find the input_array and output_array of the .pb file ?

A: Is the frozen model your own? In that case you can name the layers when creating the model.
Otherwise you could perhaps open the model in some sort of inspection tool, like Netron, and look for the names.

A: If you have created the model yourself, then the input_arrays will be the list of names of the input placeholder tensors. The output tensor which we use for inferencing will have their names in the output_arrays.
If in case we have a model readily downloaded from some other source, you can have some workarounds.

*

*In most TF projects, authors provide the details of the input/output tensors in the README section.

*Also, most of the projects using the graph.get_tensor_by_name() method to get the input output tensors, so that they could use them for inference ( particular with tf.Session() ). You can explore the inference files in depth to discover the names of the tensors.

If all other methods don't work, then as mentioned by @Silfverstrom, we can use Netron to visualize the graph.
Another way to visualize the graph could be TensorBoard. Write the graph to an events file like,
file_writer = tf.summary.FileWriter('/path/to/logs', sess.graph)

Then open up TensorBoard like,
tensorboard --logdir path/to/logs

Finally, only graph may help you to solve the problem.


text:
Q: Is there a way to find / replace a string across all tables in a mysql database? I'm thinking this isn't possible without doing a dump, searching / replacing within the .sql file, and then reimporting it, but figured I'd ask anyway...
Basically, is there a way to search for "samplestring" within all of the fields, within all of the tables, within one database and replace it with "examplestring"?

A: I don't know of one.  There especially isn't if you're willing/want to look at and modify column names and other non-data stuff.
If you don't have to do it very often, it's not that problematic.
mysqldump --username user --password pass database | sed 's/somestring/otherstring/g' | mysql -uroot -p

A: You can, but it requires using dynamic SQL (MySQL's Prepared Statements).
First, you need to get a list of the text based columns:
SELECT c.column_name, c.table_name
  FROM INFORMATION_SCHEMA.COLUMNS c
 WHERE c.table_schema = your_db_name
   AND c.data_type IN ('varchar') -- don't want to replace on an INT/etc

Then you need to iterate over that list to create the UPDATE statement(s)...

A: Here's a solution in PHP:
<?php

// edit this line to add old and new terms which you want to be replaced
$search_replace = array( 'old_term' => 'new_term', 'old_term2' => 'new_term2' );

//change the localhost,username,password and database-name according to your db
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database-name") or die(mysql_error());

$show_tables = mysql_query( 'SHOW TABLES' );
while( $st_rows = mysql_fetch_row( $show_tables ) ) {
    foreach( $st_rows as $cur_table ) {
        $show_columns = mysql_query( 'SHOW COLUMNS FROM ' . $cur_table );
        while( $cc_row = mysql_fetch_assoc( $show_columns ) ) {
            $column = $cc_row['Field'];
            $type = $cc_row['Type'];
            if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
                foreach( $search_replace as $old_string => $new_string ) {
                    $replace_query = 'UPDATE ' . $cur_table .
                        ' SET ' .  $column . ' = REPLACE(' . $column .
                        ', \'' . $old_string . '\', \'' . $new_string . '\')';
                    mysql_query( $replace_query );
                }
            }
        }
    }
}
echo 'replaced';
mysql_free_result( $show_columns );
mysql_free_result( $show_tables );
mysql_close( $mysql_link );

?>

Source


text:
Q: Grab object from MongoDB but limit number of items pulled from array My API currently has a route for Getting an event from my MongoDB database based on event_id. This works fine. However, I have a 'photos' array within this event object that is growing (currently over 3,000 objects within this array).
I want to pass a limit parameter to limit the number of results pulled from this array, but cannot figure out how. Below is my current node route and mongoDB schema:
route:
// get event by _id
app.get('/api/events/:event_id', function(req, res) {

    // use mongoose to get event
    Event.findOne({object_id: req.params.event_id}, function(err, event) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)

        if (req.params.limit >= 0) {
            // res.jsonp(event) with photos array limited to req.params.limit
        }

        res.jsonp(event); // return event in JSON format
    });
});

schema:
var eventSchema = new Schema({
event: String,
city: String,
state: String,
date: String,
start: String,
end: String,
dateState: String,
radius: String,
team_1: String,
team_2: String,
object_id: String,
longitude: String,
latitude: String,
cover: {
    img: String,
    username: String
},
photos: []

})

A: Event.findOne({object_id: req.params.event_id})
    .limit(10)
    .exec(function(e,doc){
        ...
});

Edit
Or if you have ref on the photo... you can populate the doc array of referenced id with limit option. Hope it helps :) All abount population
.find(...)
.populate({
     path: 'photos',
     options: { limit: 5 }
})
.exec(...)

Schema
var eventSchema = new Schema({
event: String,
city: String,
state: String,
...
photos: [{ type:String, ref:'pictureSchema' }]
}

var pictureSchema = new Schema({
name : {type:String},
url : {type:String},
...
}

In photos array than you just put id of the pictures doc, when you populate the photos array it will put pictureSceham doc insted of _id.

A: Don't have a constantly growing array field. It's not good for performance because MongoDB (well, if <= 2.6/using mmap) will be moving the document around when it grows outside of the space allocated for it by the storage engine, causing performance problems. You should change your schema to avoid an array like this, but I can't really say more about how you should do it because I don't know much about your use case.
There is a way to limit the number of array elements returned in a find query though, using $slice projection.
> db.test.drop()
> db.test.insert({ "_id" : 0, "x" : [0, 1, 2, 3, 4] })
> db.test.find({ "_id" : 0 }, { "x" : { "$slice" : 2 } })
{ "_id" : 0, "x" : [0, 1] }


text:
Q: fix The caller does not have permission to execute the specified operation flutter firestore :
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation
Firestore rule allow write and read


text:
Q: Switch scope between the browser and dev tools (normal pane and mini console) with keyboard In Chrome, when using the dev tools, I sometimes want to switch between the actual bowser window, and the dev tools window.   What keyboard shortcut exists if at all? Currently I have to click on on window to switch scope.

A: You can find all DT shortcuts written down in the Settings -> Shortucts menu (open DT settings by clicking on the 'cog' icon) and in the docs. Unfortunately, there is no shortcut for switching between Chrome and DT.
However, if you have Chrome and DevTools in separate windows you should be able to switch between them using 'cycle between open windows' feature (available on most OSes):

*

*Windows

*OSX

*Ubuntu


text:
Q: Bind value and class to Ember.TextField i'm trying to bind two attributes to an Ember textfield, but it doesn't work.
{{input type="text" value=name class="uk-width-1-1" placeholder="Name" required="" }}

How can I bind an "error" class to this textfield when errors.name is true?

A: what you are looking to do is as follows:
{{input type="text" value=name classBinding=":uk-width-1-1 errors.name:error" placeholder="Name" required=""}}

there is no need for a computed property here as long as error.name is truely a boolean value. in classBindings :uk-width-1-1 will always print and error will only be there if errors.name is true.
Just for reference, say you had a error and non-error class you wanted to use. You could do errors.name:error:non-error which would have error when errors.name is true and non-error when it is false.

A: You could change it to:
{{input type="text" value=name classBinding="textFieldClasses" placeholder="Name" required="" }}

end in your view define a computed property along the lines of:
textFieldClasses: function() {
    var class = "uk-width-1-1";
    if (this.get('controller.content.errors.name')) class += "error";
    return class;
}.observes('controller.content.errors.name'),


text:
Q: Enum pointer parameter in C I'm writing some testing functions for a project. The test function takes a function pointer, an expected value and a test value and checks them:
int TestIntInIntOut(int (*func)(int val), int expected, int testvalue);

However, I'm also testing functions which can take an enum as a parameter or as an exit value.
Suppose the following:
typedef enum { Zero, One, Two } MyEnum;

Is there a way I can pass an entire enum as a type? For any enum. For example:
int TestIntInEnumOut(?enum? (*func)(int val), ?enum? expected, int testvalue);

or
int TestEnumInIntOut(int (*func)(?enum? val), int expected, ?enum? testvalue);

(Sort of like what a generic in C# would allow.)

A: Do you mean any enum, or just MyEnum?
If you only need a function to support MyEnum, you could do:
int TestEnumInIntOut(int (*func)(MyEnum val), int expected, MyEnum testvalue);

Otherwise you probably can't do it in C, with much type safety.  But an enum is essentially the same as an int, so you could just treat them all as int types.  If the type safety is necessary, consider providing different integer value ranges for different enum types.

A: Not directly an answer to your question, however as you said you are writing some test functions: You might want to have a look at googletest or cppunit - could save you some trouble.


text:
Q: UIColectionView with a UILable with sizeToFit I have a UILabel in a UICollectionViewCell in a class named CollectionViewCell its all working. But the problem comes when the UILabel is smaller than the text I want to put in.
I've already made the [cell.label sizeToFit]; in the cellForItemAtIndexPath.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

   NSDictionary *news = [self.select objectAtIndex:indexPath.row];

   CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

   cell.label.text = [news objectForKey:@"content"];
   [cell.label setFont:[UIFont systemFontOfSize:15]];
   cell.label.numberOfLines = 0;
   [cell.label sizeToFit];
   cell.label.preferredMaxLayoutWidth = 292.f;
   return cell;
}

Already made the constraints like this answers https://stackoverflow.com/a/16009707/2577738 and it works only with the 7 first cells, the others just have a height of 29, here's the code that I implemented to make size of the cell variable.
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    int h = 29 + cell.label.frame.size.height;
    return CGSizeMake(292, h);
}

this is the result in some it worked

A: If this is with a UICollectionViewFlowLayout, you must implement collectionView:layout:sizeForItemAtIndexPath:. That is where you must do your measurement.
The modern technique is to use auto layout constraints and call systemLayoutSizeFittingSize: to work out the cell size for you. Here's actual code:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    self.modelCell.lab.text = self.sectionData[indexPath.section][indexPath.row]
    var sz = self.modelCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
    sz.width = ceil(sz.width); sz.height = ceil(sz.height)
    return sz
}

Note that this means you must supply the content of the label in both collectionView:layout:sizeForItemAtIndexPath: (to do the measurement) and in cellForItemAtIndexPath: (to make the label contents appear in the actual cell).


text:
Q: Why are boxed vectors so slow? I am trying to get amortized O(n) time concatenation of vectors. It seems to be working but if I need to store boxed values (such as vectors) the result is still very slow.
import qualified Data.Vector as V
import qualified Data.Vector.Generic.Mutable as GM
import Data.Vector(Vector)
import Control.Monad.State.Strict
import Control.Monad.ST

data App = S !(Vector Int) !Int deriving (Show)

main = do
  x <- liftM (map read . words) getContents
  print $ execState (mapM_ (add . V.singleton) x) (S V.empty 0)

add :: Vector Int -> State App ()
add v1 = do
    S v2 n <- get
    let v3 = vectorGrowAdd v1 v2 n
    put (S v3 (n + V.length v1))

vectorGrowAdd v1 v2 n = runST $ do
  m1 <- V.unsafeThaw v1
  m2 <- V.unsafeThaw v2
  m3 <- if GM.length m2 > (GM.length m1 + n)
         then do
           return m2
         else do
           GM.unsafeGrow m2 (GM.length m1 + 2*(GM.length m2))
  let copyTo = GM.unsafeSlice n (GM.length m1) m3
  GM.unsafeCopy copyTo m1
  V.freeze m3

In this example, testVals is a text file with 100000 integers, Boxed.hs is the code above and Unboxed.hs is the same as Boxed.hs except for importing Data.Vector.Unboxed instaid of Data.Vector.
> ghc -v
Glasgow Haskell Compiler, Version 7.0.3
> ghc --make -O2 Boxed.hs
> time (cat testVals | ./Boxed.hs)
  ...
  real      1m39.855s
  user      1m39.282s
  sys       0m0.252s
> ghc --make -O2 Unboxed.hs
> time (cat testVals | ./Unboxed.hs)
...
real        0m4.372s
user        0m4.268s
sys         0m0.088s

My question is: Why is there such a drastic difference between Unboxed and Boxed? Is there something I can do to improved the speed if I need to store values that can't be unboxed?

A: I'm not sure why it has such a dramatic impact on boxed Vectors, but you're wasting a lot of time in
V.freeze m3

That creates a copy of m3 each time. So you're copying 100,000 Vectors of increasing length. You don't need the old ones anymore, so they're garbage-collected. Garbage collection of boxed Vectors takes much longer than collection of unboxed Vectors because all pointers have to be followed to see whether the pointees can be collected too. I'm a bit surprised by how much difference it makes, though.
A few stats:
$ cat ./testVals | ./OldBoxed +RTS -t > Bxd.txt
<<ghc: 72590744976 bytes, 79999 GCs, 5696847/15655472 avg/max bytes residency (16 samples),
802M in use, 0.00 INIT (0.00 elapsed), 36.97 MUT (37.01 elapsed), 52.60 GC (52.67 elapsed) :ghc>>
$ cat ./testVals | ./OldUnboxed +RTS -t > UBxd.txt
<<ghc: 72518297568 bytes, 78256 GCs, 1013955/2294848 avg/max bytes residency (63 samples),
81M in use, 0.00 INIT (0.00 elapsed), 9.14 MUT (9.16 elapsed), 0.60 GC (0.60 elapsed) :ghc>>

So you see that the enormous difference is due to GC, althogh MUT (the time your programme does actual work) is far lower for unboxed, too.
Now, if we replace the offending freeze by unsafeFreeze, we get
$ cat ./testVals | ./Boxed +RTS -t > Bxd.txt
<<ghc: 1149880088 bytes, 2214 GCs, 5236803/17102432 avg/max bytes residency (11 samples),
39M in use, 0.00 INIT (0.00 elapsed), 0.53 MUT (0.53 elapsed), 0.29 GC (0.29 elapsed) :ghc>>
$ cat ./testVals | ./Unboxed +RTS -t > UBxd.txt
<<ghc: 1152277200 bytes, 2229 GCs, 767477/2267200 avg/max bytes residency (31 samples),
7M in use, 0.00 INIT (0.00 elapsed), 0.61 MUT (0.62 elapsed), 0.04 GC (0.04 elapsed) :ghc>>

which exposes a far smaller difference. In fact, here the boxed Vector needed less mutator time than unboxed. The GC time is still much higher, though, so overall unboxed still is faster, but at 0.66s vs 0.82s, it's nothing dramatic.


text:
Q: Probability of a point taken from a certain normal distribution will be greater than a point taken from another? Let's say I have one point that will be taken randomly from a normal distribution with mean $\mu_1$ and standard deviation $\sigma_1$.  Let's say I have another point that is taken much in the same way from another normal distribution with mean $\mu_2$ and standard deviation $\sigma_2$;.
How can I compute the probability, given $\mu_1$, $\mu_2$, $\sigma_1$, and $\sigma_2$, that my first point will be larger than the second?
I am sort of interested in the reasoning behind an "analytic" answer (or as analytic as you can possibly get with the normal distribution, which isn't that much), but I am more importantly looking for an algorithm of computing this probability, as it will be used in a simulation/model.
Does anyone know where I could get started on reasoning through this?
Note: For actual computation, having a table of values of the % of the curve within a given multiple of the standard deviation is feasible in my situation.

A: Suppose that $X_1 \sim {\rm N}(\mu_1,\sigma_1^2)$ and $X_2 \sim {\rm N}(\mu_2,\sigma_2^2)$ are independent. Then,
$$
{\rm P}(X_1  > X_2 ) = {\rm P}(X_1  - X_2  > 0) = 1 - {\rm P}(X_1  - X_2  \le 0).
$$
Now, by independence, $X_1 - X_2$ is normally distributed with mean
$$
\mu := {\rm E}(X_1 - X_2) = \mu_1 - \mu_2
$$
and variance
$$
\sigma^2 := {\rm Var}(X_1 - X_2) = \sigma_1^2 + \sigma_2^2.
$$
Hence,
$$
\frac{{X_1  - X_2  - \mu}}{{\sigma}} \sim {\rm N}(0,1),
$$
and so
$$
{\rm P}(X_1  - X_2  \le 0) = {\rm P}\bigg(\frac{{X_1  - X_2  - \mu }}{\sigma } \le \frac{{0 - \mu }}{\sigma }\bigg) = \Phi \Big(  \frac{-\mu }{\sigma }\Big),
$$
where $\Phi$ is the distribution function of the ${\rm N}(0,1)$ distribution. Thus,
$$
{\rm P}(X_1  > X_2 )  = 1 - {\rm P}(X_1  - X_2  \le 0) = 1 - \Phi \Big(  \frac{-\mu }{\sigma }\Big).
$$


text:
Q: drop-shadow CSS function makes app laggy in Firefox mobile I'm making a pomodoro clock in React and apply an animated filter: drop-shadow on an svg circle timer to make it look like it pulses.
This works fine on my Firefox desktop browser, but it makes my whole app laggy on Firefox mobile on my Android device. The app works fine on the Chrome mobile browser.
I noticed the app is still laggy even if I remove the animation and only apply a static filter: drop-shadow to the svg element. Is there a fix for this, or perhaps another way to achieve the effect I want?
Here is a codesandbox link for my app.
The relevant svg code is in PomodoroTimer.jsx, or here:
    <svg width="17em" height="17em" viewBox="0 0 20em 20em">
      <circle
        cx="8.5em"
        cy="8.5em"
        r="5.8em"
        fill="none"
        stroke="#FFF"
        strokeWidth=".05em"
      />
    </svg>
    <svg
      className="pulse"
      width="17em"
      height="17em"
      viewBox="0 0 20em 20em"
    >
      <circle
        cx="8.5em"
        cy="8.5em"
        r="5.8em"
        fill="none"
        stroke="#FFF"
        strokeWidth=".2em"
        strokeDasharray="36.442em"
        strokeDashoffset={36.442 * this.props.offsetModifier + "em"}
      />
    </svg>

And the relevant CSS is in PomodoroTimer.css, or here:
svg {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  transform: rotate(-90deg);
}

@-webkit-keyframes svg_pulse {
  0% {
    filter: drop-shadow(0 0 0.5em #fff);
  }
  50% {
    filter: drop-shadow(0 0 1.5em #fff);
  }
  100% {
    filter: drop-shadow(0 0 0.5em #fff);
  }
}

@keyframes svg_pulse {
  0% {
    filter: drop-shadow(0 0 0.5em #fff);
  }
  50% {
    filter: drop-shadow(0 0 1.5em #fff);
  }
  100% {
    filter: drop-shadow(0 0 0.5em #fff);
  }
}

.pulse {
  -webkit-animation: svg_pulse 3s linear infinite;
  animation: svg_pulse 3s linear infinite;
}


text:
Q: `npm install` is installing dozens of dependencies My package.json only has express, mongodb, and pug listed as dependencies. When I delete my node_modules folder and run npm install in the root of my app, it installs 51 dependencies (shown below). not sure what is going on...

A: npm v3 dependency resolution works that way and might install "some secondary dependencies (dependencies of dependencies) in a flat way".
You can also refer to this stackoverflow question.


text:
Q: Animation from edittext to listview row in android I am working on animation in android and got stuck when try to do this animation.
I have an edittext and listview. User type message in edittext and press Ok. The message written in edittext is appended in listview. I want to translate the message from edittext to the position where it is going to attach in listView.
I am using this animation in getView method of listview. I am only doing animation on last item of listview when it is adding in listView
<translate
android:fromXDelta="-80%" android:toXDelta="0%"
android:fromYDelta="2000%" android:toYDelta="0%"
android:duration="800" />

getView method animation code
//shouldAnimate is true only when getView is called during messageAdding in listView
    if(position == getCount() -1 && shouldAnimate) {
    v.startAnimation(animation);
    shouldAnimate = false;
}

I think it can to be done by translate animation where it's source and destination position changes for different views. I am not sure show to calculate initial and final coordinates for translate animation
Thanks in advance


text:
Q: Как в woocommerce изменить стоимость продукта на странице оформления заказа? На странице checkout есть дополнительные поля, которые влияют на конечную стоимость товара.
Я бы хотел динамически изменять общую стоимость в зависимоси от заполненных полей.
Если использовать ниже приведённый хук, то работает, но не совсем так как бы хотелось.
add_action('woocommerce_before_calculate_totals', 'set_custom_price', 50);

function set_custom_price() {
  if ( is_admin() && ! defined( 'DOING_AJAX' ) )
  return;
  $getcart = WC()->cart->get_cart();
  foreach ( $getcart as $cart_item_key => $cart_item ) {
     $cart_item['data']->set_price( $price );
  }
}

Есть ли способ динамически менять стоимость используя AJAX?
Пробовал так:
    $('#my-btn').click(function(){
        $.ajax({
            url: 'https://colis.by/wp-admin/admin-ajax.php',
            type: 'POST',
            data: {
                action: 'my-action',
                sum: '120'
            },
            beforeSend: function( xhr ) {
                $('#my-btn').text('Загрузка, 5 сек...');
            },
            success: function( data ) {
                $('#my-btn').text('Отправить');
                console.log( data );
                $(document.body).trigger("update-order-review");
            }
        });

    });

add_action( 'wp_ajax_my-action', 'test_function' );
add_action( 'wp_ajax_nopriv_my-action', 'test_function' );

function test_function(){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
   return;

     $sum = $_POST['sum'];

     $getcart = WC()->cart->get_cart();
       foreach ( $getcart as $cart_item_key => $cart_item ) {
         $cart_item['data']->set_price( $sum );
         print_r($cart_item['data']);
       }
    die;
}

В правильном ли направлении я двигаюсь? Есть ли у кого какие-нибудь идеи как мне получить ожидаемый результат?

A: Решил свою проблему добавлением переменной в сессию
add_action( 'wp_ajax_my-action', 'test_function' );
add_action( 'wp_ajax_nopriv_my-action', 'test_function' );

function test_function(){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

     $sum = $_POST['sum'];

     WC()->session->set( 'fee_sum', $sum );

    die;
}

add_action('woocommerce_before_calculate_totals', 'set_custom_fee', 50);

function set_custom_fee( $cart ) {
  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

   $sum = WC()->session->get( 'fee_sum' );

   if ( $sum && $sum > 0) {
      $cart->add_fee( 'Дополнительная стоимость', $sum );
   }
}


text:
Q: What on earth is $ \mathcal{O} (\mathbb{C})$? What on earth is $ \mathcal{O} (\mathbb{C})$?
I used this in a project I hastily put together and now I cannot remember the definition of it. I checked in as many books as I still had with me and this symbol doesn't appear in any of them. But when I looked at the source Classical Topics in Complex Function Theory, Volume 177 in Google Books I found only a piece of the puzzle as I couldn't look at the other pages anymore:

For every region $D \in \mathbb{C}$, let $\mathcal{O}(\bar D)$ denote the set of all functions that are holomorphic in the open neighborhood $ \bar D = D \cup \delta D$

Am I right to assume that $\mathcal{O} (\mathbb{C})$ is just a symbol representing the set of all holomorphic functions in $\mathbb{C}$?


text:
Q: How to know the configured size of the Chronicle Map? We use Chronicle Map as a persisted storage. As we have new data arriving all the time, we continue to put new data into the map. Thus we cannot predict the correct value for net.openhft.chronicle.map.ChronicleMapBuilder#entries(long). Chronicle 3 will not break when we put more data than expected, but will degrade performance. So we would like to recreate this map with new configuration from time to time.
Now it the real question: given a Chronicle Map file, how can we know which configuration was used for that file? Then we can compare it with actual amount of data (source of this knowledge is irrelevant here) and recreate a map if needed.

A: entries() is a high-level config, that is not stored internally. What is stored internally is the number of segments, expected number of entries per segment, and the number of "chunks" allocated in the segment's entry space. They are configured via ChronicleMapBuilder.actualSegments(), entriesPerSegment() and actualChunksPerSegmentTier() respectively. However, there is no way at the moment to query the last two numbers from the created ChronicleMap, so it doesn't help much. (You can query the number of segments via ChronicleMap.segments().)
You can contribute to Chronicle-Map by adding getters to ChronicleMap to expose those configurations. Or, you need to store the number of entries separately, e. g. in a file along with the ChronicleMap persisted file.


text:
Q: How to use for, find and wildcard in a Makefile? I am trying to do the following without any success so far:
remove:
    for file in $(shell find src/ -name migrations -type d); do rm $(wildcard "$(file)/0*.py"); done

A: If I understood well, you want to remove all files named:
src/**/migrations/0*.py

where ** can be anything, including nothing at all. find can do this alone:
find src -path '*/migrations/0*.py' -delete

And as make recipes are just bare shell, you do not need $(shell... or anything like this:
remove:
    find src -path '*/migrations/0*.py' -delete

But before running this potentially dangerous rule, you should maybe use this one until you are satisfied:
remove:
    find src -path '*/migrations/0*.py' -ok rm {} \;

The only difference is that it will ask you confirmation before deleting files. We can also make all this a bit easier:
remove-safe: DELCMD := -ok rm {} \\;
remove-unsafe: DELCMD := -delete
remove-dry-run: DELCMD := -print

remove-safe remove-unsafe remove-dry-run:
    find src -path '*/migrations/0*.py' $(DELCMD)

Use one or the other goal depending of what you want:

*

*remove-dry-run to print the list of files that would be deleted without deleting them,

*remove-safe to delete the files with confirmation,

*remove-unsafe to delete the files without confirmation.

EDIT 1: if this an exercise about loops and make, just remember that make recipes are shell scripts (one per line) that are first expanded by make and next passed to the shell. So:

*

*If you want to use shell variables, use them in one single line (but you can break lines with a trailing \). Else they will be from different shell invocations and it will not work as expected.

*If you use the $ sign in your recipe for shell expansion, double them to escape the first expansion by make.

In the following I assume that you do not have directory or file names with spaces or special characters. If you do, it is time to ask a question about your shell.
So, with the bash shell, for instance, we can first build an array of target directories and then loop over them to delete the files:
SHELL := bash

remove:
    dirs=( $$(find src -type d -name migrations) ); \
    for d in "$${dirs[@]}"; do \
        rm -f "$$d"/0*.py; \
    done

EDIT 2: you could also use the builtin make loop system with one (phony) clean target per directory.
DIRS := $(shell find src -type d -name migrations)

clean-targets := $(addprefix clean-,$(DIRS))

.PHONY: remove $(clean-targets)

remove: $(clean-targets)

$(clean-targets): clean-%:
    rm -f "$*"/0*.py

The tricky part is the:
$(clean-targets): clean-%:
    rm -f "$*"/0*.py

rule. It is equivalent to one rule per migrations directory that would be:
clean-DIR: clean-%:
    rm -f "$*"/0*.py

where DIR is the directory path. And these rules are static pattern rules. In the recipe the $* make automatic variable is expanded by make as the stem of the clean-% pattern. So, if DIR is src/foo/bar/migrations, the rule for it is equivalent to:
clean-src/foo/bar/migrations:
    rm -f src/foo/bar/migrations/0*.py

The main advantage of this style over the shell loop is that make can run all recipes in parallel. If you have hundreds of migrations directories and if you have 8 or 16 cores on your computer, it can really make a difference. Just try:
make -j1 remove
make -j16 remove

and you will see the difference.

A: The short answer is you can't do that.
It's critical when writing makefile recipes to be clear in your own understanding of how they work: first, make will expand all make variables and functions.  Then, make will pass the resulting string to the shell to be run.  Finally, make waits until the shell completes and examines the exit code to find out whether it succeeded or not.
Here you're trying to use a shell for loop where the body of the loop invokes a make wildcard function.  This cannot work.
Consider what you are wanting make (and the shell) to do: the shell would run its for loop, then every time it executed the body of the loop it would communicate back to make the value of some shell variable and make would expand the make wildcard function using that variable, then return the results to the shell for more processing.  This is simply not possible.
Best is to write the recipe using shell constructs.  A good rule of thumb is that it's never a good idea to use make's shell function inside a recipe: the recipe is already being run in a shell, so you don't need the shell function at all.  It's simply confusing.  Similarly, you rarely need make's wildcard function in a recipe because the shell does file globbing for you automatically.
I would write this as:
remove:
        find src/ -name migrations -type d | while read -r dir; do rm "$$file"/0*.py; done

Note we have escaped $$file with two dollar signs to keep make from expanding it as a make variable.


text:
Q: how to navigate to multiple pages Webscrap by beautiful soup when page no is encrypted? i used to web scrape a site which cantains 1000 pages and i wused to traverse each page with page no as 1,2,3...1000 and download data in excel now they have encrypted the page no. so code is no working need help. url is coming like this now
https://bidplus.gem.gov.in/bidlists?bidlists&page_no=Hgw0LYpSZdLXow1Wq84uKar1nxXbFhClXQDuAAiPDxU
code is written below.
pagination html

 code
import concurrent
import functools
import concurrent.futures
import requests
from urllib3.exceptions import InsecureRequestWarning
import csv

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from bs4 import BeautifulSoup as bs

def download_page(session, page_no):
    url = 'https://bidplus.gem.gov.in/bidlists?bidlists&page_no=' + str(page_no)
    print('URL created: ' + url)
    resp = session.get(url, verify=False)
    return resp.text

def scrap_bid_data():
    NUMBER_THREADS =5 # number of concurrent download requests
    with open('GEMconcurrent_1016.csv', 'w', newline='') as out_file:
        f = csv.writer(out_file)
        f.writerow(['Bidnumber', 'Items', 'Quantity', 'Department', 'Enddate','pageNumber'])
        with requests.Session() as session:
            page_downloader = functools.partial(download_page, session)
            with concurrent.futures.ThreadPoolExecutor(max_workers=NUMBER_THREADS) as executor:
                pages = executor.map(page_downloader, range(1,10))
                page_no = 0
                for page in pages:
                    page_no += 1
                    soup_data = bs(page, 'lxml')
                    extracted_data = soup_data.find('div', {'id': 'pagi_content'})
                    if extracted_data is None or len(extracted_data) == 0:
                        print('No data at page number', page_no)
                        print(page)

                    else:
                        for idx in range(len(extracted_data)):
                            if (idx % 2 == 1):
                                bid_data = extracted_data.contents[idx].text.strip().split('\n')
                                if (len(bid_data)>1):
                                    print(page_no)
                                    if (len(bid_data[8]) > 1 and len(bid_data[10].split(':'))>1 ):

                                                            bidno = bid_data[0].split(":")[-1]
                                                            items = bid_data[9].strip().split('Items:')[-1]
                                                            qnty = int(bid_data[10].split(':')[-1])
                                                            dept = (bid_data[11] + bid_data[16].strip()).split(":")[-1]
                                                            edate = bid_data[21].split("End Date:")[1]
                                                            f.writerow([bidno, items, qnty, dept, edate,page_no])
scrap_bid_data()


text:
Q: Unable to change timestamp to date time {
"meeting": {
"queue": "Waiting in line",
"template": "The Technical Template"
},
"assignee": "John Snow",
"type": "Auto",
"timestamps": [
{
"starttime": 1616358840,
"future": "yes"
},
{
"endtime": 1616361540,
"future": "yes"
}
],
"name": "Chili Piper Technical Call",
"meeting_id": "30075445"
}
Question is:
Based on the configuration, when does the meeting start in PST? What is
the meeting duration?
Any help will be greatly appreciated.

A: GMT:
Start: Sun Mar 21 2021 20:34:00 GMT+0000
End: Sun Mar 21 2021 21:19:00 GMT+0000
Duration: 45min
PST=GMT-8
or something like this:
 db.collection.aggregate([
 {
  $project: {
  timestamps: {
    "$mergeObjects": "$timestamps"
  }
}
},
{
  $project: {
  startTime: {
    $toDate: {
      $multiply: [
        {
          $add: [
            "$timestamps.starttime",
            -28800
          ]
        },
        1000
      ]
    }
  },
  endTime: {
    $toDate: {
      $multiply: [
        {
          "$add": [
            "$timestamps.endtime",
            -28800
          ]
        },
        1000
      ]
    }
   }
  }
 },
 {
   $project: {
   _id: 0,
   startTime: 1,
   endTime: 1,
   durationMinutes: {
    $divide: [
      {
        $subtract: [
          "$endTime",
          "$startTime"
        ]
      },
      60000
    ]
   }
  }
 }
 ])

result in PST:
{
"durationMinutes": 45,
"endTime": ISODate("2021-03-21T13:19:00Z"),
"startTime": ISODate("2021-03-21T12:34:00Z")
}

explained:

*

*merge the start & end timestamps in single object.

*Convert the GMT unix timestamp-PST offset(8x60x60)  to ISODate

*Project the start and end ISODate and calculate the duration in minutes.

playground


text:
Q: Customized Back button for UINavigation bar I have referred to quite a few threads (How do I change the title of the "back" button on a Navigation Bar ,  NavigationController UINavigationBar Back Button  and few others) on customizing text in back button to show desired string. However, they do not use storyboard. So many of them are not applicable.
In order to give you a background, I have created my views (view1 and view2) through storyboard and I would like to use a back button on view2 to navigate to view1. How can I do this using IB?
Alternatively, I also tried setting self.navigationItem.backBarButtonItem.title to @"Custom text";, but this does not work as well.
Can somebody please suggest how can I change the text of Back button on view2? Thanks!

A: I found the solution to my question. The method described below will let you change the text of back button without changing the title of the parent view controller.

*

*Open the storyboard file and click on the link connect the two viewControllers.

*Open the Utilities pannel and click on Attributes inspector.

*Give storyboard segue a meaningful identifier. (For the sake of this example, I call it saveReturn.) Hit enter to accept.

*Open the .m file of the parent view controller and insert the code.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"saveReturn"])
{
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Save & Return" style: UIBarButtonItemStyleBordered target:nil action:nil];
}
`}

A: I know it is an old question - but for completeness:
The storyboard way of doing it (personally I like to do as much as possible in Storyboard):
In the view before the one with the back button you want to change (i.e. the destination of the back button you are changing) select the navigation bar and in the Attributes inspector change the value of the "Back Button" field (this is also where you can change the name of the view) - see below.

A: Here is the storyboard solution:
In prepareForSegue set the title of the view controller to the short title that fits onto the back button:
MyViewController *mvc = segue.destinationViewController;
mvc.title = @"Docs";

To change it back, do the reverse in viewWillAppear:
self.title = @"Important Documents";

A: I am not familiar with Storyboards.
However, usually, the trick is

*

*Right before switching from view1 to view2, set the title of your view1 as you want it on the back button of your view2
[ViewController1 setTitle:@"The text I want in the back button of view2"];

*When you switch back to view1 you do not want this title. Hence, in the implementation of the viewcontroller of your view1, you override:
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setTitle:@"The title I actually want in my view1"];
}
This way, when you switch from view1 to view2, you trigger the title you expect to appear on your back button. When you switch back from view2 to view1, you use the fact that view1 "will appear"!

A: You did not specify if view1 was the previous view of view2 in your question, but if that is what you are trying to do (use a custom title in the back button), then it's really easy to do right within the storyboard.
If you don't see the navigation bar in your storyboard, select your view controller for view1 in the storyboard, and in the Attributes Inspector, make sure the Top Bar has a Navigation Bar selected (instead of Inferred)
Select view1's navigation bar, then in the Attributes Inspector, you have 3 fields: Title, Prompt, and Back Button. If you add text to the Back button field, when you navigate to view2 from view1, the back button will use this text instead of the Title in the back button of view2.


text:
Q: What advantages does a Document-based database have over a Relational database? For example: Microsoft SQL Server vs. CouchDB.
The main benefit for me with CouchDB is that you can access it from pretty much anywhere! What advantages does a document based database have over a relational one?
Where would a document based db be a better choice over a relational?

A: I wouldn't say "accessing it from anywhere" is an advantage of CouchDB over SQL Server.  Both are fully accessible from a variety of clients.
The key differentiating factor is the fundamental concept of how data is persisted as tables & columns (SQL Server) versus documents (CouchDB).  In addition, CouchDB is designed to leverage multiple copies with replication/map-reduce in a highly forgiving fashion.  SQL Server can do the same level of fault tolerance but true map-reduce is non-existant in it (it's ability to deal with sets mimics the capabilities fundamentally however - see GROUPING SETS keyword).
You should note this post which really shows that map reduce has its place, but you need to pick the right tool for the job:
http://gigaom.com/2009/04/14/mapreduce-vs-sql-its-not-one-or-the-other/