text:
Q: Dialog with checkbox in Android I found example for dialog with checkbox:
final int DIALOG_ITEMS = 1;
    String data[] = { "one", "two", "three", "four" };
    @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button but1=(Button) findViewById(R.id.button1);
            but1.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View arg0)
                {
                     showDialog(DIALOG_ITEMS);
                }
            });
        }

        protected Dialog onCreateDialog(int id) {
            AlertDialog.Builder adb = new AlertDialog.Builder(this);

              adb.setTitle(R.string.items);
              adb.setSingleChoiceItems(data, -1, myClickListener);

          }

          OnClickListener myClickListener = new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              ListView lv = ((AlertDialog) dialog).getListView();
              if (which == Dialog.BUTTON_POSITIVE)
                Log.d(LOG_TAG, "pos = " + lv.getCheckedItemPosition());
              else
                Log.d(LOG_TAG, "which = " + which);
            }
          };

Eclipse atention about two errors:

1)
  setSingleChoiceItems(int, int, DialogInterface.OnClickListener) in the
  type AlertDialog.Builder is not applicable for the arguments
  (String[], int,
  View.OnClickListener) MainActivity.java   /master/src/com/example/hotdog_master   line
  98    Java Problem
2)
  View.OnClickListener(){} must implement the inherited abstract method
  View.OnClickListener.onClick(View)    MainActivity.java   /master/src/com/example/hotdog_master   line
  104   Java Problem

Could you help understend what is wrong?

A: Change your above code as below:
DialogInterface.OnClickListener myClickListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              ListView lv = ((AlertDialog) dialog).getListView();
              if (which == Dialog.BUTTON_POSITIVE)
                Log.d(LOG_TAG, "pos = " + lv.getCheckedItemPosition());
              else
                Log.d(LOG_TAG, "which = " + which);
            }
          };

You already imported View.OnClickListener for Button Click and eclipse is detecting the below onClickListener also as View.onClickListener(). So maintain differentiation by adding DialogInterface.OnClickListener

A: Change your OnClickListener as:
  DialogInterface.OnClickListener myClickListener = new
                                   DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              ListView lv = ((AlertDialog) dialog).getListView();
              if (which == Dialog.BUTTON_POSITIVE)
                Log.d(LOG_TAG, "pos = " + lv.getCheckedItemPosition());
              else
                Log.d(LOG_TAG, "which = " + which);
            }
          };

and Create AlertDialog.Builder  instance as:
AlertDialog.Builder adb = new AlertDialog.Builder(Your_Current_Activity.this);

EDIT :
Change your onCreateDialog method as:
protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);

      adb.setTitle(R.string.items);
      adb.setSingleChoiceItems(data, -1, myClickListener);

       AlertDialog dialog = builder.create();
       dialog.show();
      return super.onCreateDialog(id);  //<<<< add return here

  }


text:
Q: Css hover doesn't work with specific type of classes I'm working on a React project and I have button that is in Link (react-router dom). So to edit the css of the button i need to add "a." before the class:
<Link to={'/Register'} className="btn">Sign up</Link>

In the css:
a.btn {
background-color: var(--lighter-hover-color);
color: white;
padding: 10px 25px;
margin: 15px 0;
border: none;
cursor: pointer;
border-radius: 20px;
border: 1px solid var(--hover-color);
text-decoration: none;

}
So when i try to add hover function to this class:
a.btn :hover {
transform: scale(1.2);}

Nothing happens. So my question is is there any way i can make the hover to work. The problem i found is that when i have dot (.) , that makes the hover function unusable.

A: It is not working because you can not target Link react component using a tag.
I would just get rid of a.btn and just use btn:hover.
A better and more elegant approach to style react elements is to user either styled-components or css modules.
refer this article to learn more about different ways of styling react app
https://css-tricks.com/different-ways-to-write-css-in-react/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Server response time high when InnoDB tables active but not being accessed I am experiencing high server response time (up to 5 seconds) when loading every Webpage on my server, ONLY when MySQL InnoDB tables are running.
The 5 second delay occurs even on static HTML pages with no call to any MySQL data table (and no other users on the site accessing other InnoDB linked webpages).
As soon as the InnoDB is shutdown (MyISAM tables remain active), all pages (those that call DB or not) load very fast (including MyISAM tables) in about a second.
How could InnoDB be causing server wide slow response, even when not being accessed?

A: [SOLVED]
I enabled query_cache_type=1 and query_cache_size=256M.
The problem went away and the server response reduced from 6 seconds to 1 second. Very strange considering most recommend that Query cache should be disabled!


text:
Q: MVC Table values not displaying Controller
    public ActionResult Index(int? StaffID, int? id)
    {
        //var userEmail = User.Identity.Name;
        //var model = db.Staffs.Where(i => i.Email == userEmail).Include(x => x.Histories).Include(x => x.CurrentApplications).FirstOrDefault();
        //return View(model);

        var model = new LeaveIndexData();
        var userEmail = User.Identity.Name;

        model.Staffs = db.Staffs
            .Where(i => i.Email == userEmail);

        if(id != null)
        {
            ViewBag.StaffId = id.Value;
            model.CurrentApplications = model.Staffs
                .Where(i => i.StaffID == id.Value).Single().CurrentApplication;
        }

        return View(model);
    }

Index View
@model test.ViewModel.LeaveIndexData

@{
ViewBag.Title = "Index";
}

@*

    Last Name
    First Name
    Hire Date
    Office
    Courses

@foreach (var item in Model.Instructors)
{
    string selectedRow = "";
    if (item.ID == ViewBag.InstructorID)
    {
        selectedRow = "success";
    }

            @Html.DisplayFor(modelItem => item.LastName)

            @Html.DisplayFor(modelItem => item.FirstMidName)*@

    @Html.ActionLink("Create New", "Create")

@foreach (var item in Model.Staffs) {

            @Html.DisplayFor(modelItem => item.AllocatedLeave)

            @Html.DisplayFor(modelItem => item.BalanceLeave)

            @Html.ActionLink("Edit", "Edit", new { id=item.StaffID }) |
            @Html.ActionLink("Details", "Details", new { id=item.StaffID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.StaffID })

}

@if (Model.CurrentApplications != null)
{

Current Applications

        Start Date
        End Date
        Leave Type
        Period
        Application Status
        Leave Reason

    @foreach (var item in Model.CurrentApplications)
    {
        if(item.StaffID == ViewBag.StaffID)
        {

                @item.StartDate
                @item.EndDate
                @item.LeaveType
                @item.NoOfDays
                @item.AppStatus
                @item.LeaveReason

        }
    }

}

Staff Class
namespace test.Models
{
using System;
using System.Collections.Generic;

public partial class Staff
{
    public int StaffID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Nullable<decimal> AllocatedLeave { get; set; }
    public Nullable<int> BalanceLeave { get; set; }

    public virtual History History { get; set; }
    public virtual ICollection<CurrentApplication> CurrentApplication { get; set; }
}
}

I cannot figure out why my Current Applications table isn't displaying. If I remove the line @if (Model.CurrentApplications != null), I get this error:

Object reference not set to an instance of an object

Not sure if it's useful, but I'm using EntityFramework and my tables were generated from my database?

A: Solved it with this
Controller
    public ActionResult Index()
    {
        var model = new LeaveIndexData();
        var userEmail = User.Identity.Name;
        model.Staffs = db.Staffs.Single(i => i.Email == userEmail);
        var userID = model.Staffs.StaffID;

        model.CurrentApplications = db.CurrentApplications
            .Where(i => i.StaffID == userID)
            .ToList();

        model.Histories = db.Histories
            .Where(i => i.StaffID == userID).ToList();

        return View(model);
    }

Created a View Model called LeaveIndex Data
LeaveIndexData class
public class LeaveIndexData
{
    public Staff Staffs { get; set; }
    public ICollection<CurrentApplication> CurrentApplications { get; set; }
    public IEnumerable<History> Histories { get; set; }

    public IEnumerable<Staff> Staff { get; set; }
    public ICollection<CurrentApplication> DelCurrentApplications { get; set; }
}


text:
Q: Javascript Date() milliseconds difference not adding up I've created this JSFiddle to illustrate my question.
It seems that 10 - 00 = 8 in this example.
The simple question: Why does #ha contain 8? Have I misunderstood something?
var a4 = new Date(2012,00,00,00,00,00,0010);
var b4 = new Date(2012,00,00,00,00,00,0000);
var c4 = a4-b4;
var d4 = document.getElementById("ha");
d4.innerHTML=c4;

A: When an integer literal starts with 0 it is interpreted as an octal literal, not a decimal literal.  The literal 0010 has the same value as the literal 8 .  Remove the leading zeroes.

A: using a leading 0 on a number is a signal to the processor that you're using an octal (base 8) number the same way that 0x indicates hex.
0010 - 0 == 010 == 8 in base ten
10 - 0 == 10 == 10 in base ten
0x10 - 0 == 0x10 == 16 in base ten


text:
Q: Inverse Image and Tensor Product Given a morphism $f$ of Schemes $X \to Y$ and two sheaves $\mathcal F$, $\mathcal G$ of modules on $Y$,
is it right that the tensor product of $\mathcal F$ and $\mathcal G$ as modules commutes with the inverse image (not the module pullback but only the inverse image $f^{-1}$)
construction? Here I mean one time tensor product over $\mathcal O_Y$ and the other time over $f^{-1}\mathcal O_Y$.
Regards!

A: $\newcommand{mc}{\mathcal}$
I guess that the problem lies in all the sheafifications so let me explain how to get rid of them in some small independent steps which are of some interest on their own.
I denote by $\cdot^\#$ the sheafification.
The following two statements follow without difficulty by checking that the object in question has the right universal property (in particular there is no need to adhere to any construction of the sheafification):
i) Let $X$ be a topological space, let $\mc O$ be a presheaf of rings on $X$ and let $\mc M$ and $\mc N$ be presheaves of $\mc O$-modules. Then $(M\otimes^p_{\mc O}\mc N)^\#=M^\#\otimes^s_{\mc O^\#}\mc N^\#$, where the superscript of the tensor product indicates whether I mean the tensor product of sheaves or the one of presheaves.
ii) Let $f:X\to Y$ be a continuous map of topological spaces and let $\mc M$ be a presheaf of abelian groups on $Y$. Then $f^{-1,s}(M^\#)=(f^{-1,p}(M))^\#$, where the superscript to the pullback indicates whether I mean the one for sheaves or for presheaves.
Concerning your question (and using your notation): By ii) we have
$f^{-1,s}(\mc F\otimes^s_{\mc O_Y}\mc G)=(f^{-1,p}(\mc F\otimes^p_{\mc O_Y}\mc
G))^\#$. By i) we have $f^{-1,s}\mc F\otimes^s_{f^{-1,s}\mc O_Y}f^{-1,s}\mc
G=(f^{-1,p}\mc F\otimes^p_{f^{-1,p}\mc O_Y}f^{-1,p}\mc G)^\#$. Thus it suffices to show the
corresponding statement for presheaves. By the definition of $f^{-1,p}$ it follows from the
following fact: Let $(A_i)_{i\in I}$ be a direct system of rings and let $(M_i)_{i\in I}$ and
$(N_i)_{i\in I}$ be direct systems of $A_i$-modules. Then $\varinjlim
M_i\otimes_{\varinjlim A_i}\varinjlim N_i=\varinjlim (M_i\otimes_{A_i}N_i)$.

A: The tensor product $F \otimes G$ of sheaves of modules has the following universal property:
$\hom(F \otimes G,H) = \text{bilin}(F \times G,H)$
Here, the right hand side is the set of bilinear sheaf homomorphisms $F \times G \to H$. You should keep this in mind instead of the explicit construction involving sheafifications! The idea behind tensor products is not their construction, but rather that they classify bilinear maps. This idea is familiar from commutative algebra and should not be lost in algebraic geometry.
Now we also have a canonical identification
$\text{bilin}(F \times G,H) = \hom(F,\underline{\hom}(G,H))$.
The pullback $f^*$ has also a universal property, it is left adjoint to the pushforward $f_*$. Thus, we get:
$\hom(f^* F \otimes f^* G,-) \cong \hom(f^* F,\underline{\hom}(f^* G,-)) \cong \hom(F,f_* \underline{\hom}(f^* G,-))$
$\cong \hom(F,\underline{\hom}(G,f_* -)) \cong \hom(F \otimes G,f_* -) \cong \hom(f^* (F \otimes G),-)$
and the Yoneda lemma gives us $f^* F \otimes f^* G \cong f^* (F \otimes G)$.
PS: Try to prove $F \otimes (G \otimes H) \cong (F \otimes G) \otimes H$ using sheafifications and compare the proof with the one using trilinear maps.


text:
Q: Content Type IDs help I have 2 Content Types, A and B. I am trying to create Content Type ID's(not proper ID's) and completely separate from the ID already in the list. I am creating them as a calculated field but I cannot work out a formula to make it work.
Basically all I want is for it to be like this:
ID     A    B
1      1    1
2      2    2
3      3    3
4      4    4


text:
Q: OpenGL Minigolf Rendering and Physics: How to determine if a ball is in a specified tile A minigolf course is rendered through tiles; each tile has 3 or more vertices that defined its shape. We are given a ball and its starting position. Over time, this ball is meant to be acted on by Physics and reach the hole of the course.
If I have the following tile setup:
Tile 1: Vertices (-2.5, 0, 2.5) (-0.5, 0, 2.5) (-0.5, 0, 1.5) (-1.5, 0, 0.5) (-2.5, 0, 0.5)
Tile 2: Vertices (-0.5, 0, 2.5) ( 0.5, 0, 2.5) ( 0.5, 0, 1.5) (-0.5, 0, 1.5)
Ball: Vertex (-2.25, 0, 2)
Image is here:

My question here is how to check if the ball's position is within the boundaries of a Tile?
This is necessary because some tiles in the course are sloped, so appropriate physics calculations are necessary.
Note that the Tile numbers are defined in each tile. I have a tile struct that holds all its vertices and edges. A ball's position is also given to us. I don't have code to demonstrate because I don't know how to get started with this.
EDIT. I have been following the answer here How can I determine whether a 2D Point is within a Polygon?
and it seems to work fine as long as I check within x and z coordinates. However, in a blunder, I forgot there are certain golf holes in my project that will have overlapping tiles or bridges above one another; polygons that have the same x and z coordinates but different y values. This causes glitches in relation to my ball's movement. How can I go about a Ray Casting method like the link's answer and check for the tile's height given vertices?
I was thinking about taking the ball's current position's y component and comparing it to the average of the vertices that form a tile or polygon; if it was under that average, the ball was in that tile instead of the other. This doesn't work as intended. Please advise.


text:
Q: How to bind a NSLayoutConstraint's constant properly? I'm developing an app with Xamarin and MVVMCross and I'm having problems creating binding NSLayoutConstraints constants.
I have a view with a Subview that should "disapear" if a certain List<> has no elements, and the content below should move up instead of leaving it's space empty.
To do that I added an NSLayoutConstraint to this view to be able to modify it's height programmatically and I bind it with the following line of code:
var set = this.CreateBindingSet<ActivityView, ActivityViewModel> ();
set.Bind (ConstraintHeightPictures).To (vm => vm.Activity.ImageList.Count).For (cons => cons.Constant).WithConversion ("CountToConstraintHeight", Constants.HeightActivityImages);
set.Apply ();

The CountToConstraintHeightConverter is pretty simple, it just checks if the value is equal to 0 to return 0 or otherwise the default height value (Constants.HeightActivityImages).
The code gives no execution error and passes through the Converter but when I run the app, the View is still there, empty.
On the other hand if I run the following line of code inside ViewWillLayoutSubviews it works perfectly but it's not binded.
ConstraintHeightPictures.Constant = ViewModel.Activity.ImageList.Count > 0 ? Constants.HeightActivityImages : 0.0f;

Any ideas?
Many thanks in advance!
Jordi

A: I think the problem is that iOS needs you to call LayoutIfNeeded (or similar) after setting the constant.
e.g. in order to animate a constraint constant change, see Are NSLayoutConstraints animatable?
For binding, you could probably do this using a property on your View like:
public float PicHeight
{
     get { return ConstraintHeightPictures.Constant; }
     set {
         ConstraintHeightPictures.Constant = value;
         _pictureView.SetNeedsUpdateConstraints();
         UIView.Animate(0.25f, () => {
             _pictureView.LayoutIfNeeded();
         }
     }
}

This could then be bound as:
set.Bind (this).To (vm => vm.Activity.ImageList.Count).For (v => v.PicHeight).WithConversion ("CountToConstraintHeight", Constants.HeightActivityImages);

I think that should work... (and if you don't want animation then it should be easy to strip that out)
Alternatively... you might also be able to build a custom binding that would know how to do this change (although it might be a little complicated by the fact that it would need access to both the child view and the constraint)


text:
Q: All analytic functions $|f(z^2)|\geq |f(z)|$ Find all the analytic functions on the unit disk satisfying $|f(z^2)|\geq |f(z)|$
I need help for the problem. I guess we need to use Schwarz's lemma

A: We will show that $\lvert f(0)\rvert\geq \lvert f(z)\rvert$ for all $z$ in the open unit disk $\mathbb{D}$. Consider $z\in \mathbb{D}$, and note that $z^{2^k}\to 0$ as $k\to \infty$, as $\lvert z^{2^k}\rvert = \lvert z\rvert^{2^k}\to 0$ because $\lvert z\rvert < 1$. Then, as $f$ is analytic, $$\lim_{k\to \infty} f(z^{2^k}) = f(0)$$ As $\lvert f(z^{2^k})\rvert\geq \lvert f(z^{2^{k-1}})\rvert$ for all $k$, we have that $\lvert f(z^{2^k})\rvert$ increases monotonically (not necessarily strictly) to $\lvert f(0)\rvert$, so $\lvert f(0)\rvert\geq \lvert f(z)\rvert$. As this is true for all $z\in \mathbb{D}$, $f$ must be constant by the maximum modulus principle.

A: From the given condition it follows that
$$\sup_{0\le |z|\le 1/2} |f(z)|\le\sup_{0\le |z|\le 1/2} |f(z^2)|=\sup_{0\le |z|\le 1/4} |f(z)|.$$
Thus $|f|$ has a local maximum in $\{0\le |z|\le 1/4\}.$ By the maximum modulus theorem, $f$ is constant in $D(0,1).$


text:
Q: How to "Redirect to" after 'x' seconds using react-router-dom I'm beginner in React Js. I would like to redirect to path '/event' after 2 seconds.
This way is not working:
import React from 'react';
import { getFormData } from '../../../helpers/form';
import { eventCreate } from '../../../actions/EventActions';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';

if (event) {
  setTimeout(() => {
    return <Redirect to={'/event'} />;
  }, 2000);
}

But if I change it to:
if (event) {
  return <Redirect to={'/event'} />;
}

It works perfectly. How could I redirect after 2 seconds?

A: 2022 Update: While updating versions (React 18, React Router DOM 6) I noticed it required a bit of refactor.
import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

export default function myComponent () {
  const navigate = useNavigate()

  useEffect(() => {
    setTimeout(() => {
      navigate('/event')
    }, 2000)
  }, [])
  return
Content

}

2021 Update: After learning more about React, I'd probably recommend using useEffect to mimic the functionality of componentDidMount in a functional component.
import React, { useEffect, useHistory } from 'react'

export default function myComponent () {
  const history = useHistory()

  useEffect(() => {
    setTimeout(() => {
      history.push('/event')
    }, 2000)
  }, [])
  return
Content

}

Previous answer: Is your if (event) { inside a component of some sort? I think you could achieve this one of two ways. Either:
componentDidMount() {
  if (event) {
    setTimeout(() => {
      this.props.history.push('/event');
    }, 2000)
  }
}

Note, to use componentDidMount and this, you'll have to use a class component which I don't see in your example. Or:
class RedirectExample extends Component {
  state = {
    redirect: false
  }

  componentDidMount() {
    this.id = setTimeout(() => this.setState({ redirect: true }), 2000)
  }

  componentWillUnmount() {
    clearTimeout(this.id)
  }

  render() {
    return this.state.redirect
      ? <Redirect to='/event' />
      :
Content

  }
}

As requested in a comment, I modified this answer to include a refactor to functional component. Note, the following code is untested but should give you an idea of how you might accomplish it.
import React, { useState } from 'react'
import { Redirect } from 'react-router-dom'

function RedirectExample() {
  const [redirectNow, setRedirectNow] = useState(false)
  if (redirectNow) {
    return <Redirect to='/event' />
  }
  return
Content

}

Or possibly (I haven't used useHistory before but from the documentation you might be able to do something like this):
import React from 'react'
import { useHistory } from 'react-router'

function RedirectExample() {
  const history = useHistory()

  // setTimeout may cause an error
  setTimeout(() => {
    history.push('/event')
  }, 2000)
  return
Content

}

A: In Functional Component you can use useHistory() hook of React like the previous mentioned and it will work but in Class based component you may not be able to do the same thing using Hook. So, if you want to perform the task you can use a little trick by taking an extra state just like this:
 this.state={
    redirect: false
 }

if (event) {
  setTimeout(() => {
    this.setState({
       redirect: true
  }, 2000);
}

 render(){

    if(this.state.redirect){
       return <Redirect to='/event'/>
     }
 }

This may helpful for you.

A: This worked for me:
import { useState } from "react";
import { Redirect } from "react-router-dom";

function SplashScreen() {
  const [redirectNow, setRedirectNow] = useState(false);
  setTimeout(() => setRedirectNow(true), 2000);
  return redirectNow ? (
    <Redirect to="/game" />
  ) : (

Hello World

  );
}

export default SplashScreen;

A: import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

const RedirectComponent = () => {
  const [count, setCount] = useState(2);
  const navigate = useNavigate();
  useEffect(() => {
    const interval = setInterval(() => {
      // update the state after 1000ms
      setCount((currentCount) => currentCount - 1);
    }, 1000);
    // when count is 0, navigate
    count === 0 && navigate("/event");
    // clean up the interval
    return () => clearInterval(interval);
  }, [count, navigate]);
  return (

Redirecting you in {count} sec

  );
};


text:
Q: Rails 3: best way to preview image before upload I need to preview an image prior to submitting a form.
I work with Rails 3 and needs something that is browser compatible.
Any ideas how I can achieve that?

A: So! :) The main idea is to use the FileReader Javascript Class, which is really handy for what you need to do.
You just have to listen to the "change" event on your file input and then call a method that will use the "readAsDataURL()" method of the FileReader class. Then you just have to fill the source of a "preview img tag" with the returned result of the method...
I've wrote you a simple jsFiddle that achieves what you want. You can see my code below:

<input class="file" name="logo" type="file">

//JS File
$(document).ready(function(){
    var preview = $(".upload-preview img");

    $(".file").change(function(event){
       var input = $(event.currentTarget);
       var file = input[0].files[0];
       var reader = new FileReader();
       reader.onload = function(e){
           image_base64 = e.target.result;
           preview.attr("src", image_base64);
       };
       reader.readAsDataURL(file);
    });
});

And in the Mozilla Documentation, you have another example (surely more robust). This solution should work with Safari (version 6.0+).
This is the only way I know to preview an image prior to submitting a form, but I think it is quite a common way. Of course it has nothing to do with Ruby On Rails as we only use Javascript here... It would be impossible to do it using Rails only as you would have to upload the image before rendering it. (As Rails is server side, I think you perfectly understand why. :) )

A: HTML:
<input type="file">

JS (require jquery):
$(document).ready(function(){
   $('input[type="file"]').change(function(){
     var image = window.URL.createObjectURL(this.files[0]);
     $("#image_preview").css("background-image", "url(" + image + ")");
   });
});


text:
Q: Silverlight Combobox and Selected item problem The title may sound simple and dumb, but allow me to explain.
I am using WCF RIA Services to bind a combobox to a list of say, countries. The control housing the entire control os already bound to a datacontext, and the country is among the data in the context.
How can I go about binding the comboxbox's selected item to the country in the entire context, while the entire list is coming from the RIA Datasource in the xaml.
Code is as follows:
 <riaControls:DomainDataSource AutoLoad="True" LoadedData="countryDomainDataSource_LoadedData" x:Name="countryDomainDataSource" QueryName="GetCountriesQuery" VerticalAlignment="Top">
        <riaControls:DomainDataSource.DomainContext>
            <my:ApplyDataContext />
        </riaControls:DomainDataSource.DomainContext>
    </riaControls:DomainDataSource>

            <ComboBox x:Name="CountryCB" Grid.Column="1" Margin="10,3,92,4" Grid.Row="10" ItemsSource="{Binding Data, ElementName=countryDomainDataSource}" DisplayMemberPath="Country1" SelectedValuePath="{Binding NationalCountry}"  />

A: Problem solved. i, instead, bound the control to the actual item, then rebound it to the itemsource when the edit button was clicked.


text:
Q: How to check error in express listen callback? I have the following code to check whether there was an error starting Express:
express()
    .listen(port, (err: Error) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log(`Express started`);
    });

However, recently, I'm getting this error in Typescript compiler:

TS2345: Argument of type '(err: Error) => void' is not assignable to
  parameter of type '(() => void) | undefined'.

It seems like the callback function of listen() doesn't take in an error parameter. If this is the case, how should I check and handle errors when starting Express?

A: The Server object is a Node.js EventEmitter. As with all EventEmitters, most errors are passed to the 'error' event. So you can catch like this:
express().listen(port, () => {
   console.log('Listening on port: ', port);
}).on('error', (e) => {
   console.log('Error happened: ', e.message)
});

I hope this will be useful.


text:
Q: creating json value pair? I have 2 arrays of same length :
var arr1= ["1", "2", "3", "4", "5", "6", "7", "8"]
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"]

I want output like :
result = [{id:1,chan:discovery},{id:2,chan:nationalgeographic},{id:3,chan:hbo},{id:4,chan:wb},{id:5,chan:comedycentral},{id:6,chan:pogo},{id:7,chan:cnn},{id:8,chan:romedynow}]

Can someone please help me on this ?

A: Use map for that:
const newArr = arr1.map((item, index) => ({ id: item, chan: arr2[index] }));

A: You can simply achieve this by using Array.map().
Live Demo :

  var arr1= ["1", "2", "3", "4", "5", "6", "7", "8"];
  var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"];

  const result = arr1.map((item, index) => {
    return {id: item, chan: arr2[index]}
  });

  console.log(result);

A: var arr1= ["1", "2", "3", "4", "5", "6", "7", "8"];
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"];

let result = [];
for(let i = 0; i < arr1.length; i++) {
    let obj = {
    id: arr1[i],
    chan: arr2[i]
  }
  result.push(obj);
}

console.log(result);

A: I think you're looking for something like this.
var arr1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"]

var result = []

for (var i = 0; i < arr1.length; i++) {
    result.push({"id": arr1[i], "chan": arr2[i]})
}

console.log(result)

And the result I'm getting is
[ { id: '1', chan: 'discovery' },
  { id: '2', chan: 'nationalgeographic' },
  { id: '3', chan: 'hbo' },
  { id: '4', chan: 'wb' },
  { id: '5', chan: 'comedycentral' },
  { id: '6', chan: 'pogo' },
  { id: '7', chan: 'cnn' },
  { id: '8', chan: 'romedynow' } ]

Good luck!


text:
Q: Cannot access property from inside the class I made this function
    protected function createRecord(){
        var_dump($this->id);
        global ${DEFAULT_DATABASE};
        ${DEFAULT_DATABASE}->exec("INSERT INTO sessions SET id='{$this->id}',userid={$this->user->data->id}");
    }

This function is called by the constructor, so it should access $this->id, but exec() can't for some reason. Maybe because $this refers to the PDOObject in this context?
If I var_dump($this->id); just before executing the code above, everything's okay, I get the correct session id.
Before any comments pointing it out, it's not a typo, ${DEFAULT_DATABASE} exists, id is a varchar(32) field, and both $this->user and this->user->data are objects (they are not so much relevant now).
Your help is appreciated :)


text:
Q: xpath question on selecting node set Here is a simplified version of my source xml document:
<eml>
<additionalMetadata>
    <describes>sbclter.380</describes>
    <access authSystem="knb" order="denyFirst">
      <allow>
        <principal>public</principal>
        <permission>all</permission>
      </allow>
    </access>
  </additionalMetadata>

  <additionalMetadata>
    <describes>sbclter.415</describes>
    <describes>sbclter.380</describes>
      <access authSystem="knb" order="allowFirst">
        <allow>
          <principal>public</principal>
          <permission>all</permission>
        </allow>
      </access>
  </additionalMetadata>

  <additionalMetadata>
        <describes>sbclter.415</describes>
        <access authSystem="knb" order="allowFirst">
            <allow>
              <principal>public</principal>
              <permission>all</permission>
            </allow>
          </access>
    </additionalMetadata>
 <eml>

I want to select a node set of element "describes" - its value shows in more than one addtionalMetadata block and its "access" sibling has different order: "denyFirst" and "allowFirst".
In above example, the "describes" with value sbclter.380 is the case. Since it shows in two additionalMetadata block, the first one has "denyFirst" in access sibling, but the second one has "allowFirst" in access sibling. sbclter.415 would NOT be the case. Since it shows up in two additionalMetadata block, but both access siblings has the same value "allowFirst" at the attribute "order".
After transformation, i want get:
<eml>
    <additionalMetadata>
        <describes>sbclter.380</describes>
        <access authSystem="knb" order="denyFirst">
          <allow>
            <principal>public</principal>
            <permission>all</permission>
          </allow>
        </access>
      </additionalMetadata>

      <additionalMetadata>
        <describes>sbclter.380</describes>
          <access authSystem="knb" order="allowFirst">
            <allow>
              <principal>public</principal>
              <permission>all</permission>
            </allow>
          </access>
      </additionalMetadata>

      <additionalMetadata>
            <access authSystem="knb" order="allowFirst">
                <allow>
                  <principal>public</principal>
                  <permission>all</permission>
                </allow>
              </access>
        </additionalMetadata>
     <eml>

Here is my node:
   <xsl:for-each select="/*/*">
        <xsl:choose>
           <xsl:when test="name()='additionalMetadata'">
            <xsl:call-template name="handle-describe-access-in-additional-metadata">
                <xsl:with-param name="describes-list" select="./describes[//additionalMetadata[describes = . and access[@order='allowFirst']] and //additionalMetadata[describes = . and access[@order='denyFirst']]]"
          ></xsl:with-param>
              ></xsl:with-param>
            </xsl:call-template>
          </xsl:when>
        </xsl:choose>
      </xsl:for-each>

However,it doesn't work. The xpath in "xsl:with-param" picked up nothing - no  sbclter.415 either sbclter.380. Do you have any suggestion? Thank you  so much!
Note: this is simplified version of code.

A: Here is one transformation that produces the wanted result:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
<!--                                                -->
 <xsl:key name="kDescrByVal" match="describes"
  use="."/>
<!--                                                -->
    <xsl:template match="node()|@*" name="identity">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
<!--                                                -->
    <xsl:template match="describes">
      <xsl:if test=
       "count(key('kDescrByVal', .)) > 1
       and
        following-sibling::access/@order
       !=
        key('kDescrByVal', .)/following-sibling::access/@order
       ">
       <xsl:call-template name="identity"/>
      </xsl:if>
    </xsl:template>
</xsl:stylesheet>

When applied to the provided XML document (corrected to be well-formed):
<eml>
    <additionalMetadata>
        <describes>sbclter.380</describes>
        <access authSystem="knb" order="denyFirst">
            <allow>
                <principal>public</principal>
                <permission>all</permission>
            </allow>
        </access>
    </additionalMetadata>
    <additionalMetadata>
        <describes>sbclter.415</describes>
        <describes>sbclter.380</describes>
        <access authSystem="knb" order="allowFirst">
            <allow>
                <principal>public</principal>
                <permission>all</permission>
            </allow>
        </access>
    </additionalMetadata>
    <additionalMetadata>
        <describes>sbclter.415</describes>
        <access authSystem="knb" order="allowFirst">
            <allow>
                <principal>public</principal>
                <permission>all</permission>
            </allow>
        </access>
    </additionalMetadata>
</eml>

the wanted result is produced:
<eml>
    <additionalMetadata>
        <describes>sbclter.380</describes>
        <access authSystem="knb" order="denyFirst">
            <allow>
                <principal>public</principal>
                <permission>all</permission>
            </allow>
        </access>
    </additionalMetadata>
    <additionalMetadata>

        <describes>sbclter.380</describes>
        <access authSystem="knb" order="allowFirst">
            <allow>
                <principal>public</principal>
                <permission>all</permission>
            </allow>
        </access>
    </additionalMetadata>
    <additionalMetadata>

        <access authSystem="knb" order="allowFirst">
            <allow>
                <principal>public</principal>
                <permission>all</permission>
            </allow>
        </access>
    </additionalMetadata>
</eml>

Do note the use of:

*

*Keys.

*The Xpath "!=" operator.

A: I would try making a variable of the current describes node and using it instead of referencing . in your XPath subexpressions.
Because, for example, in the statement [//additionalMetadata[describes = ., the . is referenceing the additionalMetadata node, not the describes node.

A: Elaborating on what I said in my comment to your answer, here's an example that demonstrates what I mean:
Using this XML file as a source,
<Header>
  <thing>
    <child>5</child>
  </thing>
  <thing>
    <child>6</child>
  </thing>
  <thing>
    <child>7</child>
  </thing>
  <thang>
    <children>5</children>
  </thang>
</Header>

With this XSLT file:
<xsl:template match="/Header">
    <xsl:value-of select="./thing[//thang[children = ./child]]"/>
</xsl:template>

If the . refered to thing in this example, the output would be 5, but since . refers to thang, there is no output. If there were a variable that contained thing, then it would work:
  <xsl:template match="/Header">
    <xsl:variable name="thing" select="./thing"/>
    <xsl:value-of select="./thing[//thang[children = $thing/child]]"/>
  </xsl:template>

You're in the same situation. Your . is referencing something other than what you think it is.


text:
Q: Article before a dependent clause When one writes a noun after a dependent clause, should that noun be preceded by an "a" or an "an".
"That was an, to be quite clear, extremely clever idea."
Or: "That was a, to be quite clear, extremely clever idea."

A: No native speaker would put the article before the dependent clause in this case. In the example you give the dependent clause modifies the verb (was) and not the noun. The article should go close to the noun and after the dependent clause.

That was, to be quite clear, an extremely clever idea.

There might be rare cases where the dependent clause really does modify the noun:

The hunter's video shows a soon to be killed animal.

However this construction is clumsy and hard to understand. Most writers would use hyphens within the dependent clause.

The hunter's video shows a soon-to-be-killed animal.

In any case usual rules would be followed for deciding between a and an, which is that the next word controls which one to use

an animal
a large animal
a soon-to-be-killed animal


text:
Q: copy entire self executable to memory c++ I have an c++ executable, I concatenated the last part of it, with an image.
Would like to load the entire executable to memory, then break the concatenated image into a unsigned char * to be loaded, inside the same executable.
Suppose the executable itself has a size of 47104 and the image has a size of 13216.
So concatening these two, the executable would be around 60320 (47104 + 13216).
I was thinking about :
unsigned char * entireExe;
unsigned char * img;

memcpy(entireExe, how to load the entire executable to memory???, 60320);
memcpy(img, entireExe + 47104, 13216);
displayImage(img); // using any method available (opencv/poco/devilIL/opengl,etc)

A: Why not load a DLL into memory and use its address space to hold the image information? It should allocate enough space to do whatever you need to do. Or you could display the image inside of a window created by the DLL if you want. If you are trying to edit the executable itself, I would suggest using IDA or any other reverse engineer tool to look at it's PE struct/memory pages and going from there.
This is a good resource:
https://github.com/67-6f-64/Firefly/blob/master/Firefly%20Library/pe_structs.hpp


text:
Q: Pyspark add row based on a condition I have a below dataframe structure

A
B
C

1
open
01.01.22 10:05:04

1
In-process
01.01.22 10:07:02

I need to insert a row before the open value row.So,I need to check the status whether its open and then add a new row before it with other columns being the same values except the C column to get 1hour subtracted. How this can be acheived using Pyspark?

A: Instead of "insert a row" – which is a non-trivial issue to solve –, think about it as "union dataset"
Assuming this is your dataset
df = spark.createDataFrame([
    (1, 'open', '01.01.22 10:05:04'),
    (1, 'In process', '01.01.22 10:07:02'),
], ['a', 'b', 'c'])

+---+----------+-----------------+
|  a|         b|                c|
+---+----------+-----------------+
|  1|      open|01.01.22 10:05:04|
|  1|In process|01.01.22 10:07:02|
+---+----------+-----------------+

Based on your rule, we can construct another dataset like this
from pyspark.sql import functions as F

df_new = (df
    .where(F.col('b') == 'open')
    .withColumn('b', F.lit('Before open'))
    .withColumn('c', F.to_timestamp('c', 'dd.MM.yy HH:mm:ss')) # convert text to date with custom date format
    .withColumn('c', F.col('c') - F.expr('interval 1 hour'))   # subtract 1 hour
    .withColumn('c', F.from_unixtime(F.unix_timestamp('c'), 'dd.MM.yy HH:mm:ss')) # revert to custom date format
)

+---+-----------+-----------------+
|  a|          b|                c|
+---+-----------+-----------------+
|  1|Before open|01.01.22 09:05:04|
+---+-----------+-----------------+

Now you just need to union them together, and sort if you want to "see" it
(df
    .union(df_new)
    .orderBy('a', 'c')
    .show()
)

+---+-----------+-----------------+
|  a|          b|                c|
+---+-----------+-----------------+
|  1|Before open|01.01.22 09:05:04|
|  1|       open|01.01.22 10:05:04|
|  1| In process|01.01.22 10:07:02|
+---+-----------+-----------------+


text:
Q: Xamarin Size Limit? Xamarin's website says Visual Studio Community doesn't have a size limit... But when I try to run a test app it says otherwise...
I'm new to Xamarin and app development, but this seem's straight forward. What am I missing?
Xamarin Website:

App Restrictions:
  None. Unlimited app size.
  Deploy to public and private app stores.

https://www.xamarin.com/compare-visual-studio
Visual Studio Error:
Severity    Code    Description Project File    Line    Suppression State
Error       User code size, 2426880 bytes, is larger than 131072 and requires aáBusinessá(or higher) License.   ClientApp
Error       Using type `Android.Runtime.JNIEnv` requiresáBusinessá(or higher) License.  ClientApp

VS 2015 info
Microsoft Visual Studio Community 2015
Version 14.0.24720.00 Update 1
Microsoft .NET Framework
Version 4.6.01038

Installed Version: Community

Visual Basic 2015   00322-20000-00000-AA885
Microsoft Visual Basic 2015

Visual C# 2015   00322-20000-00000-AA885
Microsoft Visual C# 2015

Visual C++ 2015   00322-20000-00000-AA885
Microsoft Visual C++ 2015

Application Insights Tools for Visual Studio Package   1.0
Application Insights Tools for Visual Studio

ASP.NET and Web Tools 2015.1 (Beta8)   14.1.11106.0
ASP.NET and Web Tools 2015.1 (Beta8)

ASP.NET Web Frameworks and Tools 2012.2   4.1.41102.0
For additional information, visit http://go.microsoft.com/fwlink/?LinkID=309563

ASP.NET Web Frameworks and Tools 2013   5.2.30624.0
For additional information, visit http://www.asp.net/

Common Azure Tools   1.5
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Microsoft Azure Mobile Services Tools   1.4
Microsoft Azure Mobile Services Tools

NuGet Package Manager   3.3.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

PreEmptive Analytics Visualizer   1.2
Microsoft Visual Studio extension to visualize aggregated summaries from the PreEmptive Analytics product.

SQL Server Data Tools   14.0.50616.0
Microsoft SQL Server Data Tools

TypeScript   1.7.6.0
TypeScript for Microsoft Visual Studio

Xamarin   4.0.1.96 (dcea9c1)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android   6.0.1.10 (e98e962)
Visual Studio plugin to enable development for Xamarin.Android.

Xamarin.iOS   9.4.1.24 (47eb74b)
Visual Studio extension to enable development for Xamarin.iOS.

A: You need to update to at least the first stable version after the Microsoft acquisition:
Release Notes: STABLE RELEASE: CYCLE 6 SERVICE RELEASE 3
Blog: Xamarin for Everyone

*

*Xamarin for Visual Studio 4.0.3.214

*Xamarin.Android 6.0.3.5

But I would update to at least latest stable version:
Review the release notes for stable/beta/alpha/previews here:

*

*https://releases.xamarin.com


text:
Q: Enable A Submit Button in Chrome what is the proper way to ENABLE a form submit button in HTML?  My form is currently disabled by Chrome and I need it to be enabled.

<form method="post" action="#mc_signup" id="mc_signup_form">
    <input type="hidden" id="mc_submit_type" name="mc_submit_type" value="html" />
    <input type="hidden" name="mcsf_action" value="mc_submit_signup_form" />
    <input type="hidden" id="_mc_submit_signup_form_nonce" name="_mc_submit_signup_form_nonce" value="d0bc38cc04" />

Email Address
<input type="text" size="18" value="" name="mc_mv_EMAIL" id="mc_mv_EMAIL" class="mc_input"/>

        <input type="submit" name="mc_signup_submit" id="mc_signup_submit" value="Keep Me Updated!" class="button" />

</form>

This button is also disabled somehow in IE9.  What is going on here?  I've never had this problem with forms.
Thanks!

A: By default, it is always enabled. Are you placing this submit button inside of a <form> tag?
You most likely have something else on the page interfering with your submit button.
Doing a quick test, it seems it is not any of the css classes or ids.
I would first remove this script: , and see if it fixes the no submit problem.

A: You can disable a submit button in markup (to enable it simply remove the attribute):
<input type="button" id="my-button" value="Button" disabled="disabled" />

Or you can do it in script:
// disable
document.getElementById("my-button").setAttribute("disabled", "disabled");

//enable
document.getElementById("my-button").removeAttribute("disabled");

However, html elements are always enabled by default so check whether you have any script setting input children of an element to disabled.

A: In endingpovertytogether.org's code:
<form method="post" action="#mc_signup" id="mc_signup_form" onSubmit="document.getElementById('submit').disabled=true;">
..
<input type="submit" name="mc_signup_submit" id="mc_signup_submit" value="Keep Me Updated!" class="button" />
</form>

Remove onSubmit="document.getElementById('submit').disabled=true;" in tag from
It's in script file:

Remove:
$('#mc_signup_submit').attr("disabled","disabled");

In function mc_beforeForm()

A: Is it inside a <form> tag?  That could lead to a submit button being disabled.  There is nothing to submit.


text:
Q: Is there a bug in PdfStamper in iText 2.1.7? I am trying to use iText 2.1.7 in my application. I nailed down by problem to the following piece of code:
InputStream inputFile = ...
OutputStream outputStream = ...
PdfReader pdfReader = new PdfReader(fis);
PdfStamper pdfStamper = new PdfStamper(pdfReader, os, '0', true);

pdfStamper.close();
pdfReader.close();
outputStream .close();

This code yields broken pdf (error 118) when as input I use this pdf (this is polish taxation form). Do you know if it there is some easy work-around for this problem? I know that corresponding code in c#/iTextSharp works.
Edit: This is not a problem with encryption. I have already solved this one.

A: As mentioned as a comment, the document in question is encrypted to restrict permissions. The code from the official iText 2.1.7 jar will, therefore, throw a BadPasswordException when instantiating the PdfStamper because the correct password was not supplied. Thus, it does not produce a broken PDF and so the issue here is not a bug. ;)
That being said it of course is possible to coerce iText 2.1.7 into ignoring the fact that the password was not supplied. In that case the program (having corrected the variable names where necessary) indeed produces a PDF which Adobe Acrobat refuses to open showing an error code 118.
Doing the same with the current iText 5.x, on the other hand, produces a document which Adobe Acrobat opens without any objection.
If one compares those two outputs, the problem becomes clear. While in case of iText 2.1.7 the updated info dictionary looks like this:
16 0 obj
<<
/Creator(ADEP Document Services … Designer 10.0)
/Producer(Adobe LiveCycle Forms ES3; modified using iText 2.1.7 by 1T3XT)
/schemat(http://crd.gov.pl/wzor/2011/12/19/732/)
/Title(PIT-37)
/wersja_schemy(1-0E)
/ModDate(D:20121129153659+01'00')
/Subject(þÿ Z e z n a n i e   o   w y s o k o[ c i   o s i g n i t e g o   d o c h o d u \( p o n i e s i o n e j   s t r a t y \)   p r z e z   p o d a t n i k a   p o d a t k u   d o c h o d o w e g o   o d   o s ó b   f i z y c z n y c h)
/wariant(17)
/Author(Ministerstwo Finansów)
/CreationDate(D:20120816122649+02'00')
>>
endobj

it looks like this with the current iText 5.x:
16 0 obj
<<
/Creator(Ìû±d\\'0Ú¼U´N°4@è4÷¤&'ŸWŠÖsW¦ïôeå¿ê¹@aC<M¹^\t¯p; Um…‡&U$")
/Producer(Ìû±d\\'0Ú¼U´NSH<š¶CìœhMÙg6\(@+C"rxó3% èúáž#"~îí$´Ñ\rEÿ\){â®ø×ÇMõÒ"/k«'T"…Ô»6D±Šàûèq}=_]YùèM»Lõ‡!õØûÚ©'é+t#Väò¿ÃSVõñý)
/schemat(Ìû±d\\'0Ú¼U´N"hÙÚújñÂð\)÷Lsg—¥oÏ0<Á@õ5/•X6úJ!–nÈÒvU'nð)
/Title(Ìû±d\\'0Ú¼U´NÅÎéÈ€Ã3 ÅpC"¡H)
/wersja_schemy(Ìû±d\\'0Ú¼U´NAÞ&·4ul‰¡b'Œó)
/ModDate(Ìû±d\\'0Ú¼U´NÏbZk£&"!õH³Î¨l\f6\)¥+¥ûcoûÒ\rÕ8˜Í)
/Subject(Ìû±d\\'0Ú¼U´N:¡Ž""ؘí¹~KŸpS†ÑŽäQ%"ýãtõÌt\t'Ý3t\r9Ñ}#M …O¦\nqWóm: íÑ;A"GÝ.mÐÔéÔ]Ùn"Ƽä°'0%±@ \rÞªeé¶T<"¾./ýÂA"ÆRvoo€'—Ý{?Ü"Nö\r¼¨]üv•¯y©Tˆ aŸ?"y°à¡ÀaÂÛ"ÄR'rèŽêKD•M6{Ä£t´é¾ù|%¬ƒÒˆM….'Ëð½˜B‡lƳ¤+¦Š¹ôTÝ^å¤=‹BAO'Ø€°ú̱æj9_!#÷h‡5)
/wariant(Ìû±d\\'0Ú¼U´N6©BÛâ`Ì¡k‹Ô <½`)
/Author(Ìû±d\\'0Ú¼U´NŒ'×,ïZ2ä¡Åöw윭?bjÃô'w|éUÆб)
/CreationDate(Ìû±d\\'0Ú¼U´N'·¬‡jHÎâÃë&šZ¦Ñ.U©ü«s¾½Ý;2¸Q)
>>
endobj

Thus, the iText 2.1.7 did not encrypt the entries of the updated info dictionary, and Adobe Acrobat hickuped while trying to decrypt it.
EDIT
Unfortunately, even after spacing away the unencrypted info dictionary, there is the 118 when trying to load the file. Thus looking at the files again there is another difference: the version created by iText 2.1.7 contains a tiny object stream while the other version does not. iText itself stumbles when trying to read that object stream...


text:
Q: Issues with locating gem file? I am attempting to build a Ruby Gem following this tutorial, however I am unable to configure the rspec as it is unable to find my gem.
$ gem list | grep gemname
gemname (0.0.1.alpha)

$ rake spec
/Users/rudolph9/.rvm/rubies/ruby-1.9.3-p0/bin/ruby -S rspec ./spec/gemname_spec.rb
/Users/rudolph9/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such  file -- gemname (LoadError)
    from /Users/rudolph9/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/rudolph9/Developer/gemname/spec/spec_helper.rb:2:in `<top (required)>'
    from /Users/rudolph9/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/rudolph9/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/rudolph9/Developer/gemname/spec/gemname_spec.rb:1:in `<top (required)>'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/configuration.rb:698:in `load'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/configuration.rb:698:in `block in load_spec_files'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/configuration.rb:698:in `map'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/configuration.rb:698:in `load_spec_files'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/command_line.rb:22:in `run'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/runner.rb:80:in `run_in_process'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/runner.rb:69:in `run'
    from /Users/rudolph9/.rvm/gems/ruby-1.9.3-p0/gems/rspec-core-2.8.0/lib/rspec/core/runner.rb:10:in `block in autorun'
rake aborted!
/Users/rudolph9/.rvm/rubies/ruby-1.9.3-p0/bin/ruby -S rspec ./spec/gemname_spec.rb failed

Tasks: TOP => default => spec
(See full trace by running task with --trace)

I this this may have something to do with using rvm or perhaps the way the rake file is being configured on the tutorial previously mentioned but I am not sure.
What is causing the issue?

A: It looks like this is bubbling up from the require in your spec_helper.rb file. Is your main gem class the same as your gem's name? You should be requiring the main class and not the gem's name. Try varying the require statement to one of the following and see if you get a different result.
require 'gemname'
# Or
require 'gemname.rb'
# Or
require './path/to/gemname.rb'

I would also try to require the class from IRB and see what circumstances it will work in.

A: When you build a gem and want to require it by it's name you need to provide:
lib/gemname.rb

It's less important what's in this file, just what you want like requiring other stuff from it:
require 'gemname/nothing'

where also this file exists:
lib/gemname/nothing.rb


text:
Q: Parfor on a cluster : failure to recognize a function I try to run a simple task on different machines of a cluster.
My configuration has been validated (it's ok). When I run the code
on the 'local' configuration, it works. But when I use the cluster
configuration, I get the following error :
Error using parallel_function (line 598)
Undefined function 'lafunc' for input arguments of type 'double'.
Error Stack : (No remote error stack)
Error in petittest (line 6)  --» (petittest is my program's name)
parfor it=1:200
I try to modify the code to use "dfeval" instead of the parfor loop,
but I got the same kind of result (unrecognize function lafunc).
How do I get the other workers in the cluster to recognize the function
lafunc that I manually defined ?
The code is the following:
%%%%%%%%%%%%%
laconfig='/home/matlab/fred/LACED_DC1.mat';
setmcruserdata('ParallelConfigurationFile',laconfig);

matlabpool open

parfor it=1:200

yo=lafunc(it);
disp(yo)

end

matlabpool close

%%%%%%%%%%%

where the lafunc function is
%%%%%%%%%%%%%%

function [y]=lafunc(x)
y=x*x;
end

%%%%%%%%%%%%%%%%%%%%%%

Thanks a lot, every piece of info is useful to me!!

A: Make sure that your MATLAB script on all worker nodes running in the same working directory, and that other directories with functions you need are included in the path. So you can specifically set the working directory and path in your script:
matlabpool open
cd workdir
addpath funcdir
...

After you run matlabpool open it will run all path related commands on all workers. See here.
You can also open matlabpool with 'FileDependencies' parameter so all the workers will know where to look for required files. See the documentation for MATLABPOOL.


text:
Q: Global variable set from file read doesn't update with app restart I made changes to a YML file locally that is read in from an initializer and restarted the Rails environment, but the old version of the data from that file persisted in application state. The file was saved and checked into version control (just in case that was the issue for whatever reason).
The code itself was simple:
# config/initializers/tagging.rb
require 'yaml'

$tag_refs = YAML.load_file("static/tagging_lookup.yml")

The original data looked like this:
{
    "tag_types" => {
        "users" => [
            [0] "skill",
            [1] "availability"
        ],
         "jobs" => [
            [0] "skill"
        ]
    },
        "users" => {
               "skill" => [
            [0] "skilled",
            [1] "expert",
            [2] "experienced",
            [3] "flexible",
            [4] "communicative"
        ],
        "availability" => [
            [0] "part-time",
            [1] "full-time",
            [2] "gig",
            [3] "contract"
        ]
    }
}

This was fixed by 'unsetting' and 'resetting' the variable:
# config/initializers/tagging.rb
require 'yaml'

$tag_refs = nil
$tag_refs = YAML.load_file("static/tagging_lookup.yml")

The updated (and correct) data looked like this:
{
    "tag_types" => {
        "users" => [
            [0] "skill",
            [1] "availability"
        ],
         "jobs" => [
            [0] "benefit",
            [1] "experience",
            [2] "availability"
        ]
    },
        "users" => {
               "skill" => [
            [0] "skilled",
            [1] "expert",
            [2] "experienced",
            [3] "flexible",
            [4] "communicative"
        ],
        "availability" => [
            [0] "part-time",
            [1] "full-time",
            [2] "gig",
            [3] "contract"
        ]
    },
         "jobs" => {
             "benefit" => [
            [0] "PTO",
            [1] "remote",
            [2] "flexible",
            [3] "supplied equipment"
        ],
        "availability" => [
            [0] "part-time",
            [1] "full-time",
            [2] "gig",
            [3] "contract"
        ],
          "experience" => [
            [0] "skilled",
            [1] "expert"
        ]
    }
}

Am I missing something here? Does Rails persist global variable states if the same code is run against it? Does this have something to do with the default file caching functionality in Rails?
EDIT:
Upon further investigation, it appears that it doesn't work without $tag_refs = nil when I add a new key to the YML file under nested context. For example:
tag_types:
  jobs: ["benefit", "industry"]
jobs:
  benefit: ["PTO", "remote", "flexible", "supplied equipment"]
  industry: ["food"]

When changed to:
tag_types:
  jobs: ["benefit", "industry", "lodging"]
jobs:
  benefit: ["PTO", "remote", "flexible", "supplied equipment"]
  industry: ["food"]
  lodging: ["on-site"]

Will NOT include the 'lodging' key in the read jobs values.


text:
Q: mysql remote login from workbench does not work I want to connect a ubuntu (16.04) machine through mysql workbench and it gives the following error.

ERROR 2003 (HY000): Can't connect to MySQL server on '35.200.151.3' (10060 "Unknown error")

I checked the config for bind_address and it is *.
I have created a new user and grant privileges with host % also.
I also checked if its a firewall issue and it is not. What else could cause this error ?


text:
Q: Run redis-server as PyCharm configuration Every time I start one of my PyCharm projects, I have to go into a terminal window and start redis with the command redis-server. How can I add this as a run/debug configuration so I can combine it with other parts of my app? My goal is to have a single compound configuration that starts a Django web server, background worker, and redis.

A: In the run\debug configuration menu you can add shell script. But Redis process only possible to stop with ctrl+c.


text:
Q: What are the lead and free variables of the matrix in reduced row-echelon form? The following matrix is in reduced row-echelon form:
$\begin{bmatrix}1&0&0&0&1&-1\\0&1&0&0&0&2&\\0&0&1&1&0&0&\end{bmatrix}$
There is a 'staircase-structure' in this matrix. In theory, at all of the separate 'stairs', the first nonzero element of the row equals 1. These elements represent the lead variables. The others represent the free variables. However, I am confused whether the fourth variable is a lead variable as well, considering it starts with a 1, but doesn't follow the staircase structure. I believe that the fifth and the sixth variable are free variables and that the first three variables are definitely lead variables. Could someone confirm this?


text:
Q: Windows 10 batch unzip multiple files with filename the same as zip directory name I have about 60 files to unzip as you can see below:

know the 7zip option, which can unzip all of them, but the problem is, that the file inside doesn't match the zip directory name, which would be highly desirable here.
I found some solutions for the batch file here:
Extract all Zip's in a directory (incl. subfolders) with a .bat file or dos command
and prepared some batch code for this which looks like this:
 @echo off
 setlocal
 cd /d %~dp0
 for %%a in (*.zip) do (
  Call :UnZipFile "C:\my\Desktop current\Occ KMZ\bat\Aldebaran" "C:\my\Desktop current\Occ
  KMZ\bat\Aldebaran"
  )
   exit /b

but it doesn't work at all. I can neither unzip it nor get files.
The 7zip software has a few options, which potentially could be good

I found also some options here:
https://stackoverflow.com/questions/48967931/renaming-files-to-folder-names
How can I unzip multiple "7z" files all in one go, and have the contents go into a respective folder with the same name as the zip file?
but they didn't work either.
How can I solve this problem?
but I don't know how to use the 7Zip command line in order to get the unzipped file with the same name as the zip directory.
What should I do to automatize this section?


text:
Q: How to get Message without creating Queue in Activemq i am new to activemq. i created one queue and produce one message to that queue from one client. i want to consume that message from another client. for consume the message the code follows
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // Create a Session
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    Destination destination = (Destination) session.createQueue("StaticQueueName");

     MessageConsumer consumer= session.createConsumer(destination);
     Message message = (Message) consumer.receive();
     System.out.println(message.getStringProperty("status"));
      if (message instanceof TextMessage) {
         TextMessage textMessage = (TextMessage) message;
         Text = textMessage.getText();
         System.out.println("Received: " + Text);
     } else {
         System.out.println("Received: " + message);
     }

if we have already knew the queue name then no need to create.i metioning below code.
 Destination destination = (Destination) session.createQueue("StaticQueueName");

so is there any method available if we know the queue name before.so using that queue name we can access the message like getqueue("queue name") instead of create the queue.

A: If such a queue already exists, then no other queue will be created, the same will be given to you. It will not get 'overridden'.

A: QueueReceiver receiver= session.createReceiver(queueName);
receiver.setMessageListener(this);

If you know the queueName than just create a receiver it will get the message from the queue.


text:
Q: Issue passing parameters Form::Open Laravel Fairly new at Laravel and trying to grasp the store function and routing. I'm getting the following error trying to open a form in Laravel:
Missing required parameters for [Route: {$route->getName()}] [URI: {$route->uri()}].

The issue is because my url is:
/projects/1/documents/create

And I'm opening to:
/projects/1/documents

I'm trying to pass the projects ID but I'm missing something.
Form Call:
{!! Form::open(['route'=>'projects.documents.store', $project->id]) !!}
     @include('pages.projects.documents.charter.partials._form', ['submitButtonText'=>'Create Project Charter'])
{!! Form::close() !!}

My Web Route (I'm assuming the issue is here):
// Resource route for Project Document Controller
Route::resource('projects.documents', 'Project\DocumentController');

My DocumentController store function:
public function store(Request $request, Project $project)
{
    // Validate the request
}

I'm not sure if there is any other sections of code that are need. The page renders fine without Form::open and $project->id echo's out correctly.
Edit:
I figured out my issue, it was somewhat silly. Just not use to Laravel formatting yet. The route & param needed to be in an array. The correct formatting is:
{!! Form::open(['route'=>array('projects.documents.store', $project->id)]) !!}


text:
Q: how to vlookup beetwen two dataframes My example;

Code
Volume
Trade

ApplA
500
1000

Amazon
1000
500

Facebook
250
750

ApplE
100
1500

df_samecompanies['Codes']

df['Volume Order'] = df['Volume'].rank(ascending=False)
df['Trade Order']  = df['Trade'].rank(ascending=False)
df['Trade Order2']  = df['Trade'].rank(ascending=True)
df['Max Ordered Number']  = df[['Volume Order', 'Trade Order']].max(axis=1)
df['Final Sorted Number'] = df[['Max Ordered Number', 'Trade Order2']].apply(tuple, axis=1).rank(ascending=False)
df.drop('Trade Order2', axis=1)

Output;
       Code  Volume  Trade  Value  Volume Order  Trade Order  Max Ordered Number  Final Sorted Number
0     ApplA     500   1000   <NA>             2            2                   2                    4
1    Amazon    1000    500   <NA>             1            4                   4                    2
2  Facebook     250    750   <NA>             3            3                   3                    3
  3   ApplE     100   1500   <NA>             4            1                   4                    1

I have 2 dataframes. There is no common column name. But there are common values. My first dataframe is located above. İts name is "df".
The other dataframe's name is "buffer".

Name
Place

AppLA
U30

Amazon
U30

AppLA
U20

Facebook
U10

ApplE
U10

Amazon
U20

AppLA
U10

Amazon
row

Facebook
U20

Amazon
U10

AppLE
U20

my purpose is to embed the "Buffer" dataframe into the dataframe named ""df". As you can see, there is no common column name. But there are common values. By opening 3 new columns in the dataframe named df, the dataframe named "Buffer" vlookup the values of the "Place" column into those 3 new columns.
Columns name will be "PLACE U10" - "PLACE U20" - PLACE "U30"
My expected output;
       Code  Volume  Trade  Value  Volume Order  Trade Order  Max Ordered Number  Final Sorted Number   PLACE U10   PLACE U20   PLACE U30
0     ApplA     500   1000   <NA>             2            2                   2                    4        U10           U20        U30
1    Amazon    1000    500   <NA>             1            4                   4                    2        U10           U20        U30
2  Facebook     250    750   <NA>             3            3                   3                    3        U10           U20
  3   ApplE     100   1500   <NA>             4            1                   4                    1       U10            U20        U30

as you see, facebook doesn't has "u30".
Can you help me to embed dataframe named buffer into dataframe named df with common values without common column name? If necessary, I can make the column names the same.

A: You can pivot on dataframe buffer using .pivot(), then use .join() to join df with the pivoted table of buffer, aligning index of Code in df with index of Name in the pivoted table, as follows:
buffer_pivot = buffer.pivot(index='Name', columns='Place', values='Place').add_prefix('PLACE ')

df = df.set_index('Code').join(buffer_pivot).reset_index()

Data Input
print(buffer)

       Name Place
0     ApplA   U30
1    Amazon   U30
2     ApplA   U20
3  Facebook   U10
4     ApplE   U10
5    Amazon   U20
6     ApplA   U10
7  Facebook   U20
8    Amazon   U10
9     ApplE   U20

Result:
print(buffer_pivot)

Place    PLACE U10 PLACE U20 PLACE U30
Name
Amazon         U10       U20       U30
ApplA          U10       U20       U30
ApplE          U10       U20       NaN
Facebook       U10       U20       NaN

print(df)

       Code  Volume  Trade  Volume Order  Trade Order  Max Ordered Number  Final Sorted Number PLACE U10 PLACE U20 PLACE U30
0     ApplA     500   1000           2.0          2.0                 2.0                  4.0       U10       U20       U30
1    Amazon    1000    500           1.0          4.0                 4.0                  2.0       U10       U20       U30
2  Facebook     250    750           3.0          3.0                 3.0                  3.0       U10       U20       NaN
3     ApplE     100   1500           4.0          1.0                 4.0                  1.0       U10       U20       NaN


text:
Q: Sitecore - Use DMS profile keys for content categorisation Our usual approach to categorization in Sitecore is to create a list of basic items (e.g. named Red, blue, Green). Then we have droplinks on each page of the site which specify allowing you to specify a category. We can find related items based on them sharing the same value in the category field.
On a forthcoming site, our UX team have suggested using profile keys in place of categorization items.
So to find the items related to the current one, you would look at its associated profile keys and then get all the other items with those same profile keys.
I would like advice on whether this approach is possible, practical and advisable.
A basic code snippet would also be appreciated.
EDIT
I found this article which shows that the data I need to get hold of is stored as XML in the __Tracking field of each item.
Get Profile Key Score for Individual Page in Sitecore
However, I'm still unsure of the practicality of this, particularly when scaling up to to hundreds of items.

A: Looks like a combination these were enough get me what I wanted:

*

*Get Profile Key Score for Individual Page in Sitecore

*Find sitecore items with a specific OMS profile?
I'm using an index that includes the __Tracking field.


text:
Q: Restrict elements inside an array to be a specific type I am trying to restrict elements inside an Array to be of certain type. However, typescript allows me to mix them up and won't complain.
Find below a simple example in which typescript allows me to add a pear to the apples array. It won't let me add an apple to the pears, though.
type Pear = {
  color: string;
  isOrganic: boolean;
};

type Apple = {
  color: string;
};

const pear: Pear = {
  color: "green",
  isOrganic: true,
};

const apple: Apple = {
  color: "red",
};

const apples: Apple[] = [apple, pear];
const pears: Pear[] = [apple, pear];

I also tried the following:
type Apple = {
  color: string;
  isOrganic?: never;
};

But I don't think this is the right way. Intellisense keeps telling me there is a property isOrganic every time I type a . after an apple. Also, when creating an apple it tells me I can fill that property.
Why is this happening and how could I achieve what I want in a clean way?
Thanks in advance.


text:
Q: How to substitute correctly in python using regex I have a python string:
s = 'filename               13.00 50850.8732503344475    37.11  abc'

In order to find the second string with format nn.nn, I know I can do:
re.findall(r'.*(\b\d+\.\d+)',s)[0]

which finds:
'37.11'

But I want to replace it with 99.99.
I tried:
re.sub(r'.*(\b\d+\.\d+)','99.99',s)

But that just yields:
'99.99  abc'

whereas I want:
'filename               13.00 50850.8732503344475    99.99  abc'

Clearly I don't yet understand how regex works. Could someone offer help please?

A: You should capture what you need to keep and use the unambiguous replaement backreference in the replacement pattern:
s = re.sub(r'(.*)\b\d+\.\d+',r'\g<1>99.99', s)

See the Python demo and the regex demo.
Pattern details

*

*(.*) - Group 1 (its value is referred to with \g<1> backreference from the replacement pattern): any 0+ chars other than line break chars as many as possible

*\b - a word boundary

*\d+ - 1+ digits

*\. - a dot

*\d+ - 1+ digits.

A: Alternatively, you can replace last occurrence of simple pattern (\d+\.\d+):
s = "filename               13.00 50850.8732503344475    37.11  abc"
*_, last = re.finditer(r"(\d+\.\d+)", s)
s = s[:last.start()] + "99.99" + s[last.end():]

It's a bit faster. Results of timeit benchmark(code):
re.finditer() -> 11.30306268
re.sub() -> 15.613837582000002


text:
Q: PHP triggers web and logic at the same time I want to send a web page to the browser. At the same time, it will run another php script in the server without affecting the browser web page.
Is there any way to achieve this by php and jquery only?
ps1 My script is a heavy task, so I am not sure if it will delay the web page sending or not.

A: i would do it like this
exec("nohup php otherphpscript.php  >/dev/null 2>&1 &");

A: You can use curl() to access the script in the background
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://domain.com/script.php?s=email&m=message");
curl_exec ($curl);
curl_close ($curl);

script.php
<?php
// send an email confirming script.php was accessed (with params)
$subject = strip_tags($_GET['s']);
$message = strip_tags($_GET['m']);
mail('email@email.com',$subject,$message);

http://us2.php.net/curl
You can also do this asynchronously via ajax on document load
I'm not a javascript guy, so somebody may chime in with an issue doing it via ajax, however it's working for me in testing...
<script src="//code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function() {
$.ajax({
    type: 'POST',
    url: 'script.php',
    data: 's=subject&m=message',
    cache: false,
    success: function(data){
        // put success stuff here
        alert(data); // for testing
    }
});
return false;
 });
</script>

script.php
<?php
if($_SERVER['REQUEST_TYPE'] == 'POST') {
    $subject = strip_tags(trim($_POST['s']));
    $message = strip_tags(trim($_POST['m']));

    if(mail('email@email.com',$subject,$message)) {
        echo 'true';
    } else {
        echo 'false';
    }
}

Edit: updated answer per OP's question in comments.
Edit: added ajax example

A: It's possible. Just ping the URL:
// 'ping' the url http://localhost/browser/path/to/script2.php
$host = 'localhost';
$path = '/browser/path/to/script2.php';

$fp = fsockopen($host, 80);
if($fp !== false)
{
  $out  = "GET $path HTTP/1.1\r\n";
  $out .= "Host: $host\r\n";
  $out .= "Connection: Close\r\n\r\n";

  fwrite($fp, $out);
  fclose($fp);
}

And then in script2.php:
ignore_user_abort(true);

// your code goes here
// ...


text:
Q: Calculate coordinates of a regular polygon's vertices I am writing a program in which I need to draw polygons of an arbitrary number of sides, each one being translated by a given formula which changes dynamically. There is some rather interesting mathematics involved but I am stuck on this probelm.
How can I calculate the coordinates of the vertices of a regular polygon (one in which all angles are equal), given only the number of sides, and ideally (but not neccessarily) having the origin at the centre?
For example: a hexagon might have the following points (all are floats):
( 1.5  ,  0.5 *Math.Sqrt(3) )
( 0    ,  1   *Math.Sqrt(3) )
(-1.5  ,  0.5 *Math.Sqrt(3) )
(-1.5  , -0.5 *Math.Sqrt(3) )
( 0    , -1   *Math.Sqrt(3) )
( 1.5  , -0.5 *Math.Sqrt(3) )

My method looks like this:
void InitPolygonVertexCoords(RegularPolygon poly)

and the coordinates need to be added to this (or something similar, like a list):
Point[] _polygonVertexPoints;

I'm interested mainly in the algorithm here but examples in C# would be useful. I don't even know where to start. How should I implement it? Is it even possible?!
Thank you.

A: for (i = 0; i < n; i++) {
  printf("%f %f\n",r * Math.cos(2 * Math.PI * i / n), r * Math.sin(2 * Math.PI * i / n));
}

where r is the radius of the circumsribing circle. Sorry for the wrong language No Habla C#.
Basically the angle between any two vertices is 2 pi / n and all the vertices are at distance r from the origin.
EDIT:
  If you want to have the center somewher other than the origin, say at (x,y)
for (i = 0; i < n; i++) {
  printf("%f %f\n",x + r * Math.cos(2 * Math.PI * i / n), y + r * Math.sin(2 * Math.PI * i / n));
}

A: The number of points equals the number of sides.
The angle you need is angle = 2 * pi / numPoints.
Then starting vertically above the origin with the size of the polygon being given by radius:
for (int i = 0; i < numPoints; i++)
{
    x = centreX + radius * sin(i * angle);
    y = centreY + radius * cos(i * angle);
}

If your centre is the origin then simply ignore the centreX and centreY terms as they'll be 0,0.
Swapping the cos and sin over will point the first point horizontally to the right of the origin.

A: Sorry, I dont have a full solution at hand right now, but you should try looking for 2D-Rendering of Circles. All classic implementations of circle(x,y,r) use a polygon like you described for drawing (but with 50+ sides).

A: Say the distance of the vertices to the origin is 1. And say (1, 0) is always a coordinate of the polygon.
Given the number of vertices (say n), the rotation angle required to position the (1, 0) to the next coordinate would be (360/n).
The computation required here is to rotate the coordinates. Here is what it is; Rotation Matrix.
Say theta = 360/n;
[cos(theta) -sin(theta)]
[sin(theta) cos(theta)]

would be your rotation matrix.
If you know linear algebra you already know what i mean. If dont just have a look at Matrix Multiplication

A: One possible implementation to generate a set of coordinates for regular polygon is to:

Define polygon center, radius and first vertex1. Rotate the vertex n-times2 at an angle of: 360/n.

In this implementation I use a vector to store the generated coordinates and a recursive function to generate them:
void generateRegularPolygon(vector<Point>& v, Point& center, int sidesNumber, int radius){
    // converted to radians
    double angRads = 2 * PI / double(sidesNumber);
    // first vertex
    Point initial(center.x, center.y - radius);
    rotateCoordinate(v, center, initial, angRads, sidesNumber);
}

where:
void rotateCoordinate(vector<Point>& v, Point& axisOfRotation, Point& initial, double angRads, int numberOfRotations){
    // base case: number of transformations < 0
    if(numberOfRotations <= 0) return;
    else{
        // apply rotation to: initial, around pivot point: axisOfRotation
        double x = cos(angRads) * (initial.x - axisOfRotation.x) - sin(angRads) * (initial.y - axisOfRotation.y) + axisOfRotation.x;
        double y = sin(angRads) * (initial.x - axisOfRotation.x) + cos(angRads) * (initial.y - axisOfRotation.y) + axisOfRotation.y;
        // store the result
        v.push_back(Point(x, y));
        rotateCoordinate(v, axisOfRotation, Point(x,y), angRads, --numberOfRotations);
    }
}

Note:
Point is a simple class to wrap the coordinate into single data structure:
class Point{
public:
    Point(): x(0), y(0){ }
    Point(int xx, int yy): x(xx), y(yy) { }
private:
    int x;
    int y;
};

1 in terms of (relative to) the center, radius. In my case the first vertex is translated from the centre up horizontally by the radius lenght.
2 n-regular polygon has n vertices.

A: The simple method is:
Let's take N-gone(number of sides) and length of side L. The angle will be T = 360/N.
Let's say one vertices is located on origin.
* First vertex = (0,0)
* Second vertex = (LcosT,LsinT)
* Third vertex = (LcosT+Lcos2T, LsinT+Lsin2T)
* Fourth vertex = (LcosT+Lcos2T+Lcos3T, LsinT+Lsin2T+Lsin3T)

You can do in for loop

A: hmm if you test all the versions that are listed here you'll see that the implementation is not good. you can check the distance from the center to each generated point of the polygon with : http://www.movable-type.co.uk/scripts/latlong.html
Now i have searched a lot and i could not find any good implementation for calculating a polyogon using the center and the radius...so i went back to the math book and tried to implement it myself. In the end i came up with this...wich is 100% good:
            List<double[]> coordinates = new List<double[]>();
            #region create Polygon Coordinates
            if (!string.IsNullOrWhiteSpace(bus.Latitude) && !string.IsNullOrWhiteSpace(bus.Longitude) && !string.IsNullOrWhiteSpace(bus.ListingRadius))
            {
                double lat = DegreeToRadian(Double.Parse(bus.Latitude));
                double lon = DegreeToRadian(Double.Parse(bus.Longitude));
                double dist = Double.Parse(bus.ListingRadius);
                double angle = 36;

                for (double i = 0; i <= 360; i += angle)
                {
                    var bearing = DegreeToRadian(i);

                    var lat2 = Math.Asin(Math.Sin(lat) * Math.Cos(dist / earthRadius) + Math.Cos(lat) * Math.Sin(dist / earthRadius) * Math.Cos(bearing));
                    var lon2 = lon + Math.Atan2(Math.Sin(bearing) * Math.Sin(dist / earthRadius) * Math.Cos(lat),Math.Cos(dist / earthRadius) - Math.Sin(lat) * Math.Sin(lat2));

                    coordinates.Add(new double[] { RadianToDegree(lat2), RadianToDegree(lon2) });

                }

                poly.Coordinates = new[] { coordinates.ToArray() };
            }
            #endregion

If you test this you'll see that all the points are at the exact distance that you give ( radius ). Also don't forget to declare the earthRadius.
private const double earthRadius = 6371.01;

This calculates the coordinates of a decagon. You see the angle used is 36 degrees. You can split 360 degrees to any number of sides that you want and put the result in the angle variable.
     Anyway .. i hope this helps you @rmx!


text:
Q: TSQL Pivot with combination result I have data in SQL server 2005 table similar to below format.
OrderNo ProductId Sale
----------------------
1          A    £10
2          B    £20
3          C    £30
4          A    £10
4          B    £20
5          A    £10
5          B    £20
6          C    £30
6          B    £20
7          C    £30

I need to write TSQL  query that would give me result table  in this format.
NoOfOrders     'A' SaleValue 'B' SaleValue  'C' SaleValue
------------------------------------------------
Prod A (Only)   1   £10
Prod B (Only)   1               £20
Prod C (Only)   2                             £60
Prod A & B      2   £20         £40
Prod A & C      0   £0          £0             £0
Prod B & C      1               £20            £30

Any idea greatly appreciated.

A: I'd suggest a three-step approach:
(1) SELECT distinct ProductID into a table variable.
(2) CROSS JOIN the table variable on itself to get all possible combinations.
(3) Craft a dynamic SQL statement to pivot it out.


text:
Q: Will spending coins on Club Nintendo affect my balance towards Platinum? I have 310 points on Club Nintendo, and therefore I am a Gold member. The website says:

Within each Club Nintendo year (July 1-June 30), earn 300 Coins to reach Gold status or 600 Coins for Platinum status. We add up the Coins you've earned and we don't subtract the Coins you've spent, so you can use your Coins to redeem cool Rewards throughout the year!

Does this mean that I can spend points on things and not have my existing balance subtracted? Also, if I reach platinum where can I claim the special rewards they give out?

A: Technically, this is how it works. WHen you redeem a Club Nintendo code, the amount of coins you receive is added to the amount of coins you have previously redeemed. This does not mean that you can continue purchasing rewards without spending any coins. As you continue to add up, there will be a "count" as to how many coins you have collected over the "Club Nintendo year." This is know as the Coin Bank. No amount will be deducted for purchasing merchandise.
If you have already claimed your reward for the Gold status, you should already know how this works. Right before the Club Nintendo year ends, be sure to log in. When you do, there should be a list of the rewards you can receive. Choose carefully, though. You only get to pick one!
I hope this answer has cleared all confusion with this topic! If not, you can always go on the Club Nintendo Support Page for more details and support with any other question you have. The link will take you to the Coins and Rewards Overview section of the page. Once again, I hope this helped!

A: no it does not affect your platinum/gold status.


text:
Q: specific perl regex string in brackets after keyword I need help please with an perl regex;
My logs lines contains a User='(string)@(realm)' where i would only need the string in the first bracket after User=

A:  ...
my $line = q[User='(string)@(realm)'];
$line =~ /User='\((\w+)\)@\((\w+)\)'/;
print $1; # will print string;
print $2; # will print realm;
 ...

A: You have to escape parentheses as they have a special meaning in regexes - they create capture groups:
my $line = q{User='(string)@(realm)'};
my ($user, $realm) = $line =~ /User='\((.*)\)@\((.*)\)'/;
print "USER: $user.\nREALM: $realm.\n";


text:
Q: Merging rows in .csv in order After analysis of brain scans I ended up with around 1000 .csv files, one for each scan. I've merged them into one in order (by subject ID and date). My problem is, that some subjects had two or more consecutive scans and some had only one. Database now looks like that:
ID, CC_area, CC_perimeter, CC_circularity
024_S_0985, 407.00, 192.15, 0.138530          //first scan of A
024_S_0985, 437.50, 204.80, 0.131074          //second scan of A
024_S_0985, 400.75, 198.80, 0.127420          //third scan  of A
024_S_1063, 544.50, 214.34, 0.148939          //first and only scan of B
024_S_1171, 654.75, 240.33, 0.142453          //first scan of C
024_S_1171, 659.50, 242.21, 0.141269          //second scan of C
...

But I want it to look like that:
ID, CC_area, CC_perimeter, CC_circularity, CC_area2, CC_perimeter2, CC_circularity2, CC_area3, CC_perimeter3, CC_circularity3, ..., CC_circularity6
024_S_0985, 407.00, 192.15, 0.138530, 437.50, 204.80, 0.131074, 400.75, 198.80, 0.127420, ... ,
024_S_1063, 544.50, 214.34, 0.148939,,,,,, ...,
024_S_1171, 654.75, 240.33, 0.142453, 659.50, 242.21, 0.141269,,, ... ,
...

What is important, that order of data must not be changed and number of rows for one ID is not known (it varies from 1 to 6). (So first columns of scan 1, then scan 2 etc.). Could you help me, or provide, with solution for that using bash? I am not experienced in programming and I have lost hope, that I could do it myself.

A: You can combine the line with the same filename (or initial index) using a normal while read loop and then acting on 3 conditions. (1) whether it is the first line following the header; (2) where the current index is equal to the last; and (3) where the current index differs from the last. There are a number of ways to approach this, but a short bash script could look like the following:
#!/bin/bash

fn="${1:-/dev/stdin}"       ## accept filename or stdin

[ -r "$fn" ] || {           ## validate file is readable
    printf "error: file not found: '%s'\n" "$fn"
    exit 1
}

declare -i cnt=0            ## flag for 1st iteration

while read -r line; do      ## for each line in file

    ## read header, print & continue
    [ ${line//,*/} = ID ] && printf "%s\n" "$line" && continue

    line="${line//  */}"            ## strip //first scan of A....
    idx=${line//,*/}                ## parse file index from line
    line="${line#*, }"              ## strip index

    if [ $cnt -eq 0 ]; then         ## if first line - print
        printf "%s, %s" "$idx" "$line"
        ((cnt++))
    elif [ $idx = $lidx ]; then     ## if indexes equal, append
        printf ", %s" "$line"
    else                            ## else, newline & print
        printf "\n%s, %s" "$idx" "$line"
    fi

    last="$line"            ## save last line
    lidx=$idx               ## save last index

done <"$fn"

printf "\n"

Input
$ cat dat/cmbcsv.dat
ID, CC_area, CC_perimeter, CC_circularity
024_S_0985, 407.00, 192.15, 0.138530          //first scan of A
024_S_0985, 437.50, 204.80, 0.131074          //second scan of A
024_S_0985, 400.75, 198.80, 0.127420          //third scan  of A
024_S_1063, 544.50, 214.34, 0.148939          //first and only scan of B
024_S_1171, 654.75, 240.33, 0.142453          //first scan of C
024_S_1171, 659.50, 242.21, 0.141269          //second scan of C

Output
$ bash cmbcsv.sh dat/cmbcsv.dat
ID, CC_area, CC_perimeter, CC_circularity
024_S_0985, 407.00, 192.15, 0.138530, 437.50, 204.80, 0.131074, 400.75, 198.80, 0.127420
024_S_1063, 544.50, 214.34, 0.148939
024_S_1171, 654.75, 240.33, 0.142453, 659.50, 242.21, 0.141269

Note: I didn't know whether you needed all the additional commas or ellipses or if they were just there to show there could be more of the same index (e.g. ,,...,). You can easily add them if need be.

A: well if you know which scan belongs to which person you can add an extra column like patient name or id, but I guess that's if you have that original info of how much scans per person


text:
Q: Create a Modal component that can be called by calling function I'm trying to create a modal component like ant design that can be callable from outside of react node, like calling  Modal() in actions.ts.
the process of creating it most be something like that :
when we call Modal() it:

*

*creates a div element by id modal-wrapper

*append it to body

*render the <ModalContainer /> to Dom using ReactDOM.render( <ModalContainer/>, document.getElementById('modal-wrapper') )

*remove the div element after modal has been closed.
but I don't know how to implement it correctly . or this is even possible?
if you have any other recommendation I would love to hear it


text:
Q: How to keep audio play and image movement in LP when I got back from another link I have the code below that plays or pauses audio and move image within a function of react.
Currently, the audio plays even when I navigated to other pages like /Bio , /music or /contact.
Then when I return to LP, the audio still playing but I can't stop with click. And the image is stoping like a before click.
I want keep the audio play and the image movement when I go to other pages and got back to the LP too. And I want I can stop them when I got back to the LP.
LP
const LandingPage = ({ playing, setPlaying }) => {

  const [active, setActive] = useState(false);
  const classToggle = () => {
    setActive(!active);

    return [playing];
  };

  return (
    <>

Next live ※Tokio※14 / 8 / 2022 in shibuyavalley ※Gifu※ 19 / 8 / 2022 in slowroom ※Delta del Ebro※ 15 / 10 / 2022 in Mind Fest

Please click on the images!!

      <Container className="lpPhotos">
        <Row id="item1">
          <Col md={2} sm={2} xs={2}>

          </Col>
          <ClickableImage
            imgSrc={Bell}
            activeClass="bell"
            imgAlt="picture of a bell"
            audioSrc={BellAudio}
          />
          <Col md={2} sm={2} xs={2}>

          </Col>{" "}

          <ClickableImage
          imgSrc={Boat}
          activeClass="boat"
          imgAlt="picture of a boat"
          active={playing === "picture of a boat"}
          onClick={() => setPlaying ("picture of a boat")}
            // imgSrc={Boat}
            // activeClass="boat"
            // imgAlt="picture of a boat"
            // audioSrc={FuneAudio}
          />

          <ClickableImage
            imgSrc={Grass}
            className="grass"
            imgAlt="picture of a grass"
            audioSrc={GrassAudio}
          />
          <ClickableImage
            imgSrc={Pingpong}
            className="pingpong"
            imgAlt="picture of a pingpong"
            audioSrc={PingpongAudio}
          />
        </Row>
        <Row id="item2">
          <ClickableImage
            imgSrc={Bus}
            imgAlt="picture of a bus"
            audioSrc={BusAudio}
          />
          <Col md={2} sm={2} xs={2}>

          </Col>
          <ClickableImage
            imgSrc={Macba01}
            imgAlt="picture of a macba"
            audioSrc={MacbaAudio}
          />
          <ClickableImage
            imgSrc={Metro}
            imgAlt="picture of a metro"
            audioSrc={InsideMetro}
          />
          <ClickableImage
            imgSrc={MorningSun}
            imgAlt="picture of a morningSun"
            audioSrc={MorningSunAudio}
          />
          <Col md={2} sm={2} xs={2}>

          </Col>
        </Row>
      </Container>
    </>
  );
};

export default LandingPage;

App
const audio = new Audio();
audio.loop = true;
// //
// function App() {
const App = () => {

  const [playing, setPlaying] = useState();
  useEffect(() => {
    switch (playing) {
      case "picture of a boat":
        audio.src = FuneAudio;
        audio.play();
        break;
        default:
    }
    return () => {
      audio.pause();
    };
  }, [playing]);

  return (
      <Router>

      <Links />
      <Routes>
      <Route exact path="/" element={<LandingPage playing={playing} setPlaying={setPlaying}/>} />
      <Route exact path="Bio" element={<Bio />} />
      <Route exact path="Music" element={<Music />} />
      <Route exact path="Contact" element={<Contact />} />
      </Routes>

      </Router>
  );

}

export default App;

ClickableImage
export function ClickableImage({ imgSrc, imgAlt, audioSrc, onClick, active }) {
  let audio = useMemo(() => new Audio(audioSrc), [audioSrc]);

  const [playing, setPlaying] = useState(false);

  // const toggleAudio = () => setPlaying(!playing);

  useEffect(() => {
    playing ? audio.play() : audio.pause();
    audio.loop = true;
  }, [playing, audio]);

  useEffect(() => {
    const stopPlaying = () => setPlaying(false);
    audio.addEventListener("ended", stopPlaying);
    return () => audio.removeEventListener("ended", stopPlaying);
  }, [audio]);

  const classToggle = () => {
    setPlaying(!playing);
  };

  return (
    <Col md={2} sm={2} xs={2}>
      <img
        src={imgSrc}
        className={"img-fluid" + (playing ? ` img-playing` : "")}
        alt={imgAlt}
        onClick={() => {
          classToggle();
        }}
      />
    </Col>
  );
}

export default ClickableImage;

enter link description here


text:
Q: Dequeue always fails, queue is always empty I do not know what the heck is wrong with my code that it never Dequeus the queue, instead isEmpty always meets true.
class ConcurrentQueue
{
private:
QQueue<QByteArray> dataStore;

public:

void Enqueue(QByteArray value);
QByteArray Dequeue();

bool isEmpty();
private:
QMutex mutex;
};

void ConcurrentQueue::Enqueue(QByteArray value)
{
qDebug() << dataStore.length();
mutex.lock();
dataStore.enqueue(value);
mutex.unlock();
qDebug() << dataStore.length();
}

QByteArray ConcurrentQueue::Dequeue()
{

// mutex.lock();
// return dataStore.dequeue();
// mutex.unlock();

QByteArray tmp;

mutex.lock();

if(!dataStore.isEmpty())
{
tmp = dataStore.dequeue();
}

mutex.unlock();

return tmp;
}

bool ConcurrentQueue::isEmpty()
{
return dataStore.isEmpty();
}

next a timer is connected to a slot to Enqueu a packet every lt's say 10 milliseconds:
QByteArray built((char*)data, len) ;
//qDebug() << built.toHex();
qDebug() << "EnQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ";
queue.Enqueue(built);

A thread regularly checks if this queue is not empty it dequeues the queue and does something, but isEmplty always returns true
if(queue.isEmpty())
{
qDebug() << "#####################################";
return;
}
//NEVER COMES HERE
QByteArray rd15Bytes = queue.Dequeue();

here's the thread:
Write::Write()
{
}

void Write::run(){
while(1)
{
rs.writeToSerialPort(); // in this function above always isemplty is true

this->msleep(10);
}
}


text:
Q: gulp silently failing - no errors printed to console My gulp file is not emitting any errors on either standard gulp methods like gulp.src() with non existant paths nor are stream errors being called by their handler.  I've included a simple file that silently fails, printing only the starting.. and finished.. default messages.
var //
  gulp      = require( "gulp" ),
  gulpUtil  = require( "gulp-util" ),
  sass      = require( "gulp-ruby-sass");

 gulp.task( "default", function() {
  gulp.src( "path-that-does-not-exist.scss" )
  .pipe( sass() )
  .on( "error", function( err ) {
    console.log( "this should print" );
  })
  .pipe( gulp.dest( "./client-side/public/compiled" ) );
 });

A: If the path does not exist, gulp.src successfully pushes exactly nothing through the pipe, the sass and dest tasks successfully are never called, and with that, gulp.src's stream ends, signaling the default task is complete, and gulp exits.  It has done exactly what you've told it to.  :D

A: Okay, so Gulp is working "correctly." But what I'm hearing in your question is that it would be nice if Gulp could just tell you if a file doesn't exist.
I use gulp-expect-file as such
var coffee = require('gulp-coffee');
var expect = require('gulp-expect-file');

gulp.task('mytask', function() {
  var files = ['idontexist.html'];

  return gulp.src(files)
    .pipe(expect(files))
    .pipe(coffee());
});

Now you'll see this in the terminal:

A: I agree with @adamjgrant use gulp-expect-file.
var expect = require('gulp-expect-file'),
    gulp = require('gulp');

gulp.task('task', function() {
    var files = ['src/js/*.js'];
    gulp
        .src(files)
        .pipe(expect(files));
});

PS: Grunt.js handles this with nonull:true
lint: {
    src: ['gruntfile.js', 'gulpfile.js'],
    nonull: true
}