text:
Q: Flutter - performance drop (jank) with too many Stack children I've to render a tree with an unknown amount of leaves. But when the amount of leaves is too high, the performance of the app drops dramatically. What can I do to improve the performance? The number of leaves can go to 1000 so it's normal that a stack of 1000 children will drop the performance but what can I do about it? Thanks in advance!
class Tree extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Random random = new Random();
    final leaf = Provider.of<Leafs>(context, listen: false);
    final heightTree = (MediaQuery.of(context).size.width - 60) * (772 / 480); //Ratio of the tree
    final heightTreeTrunk = heightTree * (169 / 772); //Ratio of the treetrunk
    const leafSize = 20.0;
    final children = <Widget>[
      Padding(
        padding: EdgeInsets.fromLTRB(30, 15, 30, 0),
        child: Image.asset(
          'assets/images/tree2.png',
          color: Colors.grey.shade600,
        ),
      ),
    ];
    for (var i = 0; i < leaf.tot; i++) {
      double angle = random.nextInt(100) / 100 * 2 * pi;
      double ran = sqrt(random.nextInt(100) / 100);
      children.add(
        Padding(
          padding: EdgeInsets.fromLTRB(5, 0, 5, heightTreeTrunk),
          child: Align(
            alignment: Alignment(
              ran * cos(angle),
              ran * sin(angle),
            ),
            child: RotationTransition(
              turns: AlwaysStoppedAnimation(random.nextInt(360) / 360),
              child: SizedBox(
                height: leafSize,
                width: leafSize,
                child: Image.asset(
                  'assets/images/leaf8.png',
                ),
              ),
            ),
          ),
        ),
      );
    }
    return Container(
      height: heightTree,
      child: Stack(children: children,),
    );
  }
}

Update:
Here is my code for the moment.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:math';

import '../painter/leaf.dart';
import '../providers/number_leaf.dart';

class Tree extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Random random = Random();
    final _numberLeaf = Provider.of<NumberLeaf>(context, listen: false);
    final _heightTree = (MediaQuery.of(context).size.width - 60) *
        (772 / 480); //Ratio of the tree
    final _heightTreeTrunk = _heightTree * (120 / 772); //Ratio of the treetrunk

    final _children = <Widget>[];

    for (var i = 0; i < _numberLeaf.tot; i++) {
      final double angle = random.nextDouble() * 2 * pi;
      final double ran = sqrt(random.nextDouble());
      _children.add(
        Align(
          alignment: Alignment(
            ran * cos(angle),
            ran * sin(angle),
          ),
          child: Transform.rotate(
            angle: random.nextDouble() * 2 * pi,
            child: Leaf(),
          ),
        ),
      );
    }
    return Container(
      decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('assets/images/tree2.png'),
        colorFilter: ColorFilter.mode( Colors.grey.shade600, BlendMode.srcIn)
      ),
    ),
      height: _heightTree,
      child: Padding(
        padding: EdgeInsets.fromLTRB(5, 0, 5, _heightTreeTrunk),
        child: Stack(
          children: _children,
        ),
      ),
    );
  }
}

Here is the code for the leafpainter
import 'package:flutter/material.dart';

class Leaf extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: const Size(40, 60), //size of the leaf
      painter: LeafPainter(),
    );
  }
}

class LeafPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final double width = size.width;
    final double height = size.height;

    final Paint paint_0 = Paint()
      ..color = const Color.fromARGB(200, 19, 150, 25)  //green
      ..style = PaintingStyle.fill
      ..strokeWidth = 14.95;
    final Paint paint_1 = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    final Paint paint_2 = Paint()
      ..color = Colors.brown.shade800
      ..style = PaintingStyle.fill
      ..strokeWidth = 12.23;

    Path path_0 = Path();
    path_0.moveTo(width * 0.1223000, height * 0.3841667);
    path_0.quadraticBezierTo(width * 0.1499250, height * 0.2975000,
        width * 0.2059000, height * 0.2272167);
    path_0.cubicTo(width * 0.2595500, height * 0.1635667, width * 0.2943500,
        height * 0.1454833, width * 0.4089750, height * 0.1237833);
    path_0.cubicTo(width * 0.5149250, height * 0.1089167, width * 0.6031750,
        height * 0.1097167, width * 0.6993250, height * 0.0974333);
    path_0.quadraticBezierTo(width * 0.8040250, height * 0.0849167,
        width * 0.8882000, height * 0.0280833);
    path_0.quadraticBezierTo(width * 0.8890750, height * 0.1651667,
        width * 0.8404250, height * 0.2313500);
    path_0.cubicTo(width * 0.7884500, height * 0.3151167, width * 0.7394000,
        height * 0.3545667, width * 0.6384750, height * 0.3916667);
    path_0.cubicTo(width * 0.5696250, height * 0.4122500, width * 0.4952750,
        height * 0.4190667, width * 0.3900750, height * 0.4185833);
    path_0.quadraticBezierTo(width * 0.2472000, height * 0.4168167,
        width * 0.1223000, height * 0.3841667);
    path_0.close();

    canvas.drawPath(path_0, paint_0);  // the leaf
    canvas.drawPath(path_0, paint_1);  // the border of the leaf

    final BorderRadius borderRadius = BorderRadius.circular(15);
    final Rect rect = Rect.fromLTRB(
        0.03 * width, 0.39 * height, 0.135 * width, 0.37 * height);
    final RRect outer = borderRadius.toRRect(rect);
    canvas.drawRRect(outer, paint_2);  // the stem of the leaf
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

This is how the tree looks like:
Tree

A: You could probably try replacing your RotationTransition with a Transform.rotate widget since you are using an AlwaysStoppedAnimation.
And you could also use a Positioned widget instead of your Alignment + Padding widget!
And note that the most effective approach would be to draw the entire three using one single CustomPainter widget!


text:
Q: Composite Shared Keys and Entity I'm working on a database where tables have composite keys and part of that key is shared between tables. I don't know how to set the relationship properly in entity.
Imagine the following:
public class Sale
{
        public long ID { get; set; } //Key
        public long RetailerID { get; set; } //Key
        public virtual Location Location { get; set; } //Foreign, Many-to-One
}

public class Location
{
        public long ID { get; set; } //Key
        public long RetailerID { get; set; } //Key
        public virtual IEnumerable<Sale> Sales { get; set; } //Relationship, One-to-Many
}

Both are using the fluent API to define the composite keys OnModelCreating.
modelBuilder.Entity<Sale>().HasKey(x => new { x.RetailerID, x.ID });
modelBuilder.Entity<Location>().HasKey(x => new { x.RetailerID, x.ID });

However I am unsure how to finish this to set up the proper relationship as it sets itself up as having duplicate columns for RetailerID which is unnecessary. How is this supposed to be done properly (if at all?)

A: It's possible in several ways, all including additional LocationID FK property (either explicit or shadow).

*

*With shadow FK property (without modifying the entity model):

Data Annotations:
[Required]
[ForeignKey("RetailerID, LocationID")]
public virtual Location Location { get; set; } //Foreign, Many-to-One

Fluent API:
modelBuilder.Entity<Sale>()
    .HasOne(e => e.Location)
    .WithMany(e => e.Sales)
    .HasForeignKey("RetailerID", "LocationID")
    .IsRequired();

*

*with explicit FK property

Model:
public long LocationID { get; set; } // added
public virtual Location Location { get; set; } //Foreign, Many-to-One

Data annotations:
[ForeignKey("RetailerID, LocationID")]
public virtual Location Location { get; set; } //Foreign, Many-to-One

Fluent API:
modelBuilder.Entity<Sale>()
    .HasOne(e => e.Location)
    .WithMany(e => e.Sales)
    .HasForeignKey(e => new { e.RetailerID, e.LocationID });

(note: use either data annotations or fluent API - no need for both)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Plot component frequencies, amplitudes and phases of a mixed signal I generated a mixed signal by adding two sin waves (whose parameters I can change dynamically) and plotted them. I used the code for findPeriod from here to find the amplitudes, frequencies and phases of the component signals. Below is what I'm upto:
Manipulate[Grid[
s1 = a1*Sin[ω1 t + ϕ1];
s2 = a2*Sin[ω2 t - ϕ2];
s = s1 + s2;
{{Plot[{s1, s2}, {t, -2 π, 2 π}, PlotRange -> {-10.1, 10.1},
  ImageSize -> {500, 200}, AspectRatio -> 2/5]}, {Plot[
 s, {t, -2 π, 2 π}, PlotRange -> {-10.1, 10.1},
 ImageSize -> {500, 200}, AspectRatio -> 2/5]}},
 TableForm[Sort[findPeriod[s, 0.2][[2]], #1[[2]] > #2[[2]] &],
 TableHeadings -> {None, {"Freq", "Amp", "Phase"}}]],
"X1" -> {{ω1, 1, "frequency of wave 1"}, 1, 10},
"X2" -> {{ω2, 1, "frequency of wave 2"}, 1, 10},
"Y1" -> {{a1, 1, "amplitude of wave 1"}, 1, 5},
"Y2" -> {{a2, 1, "amplitude of wave 2"}, 1, 5},
"Y1Cyclic" -> {{ϕ1, 1, "phase of wave 1"}, 0, 2 π},
"Y2Cyclic" -> {{ϕ2, 1, "phase of wave 2"}, 0, 2 π}]

But while I'm trying to apply findPeriod inside Manipulate, I'm getting an error. How can I resolve it?

A: The code referenced in the question:
Clear["Global`*"]

Clear[findPeriod];
findPeriod[data_, threshold_] :=
 Module[{fs, s1, s = {}, i, a0f, af, pf, pos, fr, frpos, fdata,
   fdatac, n, per}, n = Length[data];
  fs = Fourier[data];
  s1 = Drop[fs, -Floor[Length[fs]/2]];
  For[i = 1, i < Length[s1], i++,
   If[Abs[fs][[i + 1]] > threshold, AppendTo[s, i + 1]]];
  a0f = Abs[fs[[1]]]/Sqrt[n];
  af = 2/Sqrt[n] Abs[fs][[s]];
  pf = Arg[fs][[s]];
  {a0f, Transpose[{s, af, pf}]}]

Clear[reconstruct];
reconstruct[data_, fp_] := Module[{n}, n = Length[data];
  Show[ListLinePlot[data, PlotStyle -> Black],
   Plot[fp[[1]] +
     Sum[fp[[2, j, 2]] Cos[
        2 Pi (fp[[2, j, 1]] - 1)/n t - fp[[2, j, 3]]], {j, 1,
       Length[fp[[2]]]}], {t, 0, n}, PlotStyle -> Red]]]

Works using a Table of s values since findPeriod needs a list of data points:
Manipulate[
 {
  s1[t_] := a1*Sin[ω1 t + ϕ1];
  s2[t_] := a2*Sin[ω2 t - ϕ2];
  s[t_] := s1[t] + s2[t];
  data = Table[Evaluate[s[t]], {t, -2 π, 2 π, π/50}];

  Plot[{s1[t], s2[t]}, {t, -2 π, 2 π}, PlotRange -> {-10.1, 10.1},
   ImageSize -> {300, 300}],
  Plot[s[t], {t, -2 π, 2 π}, PlotRange -> {-10.1, 10.1},
   ImageSize -> {300, 300}],
  TableForm[Sort[findPeriod[data, 0.2][[2]], #1[[2]] > #2[[2]] &],
   TableHeadings -> {None, {"Freq", "Amp", "Phase"}}]},

 "X1" -> {{ω1, 1, "frequency of wave 1"}, 1, 10},
 "X2" -> {{ω2, 1, "frequency of wave 2"}, 1, 10},
 "Y1" -> {{a1, 1, "amplitude of wave 1"}, 1, 5},
 "Y2" -> {{a2, 1, "amplitude of wave 2"}, 1, 5},
 "Y1Cyclic" -> {{ϕ1, 1, "phase of wave 1"}, 0, 2 π},
 "Y2Cyclic" -> {{ϕ2, 1, "phase of wave 2"}, 0, 2 π}]


text:
Q: Convert CSV to JSON and JSON to CSV using PowerShell I have a CSV file that I am trying to convert to JSON using PowerShell.
The CSV file contains the following data.
web_url.csv
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/

I would like to convert to json in the following format. Similarly how do you convert this json back to original csv in the format shown above?
web_url.json
{
    "wikipedia": "https://en.wikipedia.org/wiki/%s",
    "wolframalpha": "http://www.wolframalpha.com/input/?i=%s",
    "drive": "http://www.drive.google.com/"
}

When I run the command,

Get-Content -path web_url.csv | ConvertFrom-Csv -Delimiter ',' |
  ConvertTo-Json

it returns the following output which is not what I want.
[
    {
        "wikipedia":  "wolframalpha",
        "https://en.wikipedia.org/wiki/%s":  "http://www.wolframalpha.com/input/?i=%s"
    },
    {
        "wikipedia":  "drive",
        "https://en.wikipedia.org/wiki/%s":  "http://www.drive.google.com/"
    }
]

A: # PowerShell script

import-csv "SampleInput.csv" | ConvertTo-Json | Add-Content -Path "output.json"

A: Your csv doen't look like a "proper" csv to me: columns are swapped with rows. If you have control over input file, you may fix it there already:
@'
wikipedia,wolframalpha,drive
https://en.wikipedia.org/wiki/%s,http://www.wolframalpha.com/input/?i=%s,http://www.drive.google.com/
'@ | ConvertFrom-Csv | ConvertTo-Json

If that is not possible, you just have to perform some extra steps to get what you need:
$propertyList = @'
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
'@ | ConvertFrom-Csv -Header Name, Value

$properties = [ordered]@{}

foreach ($property in $propertyList) {
    $properties.Add($property.Name, $property.Value)
}

New-Object PSObject -Property $properties | ConvertTo-Json

And back, again - some extra work is required:
(@'
{
    "wikipedia":  "https://en.wikipedia.org/wiki/%s",
    "wolframalpha":  "http://www.wolframalpha.com/input/?i=%s",
    "drive":  "http://www.drive.google.com/"
}
'@ | ConvertFrom-Json).PSObject.Properties |
    Select-Object Name, Value |
    ConvertTo-Csv -NoTypeInformation |
    Select-Object -Skip 1

A: what about this ?
$csv=@"
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
"@

$obj= $csv |convertfrom-csv -delim ',' -Header "name","url"
#$obj

$json=$obj  |convertto-json
#$json

$csv2 =$json |convertfrom-json |select -expand syncroot  |convertto-csv -NoTypeInformation -Delimiter ','
#$csv2


text:
Q: How to insert date/time in the UTC zone into MySQL via EclipseLink using Joda-Time? I need to store date/time in UTC zone into MySQL database (of a DATETIME type column). When a user enters a date, it is first converted to org.joda.time.DateTime by a JSF converter.
Before inserting this date into MySQL database, it again needs to be converted to java.util.Date - thanks to EclipseLink.
The following is the converter that again converters org.joda.time.DateTime to java.util.Date though it is not really needed to see this converter.
package joda.converter;

import java.util.Date;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public final class JodaDateTimeConverter implements Converter
{
    private static final long serialVersionUID = 1L;

    @Override
    public Object convertObjectValueToDataValue(Object objectValue, Session session)
    {
        return objectValue instanceof DateTime?((DateTime) objectValue).withZone(DateTimeZone.UTC).toDate():null;
    }

    @Override
    public Object convertDataValueToObjectValue(Object dataValue, Session session)
    {
        return dataValue instanceof Date?new DateTime((Date) dataValue):null;
    }

    @Override
    public boolean isMutable()
    {
        return true;
    }

    @Override
    public void initialize(DatabaseMapping databaseMapping, Session session)
    {
        databaseMapping.getField().setType(java.util.Date.class);
    }
}

In the convertObjectValueToDataValue() method (the first one), the value of the first parameter - objectValue received is the correct UTC date/time converted by Joda-Time in a  JSF converter.
For example, if I entered a date - 02-Oct-2013 11:34:26 AM then, the value of objectValue would be - 2013-10-02T06:04:26.000Z. This date/time should be inserted into the database.
But when this value is converted by this expression - (DateTime) objectValue).withZone(DateTimeZone.UTC).toDate(), it is again evaluated to 2013-10-02 11:34:26.0 and this value is supplied to the database which is incorrect.
Anyway, how to set the UTC zone to (DateTime) objectValue).withZone(DateTimeZone.UTC).toDate()?

A property of type org.joda.time.DateTime is designated in a model class as follows.
@Column(name = "discount_start_date", columnDefinition = "DATETIME")
@Converter(name = "dateTimeConverter", converterClass = JodaDateTimeConverter.class)
@Convert("dateTimeConverter")
private DateTime discountStartDate;

EDIT: (The following JSF converter works as expected along with the EclipseLink converter above which remains intact - from the only answer until now by BalusC)
This is my JSF converter.
package converter;

import java.util.TimeZone;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import util.Utility;

@ManagedBean
@RequestScoped
public final class DateTimeConverter implements Converter
{
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value)
    {
        DateTime dateTime=null;

        try
        {
            dateTime = DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("IST"))).parseDateTime(value);
        }
        catch (IllegalArgumentException e)
        {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", Utility.getMessage("datetime.converter.error", DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").print(DateTime.now().withZone(DateTimeZone.forID("Asia/Kolkata"))))), e);
        }
        catch(UnsupportedOperationException e)
        {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", Utility.getMessage("datetime.converter.error", DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").print(DateTime.now().withZone(DateTimeZone.forID("Asia/Kolkata"))))), e);
        }
        return dateTime;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value)
    {
        DateTimeFormatter dateTimeFormatter=DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").withZone(DateTimeZone.forID("Asia/Kolkata")); //This zone will be tackled/handled later from the database to display.
        return value instanceof DateTime?dateTimeFormatter.print((DateTime)value):null;
    }
}

A: Your concrete problem is caused because DateTime#toDate() doesn't use the time zone during the conversion to java.util.Date. It basically returns new Date(millis) wherein the millis is the internally stored epoch time of DateTime instance, exactly as described by DateTime javadoc and required by the java.util.Date constructor.
In other words, the withZone(DateTimeZone.UTC) part has totally no effect here. The code behaves exactly the same as if that part was absent. That explains why you end up with the originally entered time.
Technically, the problem is in your custom JSF converter which converts from String to DateTime. That converter is apparently not taking the time zone into account and assuming that the input is already in GMT timezone (as by default). The converter must be instructed that the input is in IST timezone. If you were using standard java.util.Date property with standard JSF <f:convertDateTime>, then you could have solved it by setting its timeZone attribute to IST.
<h:inputText value="#{bean.date}">
    <f:convertDateTime pattern="dd-MMM-yyyy hh:mm:ss a" locale="en" timeZone="IST" />
</h:inputText>

Your custom JSF converter should under the covers be doing exactly the same: tell the API that the supplied String is in IST timezone instead of letting it assume that it's already in GMT timezone. You didn't show the custom JSF converter anywhere, so it's hard to supply the exact answer, but it should boil down to the following kickoff example:
String inputDateString = "02-Oct-2013 11:34:26 AM";
String inputDatePattern = "dd-MMM-yyyy hh:mm:ss a";
TimeZone inputTimeZone = TimeZone.getTimeZone("IST");

DateTime dateTime = DateTimeFormat
    .forPattern(inputDatePattern)
    .withZone(DateTimeZone.forTimeZone(inputTimeZone))
    .parseDateTime(inputDateString);

The resulting DateTime instance will end up having the right internal epoch time in millis.


text:
Q: Android Webview cannot load CSS and show blockquote font color effect I have got the following html to be loaded on CSS through android webview . When it comes to the execution. there has no obseravle changes to the font color changes onto my wordings tagged by blockquote
the below is my html code :

        <title>Example</title>
        <link rel="stylesheet" type="text/css" href="file:///android_asset/style.css" />

拜年根本係學溝通同交際#hehe#

唔明點解去完親戚屋企拜年 過幾日親戚要黎返我屋企再拜過年 [banghead]

CSS:
@CHARSET "UTF-8";

blockquote{
color:#d4d3d3
  }

Actual android code
viewHolder.txContent = (WebView) v.findViewById(R.id.replycontent);
        WebSettings settings = viewHolder.txContent.getSettings();
        settings.setDefaultTextEncodingName("utf-8");

        settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        viewHolder.txContent.setFocusable(false);
        viewHolder.txContent.setClickable(true);
        viewHolder.txContent.setBackgroundColor(Color.parseColor("#00FFFFFF"));

String htmlPreffix = "<title>Example</title><link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/style.css\" />";
            String htmlSuffixString = "";

            System.out.println("htmlParsed");
            System.out.println(htmlPreffix + htmlParsed + htmlSuffixString);
            viewHolder.txContent.loadDataWithBaseURL(null, htmlParsed, "text/html", "utf-8", null);

A: You're missing the opening  tag.


text:
Q: Does it make sense to reuse Runnables in a thread pool? I'm implementing a thread pool for processing a high volume market data feed and have a question about the strategy of reusing my worker instances that implement runnable which are submitted to the thread pool for execution. In my case I only have one type of worker that takes a String and parses it to create a Quote object which is then set on the correct Security. Given the amount of data coming off the feed it is possible to have upwards of 1,000 quotes to process per second and I see two ways to create the workers that get submitted to the thread pool.
First option is simply creating a new instance of a Worker every time a line is retrieved from the underlying socket and then adding it to the thread pool which will eventually be garbage collected after its run method executed. But then this got me thinking about performance, does it really make sense to instantiate 1,0000 new instances of the Worker class every second. In the same spirit as a thread pool do people know if it is a common pattern to have a runnable pool or queue as well so I can recycle my workers to avoid object creation and garbage collection. The way I see this being implemented is before returning in the run() method the Worker adds itself back to a queue of available workers which is then drawn from when processing new feed lines instead of creating new instances of Worker.
From a performance perspective, do I gain anything by going with the second approach or does the first make more sense? Has anyone implemented this type of pattern before?
Thanks - Duncan

A: I use a library I wrote called Java Chronicle for this.  It is designed to persist and queue one million quotes per second without producing any significant garbage.
I have a demo here where it sends quote like objects with nano second timing information at a rate of one million messages per second and it can send tens of millions in a JVM with a 32 MB heap without triggering even a minor collection. The round trip latency is less than 0.6 micro-seconds 90% of the time on my ultra book. ;)

from a performance perspective, do I gain anything by going with the second approach or does the first make more sense?

I strongly recommend not filling your CPU caches with garbage.  In fact I avoid any constructs which create any significant garbage.  You can build a system which creates less than one object per event end to end.  I have a Eden size which is larger than the amount of garbage I produce in a day so no GCs minor or full to worry about.

Has anyone implemented this type of pattern before?

I wrote a profitable low latency trading system in Java five years ago. At the time it was fast enough at 60 micro-seconds tick to trade in Java, but you can do better than that these days.
If you want low latency market data processing system, this is the way I do it.  You might find this presentation I gave at JavaOne interesting as well.
http://www.slideshare.net/PeterLawrey/writing-and-testing-high-frequency-trading-engines-in-java

EDIT I have added this parsing example
ByteBuffer wrap = ByteBuffer.allocate(1024);
ByteBufferBytes bufferBytes = new ByteBufferBytes(wrap);
byte[] bytes = "BAC,12.32,12.54,12.56,232443".getBytes();

int runs = 10000000;
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
    bufferBytes.reset();
    // read the next message.
    bufferBytes.write(bytes);
    bufferBytes.position(0);
    // decode message
    String word = bufferBytes.parseUTF(StopCharTesters.COMMA_STOP);
    double low = bufferBytes.parseDouble();
    double curr = bufferBytes.parseDouble();
    double high = bufferBytes.parseDouble();
    long sequence = bufferBytes.parseLong();
    if (i == 0) {
        assertEquals("BAC", word);
        assertEquals(12.32, low, 0.0);
        assertEquals(12.54, curr, 0.0);
        assertEquals(12.56, high, 0.0);
        assertEquals(232443, sequence);
    }
}
long time = System.nanoTime() - start;
System.out.println("Average time was " + time / runs + " nano-seconds");

when set with -verbose:gc -Xmx32m it prints
Average time was 226 nano-seconds

Note: there are no GCes triggered.

A: I'd use the Executor from the concurrency package.  I believe it handles all this for you.

A:
does it really make sense to instantiate 1,0000 new instances of the Worker class every second.

Not necessarily however you are going to have to be putting the Runnables into some sort of BlockingQueue to be able to be reused and the cost of the queue concurrency may outweigh the GC overhead.  Using a profiler or watching the GC numbers via Jconsole will tell you if it is spending a lot of time in GC and this needs to be addressed.
If this does turn out to be a problem, a different approach would be to just put your String into your own BlockingQueue and submit the Worker objects to the thread-pool only once.  Each of the Worker instances would dequeue from the queue of Strings and would never quit. Something like:
public void run() {
    while (!shutdown) {
        String value = myQueue.take();
        ...
    }
}

So you would not need to create your 1000s of Workers per second.

A: Yes of course, something like this, because OS and JVM don't care about what is going on a thread, so generally this is a good practice to reuse a recyclable object.

A: I see two questions in your problem. One is about thread pooling, and another is about object pooling. For your thread pooling issue, Java has provided an ExecutorService . Below is an example of using an ExecutorService.
Runnable r = new Runnable() {
    public void run() {
        //Do some work
    }
};

// Thread pool of size 2
ExecutorService executor = Executors.newFixedThreadPool(2);
// Add the runnables to the executor service
executor.execute(r);

The ExecutorService provides many different types of thread pools with different behaviors.
As far as object pooling is concerned, (Does it make sense to create 1000 of your objects per second, then leave them for garbage collection, this all is dependent on the statefulness and expense of your object. If your worried about the state of your worker threads being compromised, you can look at using the flyweight pattern to encapsulate your state outside of the worker. Additionally, if you were to follow the flyweight pattern, you can also look at how useful Future and Callable objects would be in your application architecture.


text:
Q: Downloading Reports in Amazon Advertising API I got the Report Id and using the Report Id i could get S3 Downloadable link. But when i try to use the link it shows - Access Unauthorised.

A: You need to do a GET request against the download link. The URL requires authentication as well, so the authorization header must be passed too.
Edit I am adding a function that I created that downloads the GZipped file and extracts the Json in it, in case it helps anyone else:
import requests
import gzip
import json
import io

def report_download():
    req = requests.get(url, headers=headers)
    response = req.content
    zip_file = io.BytesIO(response)
    with gzip.open(zip_file, 'rb') as f:
        file_content = f.read()

    json_data = json.loads(file_content)
    with open("filename.json", "w") as outfile:
        json.dump(json_data, outfile)

A: Here's an easy way to download the report with python and pandas
def api_download_report_resp(access_token, profile_id, report_id):
    url = f"https://advertising-api.amazon.com/v2/reports/{report_id}/download"
    client_id = os.getenv("AMAZON_ADS_API_CLIENT_ID")

    with requests.Session() as sess:
        sess.headers["Amazon-Advertising-API-ClientId"] = client_id
        sess.headers["Amazon-Advertising-API-Scope"] = profile_id
        sess.headers["Authorization"] = f"Bearer {access_token}"
        sess.headers["Content-Type"] = "application/json"
        resp = sess.get(url)

    return resp

resp = api_download_report_resp(access_token, profile_id, report_id)
print(resp)
# <Response [200]>

import pandas as pd
import io

fobj = io.BytesIO()
fobj.write(resp.content)
fobj.seek(0)
df = pd.read_json(fobj, compression='gzip')


text:
Q: Basic Probability Question: What is the probability that my data point belong to a given distribution? I have a distribution, D and a data point, X. Assuming that the distribution is Normal with parameters mu and sigma, what is the probability that X belongs to D?
I tried looking for the answer online but I couldn't find any. I looked up different questions including this one and this but couldn't find my answer.
Edit 1: I am looking at soft assignments in probabilistic clustering (i.e. mixture models) and N is one of the clusters. Computing that probability that a point X belongs to a cluster N is determined by the prior probability and N(x | mu, sigma). My question is how to calculate N(x| mu, sigma).


text:
Q: ZEND Left Join Distinct Query I have this SQLquery:
select *
from locations
left join (select location_id, name as occupied
           from meetings
           where start < $value1 and end > $value2 limit 1) m
           on locations.id = m.location_id;

Every location from locations table has many meetings, and every meeting belongs to a specific location. Every meeting has a start time and an end time. With that query, i want to get all the locations from the database and add a booked column to everyone, and if the location is occupied in the given interval, the occupied column's value would be the overlapping's meeting name.
The SQL query returns exactly what I want (ex. Location 1, Location 2, Location 3, etc).
I want to use the same query but in my ZEND model. Now I have
$model = new Model_Location();
$m = new Model_Meeting();
$model->getSelect()
      ->joinLeft(
           "meetings as m",
           "m.location_id = $model.id AND m.start < $value1 AND m.end > $value2",
           array('occupied' => "m.name"));

which returns what I expect, but for every overlapping meeting, I get an entry it's lcoation, resulting in Location 1, Location 1, Location 2, Location 2, Location 2, Location 3, etc. How can I get only the distinct values? I know that limit isn' present in my zend query, but I don't know where to use it. I tried after joinLeft, and before it, but in those cases it limit's my model to just 1 entry, not just the distinct ones. I also tried ->distinct() but didn't work either.

A: GROUP BY is what you are looking for, so :
$model = new Model_Location();
$m = new Model_Meeting();
$model->getSelect()
      ->joinLeft(
           "meetings as m",
           "m.location_id = $model.id AND m.start < $value1 AND m.end > $value2",
           array('occupied' => "m.name"));
      ->group('$model.id')

Side note : your raw sql query is not exactly the same as your zend one, since in your raw query you're doing a subquery, and in the zend one you're doing a direct join (which is better).


text:
Q: How to create a group for a string / filename? OK, I am a newbee to stackoverflow.
Developing an ecommerce site, I have as many as 50 unique images on the home page that needs to be loaded. I am using the Amazon CDN for my images and all these files are in a bucket with a unique domain.
I would like to have multiple domains mapped to this bucket. However for each image, I should be able to find at runtime, which domain it was servered last time so that the caching is most optimized. My idea is to have a function func(filename) which can return a value between 0-9 every-time for the same filename. This can be used for the domain name.
I do not want the func to be very heavy like a hash and in this case, I would want a collision rather than avoid it.
A simple method would be to use a intval(filename) and then use the least significant digit. However I am not sure this would be a good solution and if the spread would be balanced.
Any suggestions ?

A: How about something as simple as this:
function customHash($str) {
    $hash = 0;

    for ($i = 0; $i < strlen($str); $i++) {
        $hash += ord($str[$i]);
    }

    return $hash % 10;
}

You can optimize this in many ways, like using iconv_strlen() to treat utf-8 strings right and instead of the whole length, $len = max(6, $strlen); could be used (though the perfomance boost isn't really significant...).


text:
Q: Excel: Automate formatting from generated table I am trying to create a workflow to make the lives of my project managers easier.
I have financial profile of a client emailed to me automatically every month. The table lists the overall project information and then individual information for each phase of each project. the information is organized like below:
(Information starts at cell C7, headers are above that)
Snapshot of Table
I want to create an environment where project managers can guess the percent completion of each phase for upcoming months to build a financial outlook plan for the client. Then the totals for each phase is summed and shown on the line for the overall project.
I wanted to automate the formatting process for this file. I could use some guidance or direction?
I have created a general format but do not know the best way to automate this.
Desired Output
Edit:
I came up with some ugly work arounds. But am hoping to clean this up a bit. And I still need a solution for automating the process of bringing in data.
Working Solution V1
I've done the following:
Column K is used to calculate each rows % completion.
Total Contract $$$ / JTD Billed $$$ (columns I/G) =IF(G7>0,I7/G7,)
Columns L, M, N are inputs for the project manager to estimate the completion percentage of each phase by month.
Columns O, P, Q are the outputs calculating the projected billable by month.
(delta % Complete) * Total Contract $$$ (Columns delta(K-N) * G)
However, because I wanted to sum the total billable amounts for each project in the project line, I needed a way to separate the project lines and phase lines.
So, I created Column R with a Boleen value (true/false) to determine if a line was a project overview or a phase. It compares the project number (column C) to the row above it. =IF(C7=C6,TRUE)
Then I needed a way to know how many rows (phases) below a project line belong to the project. I used column S to calculate with =MATCH(1,--(R8:R100=FALSE),0)-1 which counts the number of columns to the next 'False' value.
I then used Columns T, U, V to sum the projected billable per phase per month for the project. =IF(NOT($R7),SUM(O8:INDEX(O8:O1000,$S7,1)),0)
I don't like this formula because its messy. I can't figure out how to write O8:O (like O:O).
And I showed the projected billables with this formula: =IF($R7,IF(AND((L7-K7)*$G7>0,(L7-K7)<1),(L7-K7)*$G7,0),T7). If column R identifies a project row, columns O, P, Q show the sums of the phases. If column R identifies a phase row, columns O, P, Q calculate the billable amount.
Additionally, I used conditional formation using column R to visually distinguish between projects and phases.


text:
Q: How to draw a 2 mean line plots with CI in 1 plot I'm trying to draw 2 line of means in one plot with the CI. I used gplots which has function plotmeans to draw a line but I only can draw one line in one plot. Anyone could help? Thanks a lot
This is an example of my data
Group  MC  MB
G1     5    10
G2     8    8
G3     14   7
G4     20   6
G1     10   15
G2     16   13
G3     30   9
G4     25   7
G1     15   29
G2     20   22
G3     25   20
G4     35   15

I would like to plot MC and MB as a line which the value is a mean value and CI at each group. The xlab will be group. ylab is the value of MC and MB.
I would expect something like this

Thanks a lot.

A: This can be done with a combination of tidyr, dplyr and ggplot2.
# Your data
group <- c("G1", "G2", "G3", "G4", "G1", "G2", "G3", "G4", "G1", "G2", "G3", "G4")
mc <- c(5, 8, 14, 20, 10, 16, 30, 25, 15, 20, 25, 35)
mb <- c(10, 8, 7, 6, 15, 13, 9, 7, 29, 22, 20, 15)
df <- data.frame(group, mc, mb)

First we gather your data to long format with the columns category (cat) and value.
# Requires library "tidyr"
library(tidyr)

# Gathering data
df_gathered <- gather(df, cat, value, 2:3)

Next you calculate the mean and error for each combination of group and category:
# Requires the library "dplyr"
library(dplyr)

# Calculating mean and error by group
df_mean_by_group <- df_gathered %>%
  group_by(group, cat) %>%
  summarise(mean = mean(value), error = qnorm(0.975)*sd(value)/length(value))

Finally we plot grouping the lines by category (to connect them), and we color them also by category:
# Requires "ggplot2"
library(ggplot2)

# Plotting it all
ggplot(df_mean_by_group, aes(x=group, y=mean, colour=cat, group=cat)) +
  geom_errorbar(aes(ymin=mean-error, ymax=mean+error), colour="black", width=.1) +
  geom_line() +
  geom_point(size=3)


text:
Q: Needing a workaround for IE bug with SVG attribute filterUnits There seems to be a problem with the attribute "filterUnits" for SVG filters on IE 10+. This has effects for drop-shadow filters on (nearly) vertical or horizontal lines, see this example:
<svg height="500" width="500">
    <defs>
        <filter id="f1" filterUnits="userSpaceOnUse" width="300%" height="300%">
            <feOffset result="offOut" in="SourceGraphic" dx="5" dy="5" />
            <feGaussianBlur result="blurOut" in="offOut" stdDeviation="3" />
            <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
        </filter>
    </defs>
    <line x1="10" y1="205" x2="400" y2="200"
        style="stroke:rgb(255,0,0); stroke-width:20" filter="url(#f1)" />
    <line x1="200" y1="50" x2="220" y2="300"
        style="stroke:rgb(255,0,255);stroke-width:20" filter="url(#f1)" />
</svg>

This example works perfect in Chrome and Firefox, but the lines are partially clipped in IE 10, 11. It seems that the attribute value filterUnits="userSpaceOnUse"is not supported in IE.
According to Microsoft (http://msdn.microsoft.com/en-us/library/ff934701%28v=vs.85%29.aspx and http://msdn.microsoft.com/en-us/library/ie/hh773402%28v=vs.85%29.aspx), filterUnits is not supported in IE9, but in IE10+.
Is there a workaround for this problem?

A: IE11 seems to use a stroke width of 0 when calculating the filter region - regardless of how big your stroke is, AND it doesn't seem to support specifying the filter region in userSpaceUnits (even when you tell it to). This means that the filter region for a horizontal or vertical line is zero units for the y and x dimensions respectively.
A terrible terrible but effective hack is to draw a transparent shape with the filter dimension that you want along with your horizontal or vertical lines, and set the filter on a group element grouping that shape along with your desired shape.
This works in IE, Firefox, Chrome. (Isn't the web awesome!)
<svg x="0px" y="0px" height="500px" width="500px" viewbox="0 0 500 500">
    <defs>
        <filter id="f1" x="-200%" y="-200%" width="400%" height="800%">
            <feOffset result="offOut" in="SourceAlpha" dx="5" dy="5" />
            <feGaussianBlur result="blurOut" in="offOut" stdDeviation="3" />
            <feComposite in="SourceGraphic" in2="blurOut" mode="normal" />
        </filter>
    </defs>
    <line x1="10" y1="205" x2="400" y2="200"
        style="stroke:rgb(255,0,0); stroke-width:20" filter="url(#f1)" />
    <line x1="200" y1="50" x2="220" y2="300"
        style="stroke:rgb(255,0,255);stroke-width:20" filter="url(#f1)" />

  <g filter="url(#f1)">
  <line x1="10" y1="100" x2="400" y2="100" style="stroke:rgb(255,0,0);stroke-width:20"  />
    <line x1="10" y1="100" x2="400" y2="110" stroke="red" stroke-opacity="0" />
    <g>
</svg>

BTW this is not a bug - the spec doesn't require the stroke width to be taken into account when calculating the bounding box. IE doesn't, Firefox does.


text:
Q: Program to implement neural Network I have found a program to implement Neural Network. But giving an error..
x=np.array(([3,5], [5, 1], [10, 2]), dtype=float)
y=np.array(([75], [82],[93]), dtype=float)
x=x/np.amax(x, axis=0)
y=y/100
print(x)

class NeuralNetwork(object):

    def _init_(self):
        #Define Hyperparameters
        self.inputLayerSize=2
        self.hiddenLayerSize=3
        self.outputLayerSize=1

        #weight Parameters
        self.w1=np.random.randn(self.inputLayerSize, self.hiddenLayerSize)
        self.w2=np.random.randn(self.hiddenLayerSize, self.outputLayerSize)

    def forwardPropagation(self,X):
        self.z2=np.dot(X, self.w1)
        self.a2=self.sigmoid(self.z2)
        self.z3=np.dot(self.a2, self.w2)
        yHat=self.sigmoid(self.z3)
        return yHat

    def sigmoid(self,z):
        return 1/(1+np.exp(-z))

NN=NeuralNetwork()
YHat=NN.forwardPropagation(x)

Error:
AttributeError                            Traceback (most recent call last)
<ipython-input-83-b2ae5338432a> in <module>()
      1 NN=NeuralNetwork()
----> 2 YHat=NN.forwardPropagation(x)
      3 #testInput=np.arange(-6,6,0.01)
      4 #plt.plot(testInput, NN.sigmoid(testInput), linewidth=2)
      5 #plt.show()

<ipython-input-82-5a9b5641f6b6> in forwardPropagation(self, X)
     13
     14     def forwardPropagation(self,X):
---> 15         self.z2=np.dot(X, self.w1)
     16         self.a2=self.sigmoid(self.z2)
     17         self.z3=np.dot(self.a2, self.w2)

AttributeError: 'NeuralNetwork' object has no attribute 'w1'

A: You wrote your init wrong. It should be double underscores like __init__


text:
Q: Toast Message On Touch Is it possible to show toast message , when user touch on screen and close when user again touch screen .
Like I have many toast message to display based on user click on screen.
A sample code will be much more appreciated.

A: In this answer it's explained how you can show and cancel a toast when you desire: https://stackoverflow.com/a/13727852/6150890
To know when the user is touching the screen use an onTouchEvent(), you'll find plenty of examples if you google it


text:
Q: Erro ao buscar cabeçalhos HTTP em Web Services php Estou aprendendo a criar Web Services e estou fazendo dois arquivos em php, server e cliente.
Server.php
<?php
class functions
{

    function mensagem()
    {
        return 'hello server';
    }
    function soma($a, $b)
    {
        return $a + $b;
    }

}

$options = array('uri' => 'http://127.0.0.1/teste/index.php');
$server  = new soapServer(null, $options);

$server->setClass('functions');
$server->handle();

?>

Cliente.php
<?php

$options = array('location' => 'http://127.0.0.1/teste/cliente.php',
'uri' => '127.0.0.1/teste/index.php');
$cliente = new soapClient(null, $options);

try{

    print($cliente->soma(2, 3));

} catch(Exception $e)
{

    print $e->getMessage();

}

?>

Ao executar o script cliente.php da o seguinte erro
Error fetching HTTP headers

Já aumentei até o timeout para 600s, da forma como vi no StackOverFlow ingles, mas só deixou mas demorada a mesma resposta. Alguem Pode dar uma ajuda?


text:
Q: Press, hide button in ChartContainerContent in UI5 fiori Hi all SAP UI5 and FIORI positive,
I have ChartContainer with button for graph and button for table. It is defined in xml file as:
<suite:ChartContainerContent id="idButtonChart"
                             icon = "sap-icon://bar-chart"
                             title = "Chart"
                             >

<suite:ChartContainerContent id="idButtonTable"
                                icon = "sap-icon://table-view"
                                title = "{i18n>table}">
                    <suite:content>

Let's say I want to hide some of these buttons which are placed inside ChartContainer. I have tried (in controller.js part):
this.getView().byId("idButtonChart").setVisible(false);

or
this.getView().byId("idButtonChart").setVisible(false);

But this code, hided graph but not button. Please, do you have any idea how to hide button? Or to trigger click event on button idButtonTable?

Thanks for any advices.

A: Have you found any good solution for this issue? I've been checking the SDK and I can't find a way to get those buttons in an straight way.
Anyway, you could do it using the following code -
 var chartContainerContent = this.getView().byId('your chart id');
 var chartContainer = chartContainerContent.getParent();
 var aToolbarButtons = chartContainer._oToolBar.getContent();
 var segmentedButton;
 for(var i=0; i<aToolbarButtons.length; i++){
    var button = aToolbarButtons[i];
    if(button.getMetadata()._sClassName === "sap.m.SegmentedButton"){
       segmentedButton = button;
       break;
    }
 }
 //segmentedButton.getButtons()

Once you get the buttons you can setVisible(false) to the one you want.
Of course this is not the best, but the chartContainer doesn't provide any public function to get the buttons of the chart.

A: I try to understand the issue. You define 2 charts in your example.
The buttons are usually used to switch the display to the corresponding chart.
How are you going to switch between the 2 charts if you hide the corresponding button?

A: A little late but I guess an .updateChartContainer() after the .setVisible should do the trick:
this.getView().byId("idButtonChart").setVisible(false);
this.getView().byId("<NAME OF THE CONTENT CONTAINER>").updateChartContainer();


text:
Q: Find the number of zeroes of the polynomial $h(z)=z^{5} + 5z^{3} + 2z^{2} + 4z + 1$ in the right half-plane. Question: Find the number of zeroes of the polynomial $h(z)=z^{5}+5z^{3}+2z^{2}+4z+1$ in the right half-plane.
Comments: There may be a number of ways to arrive at a solution to this problem, but it would be instructive for me to know if anyone can solve it using Rouché's theorem (or the principle of the argument if that proves impossible). My idea is to count the zeros on an area bounded by the imaginary axis and a half-circle $C$ on the right half-plane with center in $z=0$ and of radius $R$ where $R$ is a large enough number to contain all the zeros in the right-half plane. To do so using Rouché, I would need to see if there is a $g(z)$ which has an absolute value larger than $|f(z)-g(z)|$ on the boundary (that is, on the imaginary axis and on $C$). I am unsure however which $g(z)$ to choose.
This is a problem from an old complex analysis exam, it is similar to this problem which I posted earlier. All input appreciated.

A: Choose $g(z) = z^5 + 1$. The zeros of $g$ are $e^{k\pi i/5},\; k \in \{1,3,5,7,9\}$, two of which lie in the right half plane.
Then a slightly generalised version of Rouché's theorem tells you that $h$ also has two zeros in the right half plane.
The standard formulation of Rouché's theorem demands that $\lvert h-g\rvert < \lvert h\rvert$ (or $\lvert h-g\rvert < \lvert g\rvert$) on the boundary $\partial V$ of the region, but looking at the proof, whose main part is the observation that the number of zeros of $f_\lambda = g + \lambda(h-g)$ in $V$,
$$N_\lambda = \frac{1}{2\pi i}\int_{\partial V} \frac{g'(z) + \lambda\bigl(h'(z) - g'(z)\bigr)}{g(z) + \lambda\bigl(h(z) - g(z)\bigr)}\, dz$$
is independent of $\lambda \in [0,\,1]$, since no $f_\lambda$ has a zero on $\partial V$.
The role of the condition $\lvert h-g\rvert < \lvert g\rvert (\text{ or } \lvert h\rvert)$ on $\partial V$ is solely to guarantee that $g + \lambda(h-g)$ also has no zeros on $\partial V$. If we can determine that in a different way, the conclusion still holds.
For a large enough semicircle in the right half plane, we have $\lvert 5z^3 + 2z^2 + 4z\rvert < \lvert z^5 + 1\rvert$ since the RHS is a polynomial of higher degree than the LHS.
On the imaginary axis, although $\lvert g-h\rvert > \lvert g\rvert$ on some parts, expanding shows
$$g(it) + \lambda\bigl(h(it) - g(it)\bigr) = 1 + it^5 + \lambda(-5it^3 - 2t^2 + 4it) = (1-2\lambda t^2) + it(t^4 - 5\lambda t^2 + 4\lambda),$$
and the real part vanishes only for $\lambda = \dfrac{1}{2t^2}$ (with $t^2 \geqslant \frac12$, since $\lambda \leqslant 1$), when the imaginary part is
$$t\left(t^4 - \frac{5}{2} + \frac{2}{t^2}\right) = \frac1t\left(t^6 - \frac{5}{2}t^2 + 2\right),$$
and the polynomial $x^3 - \frac52x + 2$ has no positive real roots, so we conclude $g(z) + \lambda(h(z)-g(z)) \neq 0$ on the imaginary axis.


text:
Q: Changing SSH port with a bash script on CentOS SO I wrote a script that can change the SSH port on CentOS but for some reason I'm encountering this error:

sshchangecOS6.sh: line 36: syntax error: unexpected end of file

This is the script:
#! /bin/bash
# This script changes the ssh port for logins on CentOS 5 and 6
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
   exit 2
read -r -p "Would you like to change the ssh port? [Y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
then
   read -p "What would you like to change the port to? (Chose between 1024-65535) " sshportconfig
   if (( ("$sshportconfig" > 1024) && ("$sshportconfig" < 65535) )); then
    echo "Port $sshportconfig" >> /etc/ssh/sshd_config
    echo "--------------------------------------------------------------------"
    echo ""
    echo ""
    echo "SSH port has been changed to: $sshportconfig. Written by Sincere the Minotaur."
    echo ""
    echo ""
    echo "--------------------------------------------------------------------"
   else
    echo "Port chosen is incorrect."
    exit 1
   fi
else
   sshPort=$(grep "Port" /etc/ssh/sshd_config) | head -n 1
   echo "--------------------------------------------------------------------"
   echo ""
   echo ""
   echo "SSH is still: $sshPort"
   echo "Written by Sincere the Minotaur."
   echo ""
   echo "---------------------------------------------------------------------"
   exit 1
fi
exit 0

Could someone explain where the errors are?

A: There is no fi for the first if if [[ $EUID -ne 0 ]]; then. You need to close every if with a fi.


text:
Q: Fancybox not firing I am creating a simple gallery and fancybox does not seem to be firing and I have no idea why, I've used it before on other sites and works ok:
doctype
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

script, css calls and js - script sources ok checked
<link href="../js/fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />

and the php i'm using to generate the thumbs from folder and also the href to call fancybox
$files = glob("../gallery/gallery/*.*");

for ($i=1; $i<count($files); $i++)
{
 $num = $files[$i]; echo '
 ';
 }

this is the rendered html from the actual page:

A: Remove the extra } after 'transitionOut' : 'fade'

A: Complete syntax error found by console, many thanks for suggestion, never used that before:


text:
Q: Using multiple deliminators for javascript .split function I am using the split function below to get a times value:
12:00
I now want to include another .split value (period):
12.00
I discovered I could use regex to achieve this but am failing to get a working result.
WORKING
var time = time.val().split(':')

FAILING (REGEX)
var time = time.val().split('/:|\./')

A: Regex is a type in itself in javascript, no need to put it quotes. Your code looks for a literal /:|\./.
Also, :|\. is [:.].
'12.00'.split(/[:.]/);

outputs
["12", "00"]

A: You can use like this.
var time = time.val().split(/\.|&/)


text:
Q: $('#element').css("CssProperty") is not loading i am using jquery .css() function to get 'margin-left' property using var divMargin= $('#DivId').css('margin-left') but i am getting undefined in divMargin some times this works perfectly and some times causes problem
var divMargin= $('#DivId').css('margin-left');

what is cause of such unexpected behavior?

A: jQuery's .css() does not return the computed style. It'll get you only those CSS properties that you set via .css(..) calls if I remember correctly. For getting a currently set CSS property no matter where it is set from, you can use window.getComputedStyle
Use this for getting the computed style for an element:
window.getComputedStyle(element);

Ref: https://developer.mozilla.org/en/DOM/window.getComputedStyle
For margin-left, you can do:
var marginLeft = window.getComputedStyle($('#DivId')[0]).marginLeft;

A: Put your script inside
$(document).ready(function(){
var divMargin= $('#DivId').css('margin-left');
})

So it run after DOM is loaded


text:
Q: Convert jQuery AJAX API .done() and .fail() functions to AngularJS $http I am fairly new to Angular and am working on incorporating an existing jQuery AJAX API into Angular.
Right now I am doing stuff like:
$.myApi.login('username', 'password').done(function(result) {
    //do stuff
    $scope.$apply(); //apply changes to Angular app
}).fail(function(result) {
    //do stuff if login failed
    $scope.$apply(); //apply changes to Angular app
});

Is there a cleaner way to integrate APIs like this than just writing $scope.$apply() everywhere? Can I integrate with Angular's $http somehow without ditching the existing functions and just making raw AJAX requests to the URLs (i.e. can I reuse the existing API's functions directly)?


text:
Q: How to add date picker in Dialogflow bot! User have to select date by using javascript datepicker in nodejs I would like to inform you all, am using a Dialgflow chatbot, whereas the webchat is connected with the botframework, that is webchat UI is from bot-framework,  NLP is from Dialogflow.
I need an option for date picker where the user can select the date at one shot. Instead typing the date in the given format.
Can anyone let me know the procedure, how to add date picker in the dialogflow bot that too for webchat.
I have got the link from nodejs regarding js-datepicker...
https://www.npmjs.com/package/js-datepicker
Am okay with this npm but even if I use this, I need to know the procedure how to integrate with the dialogflow.
Am using fulfillment for dialogflow which is Nodejs.
Anyone help on this.
Let me know if any one has the clarifications.
REGARDS,
IMRANKHAN K

A: I know is late but just in case.  If it is a webchat what you are using try www.kommunicate.io.  It has a webchat integration with dialogflow and a bunch of very interesting rich content including form with date picker and html.  Kommunicate rich content docs


text:
Q: Odoo 9.0 Traceback Errors on contact and Products We are getting traceback errors whenever we select products or contact, our website apps runs Ok but we can't install e-commerce module which we remove recently what is causing it ? Please help
Odoo Server Error
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/openerp/http.py", line 648, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)

File "/usr/lib/python2.7/site-packages/openerp/http.py", line 685, in dispatch
result = self._call_function(**self.params)

 File "/usr/lib/python2.7/site-packages/openerp/http.py", line 321, in _call_function
return checked_call(self.db, *args, **kwargs)

 File "/usr/lib/python2.7/site-packages/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)

 File "/usr/lib/python2.7/site-packages/openerp/http.py", line 314, in checked_call
result = self.endpoint(*a, **kw)

 File "/usr/lib/python2.7/site-packages/openerp/http.py", line 964, in __call__
return self.method(*args, **kw)

 File "/usr/lib/python2.7/site-packages/openerp/http.py", line 514, in response_wrap
response = f(*args, **kw)

 File "/usr/lib/python2.7/site-packages/openerp/addons/web/controllers/main.py", line 828, in search_read
 return self.do_search_read(model, fields, offset, limit, domain, sort)

  File "/usr/lib/python2.7/site-packages/openerp/addons/web/controllers/main.py", line 849, in do_search_read
request.context)

File "/usr/lib/python2.7/site-packages/openerp/http.py", line 1069, in proxy
result = meth(cr, request.uid, *args, **kw)

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 5297, in search_read
result = self.read(cr, uid, record_ids, fields, context=read_ctx)

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 3203, in read
result = BaseModel.read(records, fields, load=load)

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 3238, in read
self._read_from_database(stored, inherited)

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 3429, in _read_from_database
res2 = self._columns[f].get(cr, self._model, ids, f, user, context=context, values=result)

File "/usr/lib/python2.7/site-packages/openerp/osv/fields.py", line 1501, in get
result = self._fnct(obj, cr, uid, ids, name, self._arg, context)

File "/usr/lib/python2.7/site-packages/openerp/addons/product/product.py", line 435, in _product_currency
res[product.id] = product.company_id.currency_id.id or main_company.currency_id.id

File "/usr/lib/python2.7/site-packages/openerp/fields.py", line 830, in __get__
self.determine_value(record)
File "/usr/lib/python2.7/site-packages/openerp/fields.py", line 930, in determine_value
record._prefetch_field(self)

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 3308, in _prefetch_field
result = records.read([f.name for f in fs], load='_classic_write')

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 3238, in read
self._read_from_database(stored, inherited)

File "/usr/lib/python2.7/site-packages/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/models.py", line 3376, in _read_from_database
cr.execute(query_str, params)

File "/usr/lib/python2.7/site-packages/openerp/sql_db.py", line 141, in wrapper
return f(self, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/openerp/sql_db.py", line 220, in execute
res = self._obj.execute(query, params)

ProgrammingError: column product_template.website_description does not exist
LINE 1: ...e" as "state","product_template"."type" as
"type","product_t...
                                                         ^


text:
Q: Make text fall of a line As a joke in a songbook I'm editing I want to make a phrase "fall of the line", letter by letter. I do remember a long time ago to have seen something like this in WikiBooks but can't find it again.
I recognize there are different ways to do this and some alternatives would be nice to learn about.
Example of what I wan't to be done, however it should be much more incremental and not fall of one letter per line. But rather a couple of pixels per letter.
He
  l
   l
    oooo

The letters should "float of the line"

A: Just not to leave the question unanswered...
The page you're looking for is the Wikibook one about LaTeX/Boxes.
The command you need is \raisebox.
Since you're writing a songbook, maybe you can add some music notes:
\documentclass{article}
\usepackage{textcomp}
\newcommand{\musicnotes}{\raisebox{-2pt}{\raisebox{4pt}{\textmusicalnote}%
    \textmusicalnote\hspace{2pt}%
    \raisebox{4pt}{\textmusicalnote}}}
\begin{document}
\raisebox{-22pt}{\musicnotes}\hspace{-24pt}
\raisebox{-2pt}{H}
\raisebox{-4pt}{e}
\raisebox{-6pt}{l}
\raisebox{-8pt}{l}
\raisebox{-10pt}{o}
\raisebox{-12pt}{o}
\raisebox{-14pt}{o}
\raisebox{-16pt}{o}
\raisebox{-18pt}{!}\hspace{-26pt}
\raisebox{2pt}{\musicnotes}
\end{document}


text:
Q: DllNotFoundException: LogitechSteeringWheelEnginesWrapper.dll I'm using logitech gaming sdk downloaded from Assets Store. When I try to use their sample script it gives the error shown below:

DllNotFoundException: LogitechSteeringWheelEnginesWrapper.dll
  LogitechSteeringWheel.Update () (at Assets/Logitech SDK/Script Sample/LogitechSteeringWheel.cs:53)

LogitechSteeringWheel.cs:53 :

if(LogitechGSDK.LogiUpdate() && LogitechGSDK.LogiIsConnected(0)){

The Dll in the 'Assets/Logitech SDK/Lib/GameEnginesWrapper/x64' and 'Assets/Logitech SDK/Lib/GameEnginesWrapper/x86' path.
When I tried run the program on different PC with same unity version, it works without any error.
What would cause this problem?

A: I found a solution that worked for me in
https://assetstore.unity.com/packages/tools/integration/logitech-gaming-sdk-6630#reviews
jeromeWork posted:
Download the STEERING WHEEL SDK from here: https://www.logitechg.com/en-gb/innovation/developer-lab.html Unzip
then navigate to: LogitechSteeringWheelSDK_8.75.30\Lib\GameEnginesWrapper\x64
copy LogitechSteeringWheelEnginesWrapper.dll and overwrite the same file in your asset folder: \Assets\Logitech SDK

A: I tried many things over time, but the solution is as simple as possible. In "LogitechSteeringWheel.cs" script there are dll importing lines. Instead of writing only the dll's name, I wrote full path. It works.


text:
Q: Is it good practice to use `fwrite` within loops? I need to write an array whose parts are scattered in code.
In short, my code is this:
(...)
FILE *f = fopen(filepath, "wb"); // wb -write binary

for (uint i = 0; i < num_points; i++) {
    fwrite(points[i].loc, sizeof(float[3]), 1, f);
}

fclose(f);

As you can see, my solution was writing each new part of the array in front of the file.
But does this have a problem with efficiency, or memory reading? Should I allocate the entire array in RAM and then write the file?

A: fwrite will buffer your data until its buffer is full, or fflush/fclose/etc. is called. So it won't perform a syscall each iteration.


text:
Q: Efficient matrix square root of large symmetric positive semidefinite matrix in Python I have a large (150,000 x 150,000) symmetric positive semidefinite sample covariance matrix whose matrix square root I wish to compute efficiently in Python.
Is there any way to speed up the square root computation given that the matrix is symmetric psd? scipy.linalg.sqrtm is slow for my purpose.

A: Depending on your application, if it is enough to find Bs @ Bs.T ~ B, you can use Cholesky decomposition. If not you could get the square root based on eigenvalue decomposition.
import numpy as np;
import scipy.linalg
A = np.random.randn(1500, 1500)

%%time
Bs = scipy.linalg.sqrtm(B)

Wall time: 4.4 s - Our baseline
%%time
Bs = scipy.linalg.cholesky(B)

Wall time: 52 ms Cholesky is much faster
D, V = scipy.linalg.eigh(B)
Bs = (V * np.sqrt(D)) @ V.T

Wall time: 1.62 s more than twice faster (it explores symmetry)
Using pytorch
Pytorch have supports some linear algebra functions, and they vectorize accross multiple CPUs
import torch.linalg
B_cpu = torch.tensor(B, device='cpu')

Square root using eigh (12 logic / 6 physical CPUs)
%%time
D, V = torch.linalg.eigh(B_cpu)
Bs = (V * torch.sqrt(D)) @ V.T

Wall time: 400 ms
Or Cholesky decomposition
Bs = torch.linalg.cholesky(B_cpu)

Wall time: 27 ms


text:
Q: How can I do to use hour using Google Sheets? I have a problem using Google Sheets,
when I type 15 for example and I set the format to hour I get 14/01/1900 00:00:00 whereas I would like to have 15:00:00. How can I do this?

A: to get hours you need to type:
15:00

if you type 15 in a cell you can convert it in another cell like this:

note that if you want to type something into cell and set formatting to Time, you need to type:
0.625

which becomes 15:00 after you set formatting to Time


text:
Q: iOS 13 not recognizing contacts with country code This morning I downloaded brand new iOS 13 (Official Release) and found it very cool, specially dark mode.
The thing is that I started receiving calls and the contact names are not being identified, Ive found out that this is happening cause some contacts are registered with country code, for example:

In above image my friend Antonio is registered with country code: +52 1 (55) etc...
Before iOS 13 the number was formatted with parenthesis but now it doesn't.
And before iOS 13 the call identifier perfectly recognizes all numbers with that format, but now it doesn't either:

Coincidentally this exact thing happened to Antonio on his own iPhone so I suppose maybe its a very common issue.
Am I missing some new configuration or what can we do? Thanks.

A: I would engage Apple support using the iOS support app. They would be able to confirm this is a bug or possible document the setting no one has discovered yet to remedy this.

A: Download this app https://apps.apple.com/us/app/10-d%C3%ADgitos/id1476001299
This fixes the issue


text:
Q: convert all dates in a column to numbers I'm trying to convert time to numbers in excel. I am using this formula:
=HOUR(A2) + MINUTE(A2) / 60 + SECOND(A2) / 3600

And it works well, but I have to convert a column with around 65.000 of dates.
How do I do that in an elegant and time saving way?

A: So assuming that your formula does what you want it to do, you just have to double click on the lower-right part on the cell with your first formula. So if your data are in the range A2:A65000, write your formula on cell B2, and double click on its lower-right part.
See the pic below:

A: Assume you mean time rather than date.
Try
=A2*24
Format as general
To apply to a large range you can put 24 into a spare cell, copy it, select range you want to convert to number and paste special... Then select multiply and okay.


text:
Q: DirectX SDK June 2010 issue I'm trying to run the sample code from the book Physics for Game Programmers. I have installed the DirectX SDK June 2010 but get the following errors.
Cannot open include file: 'd3drmwin.h'
Cannot open include file: <d3drm.h>
Cannot open include file: <d3dtypes.h>

I believe I have added all necessary include and library paths and Additional Dependencies (D3D10.lib & D3DX10.lib) as I can access the header files d3d10.h and d3d9.h without any issues.
Any ideas how to get their code running? Is the code possibly referencing a old version of DirectX?
Edit: I have installed the SDK and Set up the following:
Project->Properties->VC++ Directories->Include Directories and added
C:\Program Files %28x86%29\Microsoft DirectX SDK %28June 2010%29\Include;

Project->Properties->VC++ Directories->Library Directories and added
C:\Program Files %28x86%29\Microsoft DirectX SDK %28June 2010%29\Lib\x86;

Project->Properties->Linker->Input and added
D3D10.lib;D3DX10.lib

Edit
Ok, I have figured out those header files belong to DirectX 8. So the latest SDK doesn't support them. Now i just have to figure out where to download the DirectX 8 SDK. Any ideas where to find it?

A: Change the paths to the folders to use double quotes properly, as in
"C:\Program Files x86\Microsoft DirectX SDK June 2010\Include;"

Windows is not a web browser; it's an operating system. It doesn't understand URL encoding as far as directory locations go. (I don't have the book, but it's probably a typo there.)


text:
Q: Search for substring and store another part of the string as variable in perl I am revamping an old mail tool and adding MIME support. I have a lot of it working but I'm a perl dummy and the regex stuff is losing me.
I had:
foreach ( @{$body} ) {

   next if /^$/;

   if ( /NEMS/i ) {
      /.*?(\d{5,7}).*/;
      $nems = $1;
      next;
   }

   if ( $delimit ) {
      next if (/$delimit/ && ! $tp);
      last if (/$delimit/ && $tp);

      $tp = 1, next if /text.plain/;
      $tp = 0, next if /text.html/;
      s/<[^>]*>//g;
      $newbody .= $_ if $tp;
   } else {
      s/<[^>]*>//g;
      $newbody .= $_ ;
   }
}  # End Foreach

Now I have $body_text as the plain text mail body thanks to MIME::Parser. So now I just need this part to work:
foreach ( @{$body_text} ) {

   next if /^$/;

   if ( /NEMS/i ) {
      /.*?(\d{5,7}).*/;
      $nems = $1;
      next;
   }
}  # End Foreach

The actual challenge is to find NEMS=12345 or NEMS=1234567 and set $nems=12345 if found. I think I have a very basic syntax problem with the test because I'm not exposed to perl very often.
A coworker suggested:
foreach (split(/\n/,$body_text)){

    next if /^$/;

    if ( /NEMS/i ) {
        /.*?(\d{5,7}).*/;

        $nems = $1;
next;

    }
}

Which seems to be working, but it may not be the preferred way?
edit:
So this is the most current version based on tips here and testing:
foreach (split(/\n/,$body_text)){

    next if /^$/;

    if ( /NEMS/i ) {
        /^\s*NEMS\s*=\s*(\d+)/i;

        $nems = $1;
    next;

    }
}

A: Match the last two digits as optional and capture the first five, and assign the capture directly
($nems) = /(\d{5}) (?: \d{2} )?/x;  # /x allows spaces inside

The construct (?: ) only groups what's inside, without capture. The ? after it means to match that zero or one time. We need parens so that it applies to that subpattern only. So the last two digits are optional -- five digits or seven digits match. I removed the unneeded .*? and .*
However, by what you say it appears that the whole thing can be simplified
if ( ($nems) = /^\s*NEMS \s* = \s* (\d{5}) (?:\d{2})?/ix ) { next }

where there is now no need for if (/NEMS/) and I've adjusted to the clarification that NEMS is at the beginning and that there may be spaces around =.  Then you can also say
my $nems;

foreach ( split /\n/, $body_text ) {
    # ...
    next if ($nems) = /^\s*NEMS\s*=\s*(\d{5})(?:\d{2})?/i;
    # ...
}

what includes the clarification that the new $body_text is a multiline string.
It is clear that $nems is declared (needed) outside of the loop and I indicate that.
This allows yet more digits to follow; it will match on 8 digits as well (but capture only the first five). This is what your trailing .* in the regex implies.
Edit   It's been clarified that there can only be 5 or 7 digits.  Then the regex can be tightened, to check whether input is as expected, but it should work as it stands, too.

A few notes, let me know if more would be helpful

*

*The match operator returns a list so we need the parens in ($nems) = /.../;

*The ($nems) = /.../ syntax is a nice shortcut, for ($nems) = $_ =~ /.../;.
If you are matching on a variable other than $_ then you need the whole thing.

*You always want to start Perl programs with
use warnings 'all';
use strict;

This directly helps and generally results in better code.

The clarification of the evolved problem understanding states that all digits following = need be captured into $nems (and there may be 5,(not 6),7,8,9,10 digits).  Then the regex is simply
($nems) = /^\s*NEMS\s*=\s*(\d+)/i;

where \d+ means a digit, one or more times. So a string of digits (match fails if there are none).


text:
Q: как возвести cos в квадрат в пайтоне? Надо сделать калькулятор для решения такого примера: cos^2(sin 1/z). но pow не работает. Поясните, как можно решить эту задачку?

A: Так?
# cos^2(sin 1/z)

from math import cos, sin

z = 3
result = cos(sin(1 / z)) ** 2
print(result)  # 0.8967098683878832


text:
Q: Magento Errors after installation So I have just managed to download/setup Magento on XAMPP but I have no images on the back or front of the CMS. I have looked into the directories and there are no images where they should be.
I don't understand why this would be because I downloaded the files from the official website.
It's also running really slow :/

What could be causing how slow it is running and where would I get the images and missing js from? why would it be missing?


text:
Q: stream a command's stdout, and merge with terminal's stdin to a single stdout This answer shows numerous ways to stream multiple commands into another command, but since they use subshells you can't do stdin.
While you can achieve this with named pipes, it's somewhat ugly and can leave leftover processes afterwards:
$ mkfifo p
$ while :; do sleep 5s; echo save; done > p &
$ cat p > output &
$ cat </dev/stdin > p
test
asdf
woot
^C
$ cat output
save
test
asdf
save
save
woot
save
$ jobs
[1]-  Running                 while :; do
    sleep 5s; echo save;
done > p &
[2]+  Running                 cat p > output &

Is there a way to pull this off in a single command? Ideally I would like something along the lines of:
someutil <(while :; do sleep 5s; echo save; done) /dev/stdin > output

This way I can pipe the output to another command instead of a file.


text:
Q: AWS: ACM was unable to renew the certificate automatically because of the following error: PCA_ACCESS_DENIED I received a message from AWS warning of a  certificate to expire. It contained this phrase:
ACM was unable to renew the certificate automatically because of the following error: PCA_ACCESS_DENIED.

What does this mean and how do I fix it ?

A: Check the Private Certificate Authority and select Actions|Configure CA Permissions. Ensure Authorize ACM access to renew certificates requested by this account. is checked.
using the AWS CLI (cloudshell) run the following:
aws acm-pca list-permissions --certificate-authority-arn "arn:aws:acm-pca:us-east-2:ACCOUNTNUMBER:certificate-authority/xxxxxxx-b0e1-446e-a2ec-6f6c466e4684"
If you get back:
{
    "Permissions": []
}

This indicates the CA is not authorized to renew the cert.
Your permissions should resemble:
{
    "Permissions": [
        {
            "CertificateAuthorityArn": "arn:aws:acm-pca:us-east-2: ACCOUNTNUMBER:certificate-authority/xxxxxxx-b0e1-446e-a2ec-6f6c466e4684",
            "CreatedAt": "2022-07-15T16:21:51.890000+00:00",
            "Principal": "acm.amazonaws.com",
            "SourceAccount": "ACCOUNTNUMBER",
            "Actions": [
                "GetCertificate",
                "IssueCertificate",
                "ListPermissions"
            ],
            "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"1\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"acm.amazonaws.com\"},\"Action\":[\"acm-pca:GetCertificate\",\"acm-pca:IssueCertificate\",\"acm-pca:ListPermissions\"],\"Resource\":\"arn:aws:acm-pca:us-east-2:ACCOUNTNUMBER:certificate-authority/xxxxxxx-b0e1-446e-a2ec-6f6c466e4684\",\"Condition\":{\"StringEquals\":{\"aws:SourceAccount\":\"ACCOUNTNUMBER\"}}}]}"
        }
    ]
}


text:
Q: How to select all the data of two columns from a table using JPA query method I want to add in my Repository interface a method for the following SQL query:
SELECT ID, NAME  FROM TABLE_NAME

This SQL query works as expected, but I want to write it as a JPA query method, I've tried in many ways but didn't get it working, Please help me.
Following which I've tried but didn't work:
findAllByIdName(){}
findAllByIdAndName(){}
findByIdName(){}
findByIdAndName(){}

A: Create a result class first:
package com.example;

public class ResultClass{

  private Long id;
  private String name;

  public ResultCalss(Long id, String name){
     // set
  }
}

and then use a custom @Query:
@Query("select new com.example.ResultClass(e.id, e.name) from MyEntity e")
public List<ResultClass> findIdsAndNames();

A: Just use interface- or class-based projections:
public interface IdAndName {
    Long getId();
    String getName();
}

public interface MyRepo extends CrudRepository<MyEntity, Long> {
    List<IdAndName> findBy();
}

More info.

A: I have similar implementation. Custom query required to achieve this.
e.g -
@Query("SELECT usr.id, usr.name FROM User usr")
public List<User> findIdsAndNames();

And the User class is
@Entity
@Table(name="t_user")
public class User{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id", nullable = false)
    private Long id;

    @Column(name="name")
    private String name;
............
}


text: Q: Deleting rules from Stack Exchange filters Is it possible to delete or change rules from Stack Exchange filters, or do you need to make a completely new filter? If not I would like to request such a feature since filter lists could grow pretty big depending on ones interest.


text:
Q: How to Wait for Dispatch? I'm using react and flux utils, with es6. I'd like the SalesStore to wait for the SessionStore to finish before executing its own dispatch. In the SalesStore I have the following, but the dispatch does not wait. Does anyone know what the issue could be? Thanks.
class SalesStore extends ReduceStore {

    getInitialState() {
        return {};
    }

    reduce(state, action) {
        switch(action.type) {
            case Constants.FETCH_SALES:
                this.getDispatcher().waitFor([SessionStore.getDispatchToken()]);
                return state;

            case Constants.FETCH_SALES_SUCCESS:
                this.getDispatcher().waitFor([SessionStore.getDispatchToken()]);
                return action.payload;

            case Constants.FETCH_SALES_FAILURE:
                this.getDispatcher().waitFor([SessionStore.getDispatchToken()]);
                return state;

            default:
                return state;
        }
    }

}

export default new SalesStore(AppDispatcher);

A: The reducer must be pure function
so you should move async calls to action creators
function getToken(){
   // Async call then
   return {
     type:'GET_TOKEN_SUCCESS'
   }
}

function getSales(){
   // async then
   return {
     type:'GET_SALES_SUCCESS'
   }
}

// main action will call `getToken` and `fetchSales` actions
function fetchSales(params){
    return dispatch => {
         dispatch(getToken()).then((res)=> dispatch(getSales())
    }
}

To manage promises you can use this middleware


text:
Q: Undeclared Identifier Error in C I have this short C Code. But when I try to run the C program for the file below it shows the following errors
#define MAX 1000 - use of undeclared identifier
roundrobin(schedule, n); too long for functional call

Where am I going wrong?
EDITED FULL CODE FOR MAKING A ROUNDROBIN (Ref:http://www.math.niu.edu/~rusin/known-math/97/roundrobin)
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000

int roundrobin(int schedule[MAX][MAX], int n);

int main(void)

{
    int schedule[MAX][MAX];
    int n, r, i, rounds;

    /* Input number of teams in the schedule. */
    printf("Enter the number of teams that you want a schedule for: ");
    scanf("%d", &n);

    /* If the number of teams is even, requires n-1 rounds; if odd, requires n. */

    if (n % 2)
        rounds = n;
    else
        rounds = n-1;

    roundrobin(schedule, n);

    /* Print a nice table. */
    printf("\n       team\n     \\ ");
    for (i = 0; i < n; i++)
        printf("%6d", i+1);
    printf("\n");
    printf("round \\");
    for (i = 0; i < 6 * n; i++)
        printf(".");
    printf("\n");
    for (r = 0; r < rounds; r++)
    {
        printf("%6d:", r+1);
        for (i = 0; i < n; i++)
            printf("%6d", schedule[r][i] + 1);
        printf("\n");
    }
    printf("\n");

    /* Check the schedule and print whether or not it's valid. */
    if (check(schedule, n))
        printf("Schedule is valid.\n");
    else
        printf("Schedule is not valid.\n");
}

/*************************************************************************
 Compute the round-robin tournament schedule for n teams. If n is even,
 then there are n-1 rounds; if n is odd, there are n rounds and each team
 is idle in exactly one round. A team being idle is indicated by the
 schedule saying that it plays team number -1 in a round.
 *************************************************************************/
int roundrobin(int s[MAX][MAX], int n)
{
    int rounds, m, r, i;

    /* m is the lowest even number greater than or equal to n. */
    if (n % 2)
        m = n + 1;
    else
        m = n;

    /* If the number of teams is even, requires n-1 rounds; if odd, requires n. */

    if (n % 2)
        rounds = n;
    else
        rounds = n-1;

    /* Fill in the table with a nice diagonal pattern. */
    for (r = 0; r < rounds; r++)
    {
        for (i = 0; i < r; i++)
            s[r][i] = ((rounds+r-i+1) + m) % m;
        for (i = r; i < n; i++)
            s[r][i] = ((rounds+r-i) + m) % m;
    }

    /* Now, do knight-like moves with the 0 in the first row. Every time the 0
     lands on a number, put that number in the first column. */
    r = 0;
    for (i = m-2; i > 0; i--)
    {
        r = ((r - 2) + rounds) % rounds;
        s[r][0] = s[r][i];
        s[r][i] = 0;
    }

    /* If m != n, then remove team n from all the games, and replace with -1. */
    if (m != n)
        for (i = 0; i < rounds; i++)
            s[i][i] = -1;
}

/*************************************************************************
 Looks at a schedule and determines whether it is valid.
 *************************************************************************/
int check(int s[MAX][MAX], int n)
{
    int game[MAX][MAX];
    int rounds, r, i, j;

    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            game[i][j] = 0;

    /* If the number of teams is even, requires n-1 rounds; if odd, requires n. */

    if (n % 2)
        rounds = n;
    else
        rounds = n-1;

    /* Count the number of times every team plays every other team. */
    for (r = 0; r < rounds; r++)
        for (i = 0; i < n; i++)
        {
            j = s[r][i];
            if (j > -1)
            /* A value of -1 would mean that team i is idle this round. */
            {
                /* Record that teams i and j played. */
                game[i][j] ++;
                game[j][i] ++;
                /* Note that we will double-count the games, because we record it
                 when team i plays j, as well as when j plays i. */
            }
        }

    /* Make sure that every pair played exactly once, and nobody ever played
     themselves. */
    for (i = 0; i < n; i++)
    {
        if (game[i][i] != 0)
        /* If a team plays themselves, it's not a valid schedule. */
        { printf("Team %d played itself.\n", i); return 0; }
        for (j = i+1; j < n; j++)
        /* We have to check for a 2, because games are double-counted. */
            if (game[i][j] != 2)
            /* If two teams didn't play exactly one time, it's not valid. */
                return 0;
    }

    /* Make sure that each team plays at most once per round. */
    for (r = 0; r < rounds; r++)
    {
        /* We will use game[0] to count the number of times each team appears in
         a round. */
        for (i = 0; i < n; i++)
            game[0][i] = 0;
        /* Count number of times each teams appears in round r. */
        for (i = 0; i < n; i++)
        {
            j = s[r][i];
            /* Team i played team j in round r. */
            if (j >= 0)
            /* -1 means that team i was idle this round. */
                game[0][j] ++;
        }
        /* Make sure each team appears at most once. */
        for (i = 0; i < n; i++)
            if (game[0][i] > 1)
            /* Team i appeared more than once in round r. Not valid. */
                return 0;
    }

    /* Make sure that when team i plays team j, team j also plays team i. */
    for (r = 0; r < rounds; r++)
        for (i = 0; i < n; i++)
        {
            j = s[r][i];
            /* Team i played team j in round r. */
            if (j >= 0)
            /* -1 means that team i was idle this round. */
                if (s[r][j] != i)
                /* If team j didn't play team i, not valid. */
                    return 0;
        }

    /* Otherwise, the schedule is valid. */
    return 1;
}

A: In the line:
if (check(schedule, n))

check is an undeclared identifier. Perhaps that is what your error message actually said. To fix this, you need to add this line near the start of the file:
int check(int s[MAX][MAX], int n);

You can put that just after the declaration of roundrobin.
Aside from that, there are no compilation errors in this code.


text:
Q: Issue with position: sticky I've checked a few post in stack overflow saying that there may be an issue if overflow: hidden or overflow: auto is used with position: sticky. But there is no overflow in my css script and I cannot figure out why my script doesn't work. What I'm trying to do is that when the user scrolls down the page, the horizontal bar should be on top of the page and the vertical bar should fill up the left of the page. The vertical bar doesn't work properly as well but both of them works fine when I'm using position: fixed.

    * {
        box-sizing: border-box;
    }
    body {
        margin: 0;
    }
    .white-space {
        width: 100%;
        height: 200px;
    }
    .hor-navbar ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        background-color: black;
        position: sticky;
        top: 0;
        width: 100%;
        height: 5%;
    }
    .hor-navbar ul li {
        display: inline-block;
        border-right: 1px solid white;
    }
    .hor-navbar ul li a {
        display: block;
        padding: 15px;
        text-decoration: none;
        color: white;
    }
    .hor-navbar ul li:first-child {
        background-color: green;
    }
    .hor-navbar ul li:last-child {
        float: right;
        border-right: none;
    }
    .hor-navbar ul li:not(:first-child) a:hover {
        background-color: grey;
    }
    .ver-navbar ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        background-color: grey;
        width: 30%;
        height: 95%;
        position: sticky;
        bottom: 0;
        text-align: center;
        border: 1px solid black;
    }
    .ver-navbar ul li {
        display: block;
        border-bottom: 1px solid black;
    }
    .ver-navbar ul li a {
        display: block;
        padding: 30px;
        text-decoration: none;
        color: black;
    }
    .ver-navbar ul li:not(:first-child) a:hover {
        background-color: black;
        color: white;
    }
    .ver-navbar ul li:first-child {
        background-color: green;
        color: white;
    }
    .white-space2 {
        width: 70%;
        height: 100%;
        float: right;
    }
   <!DOCTYPE html>

        <title>test</title>
        <link rel="stylesheet" href="test.css">

        <meta charset="UTF-8">
        <meta name="keywords" content="test">
        <meta name="description" content="test">
        <meta name="author" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1-0">

                something

link1

link2

link3

link4

link1

link2

link3

link4

                something


text:
Q: the prepared music-hall allusions
Two days before the case was down for hearing the advance reporter of
  an important syndicate obtained an interview with the Duke for the
  purpose of gleaning some final grains of information concerning his
  Grace's personal arrangements during the trial.
       "I suppose I may say this will be one of the biggest affairs of its kind during the lifetime of a generation," began the reporter as
  an excuse for the unsparing minuteness of detail that he was about to
  make quest for.
       "I suppose so — if it comes off," said the Duke lazily.
       "If?" queried the reporter, in a voice that was something between a gasp and a scream.
       "The Duchess and I are both thinking of going on strike," said the Duke.
       "Strike!"
       The baleful word flashed out in all its old hideous familiarity. Was there to be no end to its recurrence?
       "Do you mean," faltered the reporter, "that you are contemplating a mutual withdrawal of the charges?"
       "Precisely," said the Duke.
       "But think of the arrangements that have been made, the special reporting, the cinematographs, the catering for the distinguished
  foreign witnesses, the prepared music-hall allusions; think of all
  the money that has been sunk — "
from The Unkindest Blow, a short story by Saki

What would they do in the music-hall?

A: The speaker is implying that references to the trial have already been written into songs that are going to be played at music halls. These were places that people would go for light entertainment at the time, and the music often included mentions of topical subjects,. Imagine if a comedy TV show like Saturday Night Live prepared a skit about a trial, but then the trial was called off - the skit would have to be rewritten.

A:
An allusion

is a reference to something. But from your excerpt, we do not know what references are made to music-halls.  It's not that something is literally taking place in a music-hall, rather some scenery or a backdrop depicting a music-hall might be used.


text:
Q: Are there facilities to automate updates in package data? For packages that rely on research data, are there facilities in R that runs a periodic check to determine if an update has been made, or if there now exists a difference between the website and the package?
Here's a reproducible example.  The following function returns the set of years for which data exists on the webpage.  The data itself is available to be downloaded from the site, and is done so in a different function.  check will be a way to handle errors in argument matching in that other function.
check <- function ()
{
    doc <- htmlTreeParse("http://www.retrosheet.org/events",
                         useInternalNodes = TRUE)
    on.exit(free(doc))
    xv <- sapply(doc["//a"], xmlValue)
    gg <- xv[grepl("eve.zip", xv, fixed = TRUE)]
    res <- gsub("(s?)eve.zip", "", gg)
    as.numeric(unique(res))
}

A subset of the result is
> library(XML)
> check()[1:5]
# [1] 1920 1921 1922 1927 1930

Notice that this is not a sequence.  Data may be added to the site later, and new years may appear in the result.  If I store the available years as a package object, I will not know that an update has been made to the data.
A profile of speed is
> system.time({ check() })
#   user  system elapsed
#  0.060   0.003   0.875

which is not slow, but the function that uses this check could be made  more efficient without it, since it also goes to same site to download the data after check makes sure it exists.

A: Many moons ago, I actually wrote the digest package for a very similar task.
And as it turns out, many package have similar needs in terms of comparison of data sets which is how the digest package ended up being used by many of the data caching packages, or by knitr to see if chunks changed etc pp.
So if you have your data in R, consider comparing a digest checksum.  That said, this still requires accessing the before and after data sets to determine if they have changed or not -- and there may be other ways.  But digest provides a relatively widely used comparison method based on checksums of complete object serialization.

A: You could take a look at my UNF package, which implements the Universal Numeric Fingerprint algorithm for datasets. It's primarily designed for data.frames but works on vectors as well:
> library("UNF")
> unf(z)
Universal Numeric Fingerprint (Truncated): UNF:5:Iw2Mw/fiLQ+OzNrOtolwFw==

Just like @DirkEddelbuettel's answer, this is a hash of the original data (and relies on library("digest") under the hood). The algorithm is described on GitHub.
In short, if the UNF signature changes, data has changed. If you're working with dataframes, there are also some functions in the package for comparing dataframes and finding what variables/columns differ.


text:
Q: Get app version from pyproject.toml inside python code I am not very familiar with python, I only done automation with so I am a new with packages and everything.
I am creating an API with Flask, Gunicorn and Poetry.
I noticed that there is a version number inside the pyproject.toml and I would like to create a route /version which returns the version of my app.
My app structure look like this atm:
├── README.md
├── __init__.py
├── poetry.lock
├── pyproject.toml
├── tests
│   └── __init__.py
└── wsgi.py

Where wsgi.py is my main file which run the app.
I saw peoples using importlib but I didn't find how to make it work as it is used with:
 __version__ = importlib.metadata.version("__package__")
But I have no clue what this package mean.

A: You should not use __package__, which is the name of the "import package" (or maybe import module, depending on where this line of code is located), and this is not what importlib.metadata.version() expects. This function expects the name of the distribution package (the thing that you pip-install), which is the one you write in pyproject.toml as name = "???".

A: You can extract version from pyproject.toml using toml package to read toml file and then display it in a webpage.


text:
Q: VS Code PHP auto-formatting / beautify with Stroustrup style braces (K&R variant) and spaces in parentheses? Help me Stack Overflow, you are my only hope.
I'd like to apply auto-formatting in VS Code to PHP files with the following rules:

*

*Stroustrup style braces (K&R variant)

*space before conditional

*space after function

*spaces in parentheses

Example in the screenshot.
I don't want to apply PSR-1 or PSR-2 or PSR-12 or CakePHP or WordPress standards.
I've struggled with:

*

*VS code internal PHP formatter

*phpfmt (which has been last updated in 2018 and archived on GitHub)

*PHP Intelephense (which has little to do with formatting, as far as I can tell)

phpfmt is the closest, but super-buggy.
VS Code settings wise, I roll with:

*

*"files.autoSave": "onFocusChange",

*"editor.formatOnSave": true,

So I'd like to instantly beautify my PHP files, please.
Thank you for any ideas!

A: EDIT 2023-01-10
I have refined the answer below and published it on Github.
The repository have a minimal guide on how to install it locally, no docker needed.
It's the same principle as outlined in the original answer, but this new repository use PSR12 as a base ruleset and enforces rule 1, 3 and 4 while allowing rule 2 in OP. I still believe this gives the most freedom, but it can easily be tinkered with by forking the repository and inspecting the individual rules in VS Code by enabling "phpsab.debug": true and "phpsab.snifferShowSources": true in the settings.

I finally sat down and figured out how to achieve this. This is from an Ubuntu perspective, but I should think that it could be made to work on the other platforms as well.
I tested a bunch of linter/fixer extensions with no real progress until I ended up at this.
It was a bit involved to install a version of phpcs/phpcbf together with a ruleset that the extension could use, so I bundled it all up in a docker container (but everything can be done locally as well with composer of course).
I haven't been able to find rules that can enforce the two whitespace rules in OP (space before conditional and space after function), but there are a lot of customization possible, including writing your own sniffs (and I didn't look super hard to be honest). But the default ruleset/standard in the project linked above allows extra whitespace, so that is half the battle I feel.
For the other rules the following are the explicit parts needed, but please do check out there resources: 1 and 2 and enable "phpsab.snifferShowSources": true and "phpsab.debug": true when creating a custom ruleset.

*

*Stroustrup style braces (K&R variant)

<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie">
</rule>
<rule ref="Drupal.ControlStructures.ControlSignature.SpaceAfterCloseParenthesis">
</rule>

*

*spaces in parentheses

<rule ref="PSR2.ControlStructures.ControlStructureSpacing">
  <properties>
    <property name="requiredSpacesAfterOpen" value="1" />
    <property name="requiredSpacesBeforeClose" value="1" />
  </properties>
</rule>


text:
Q: Resposive div element inside other div element I have two div element inside main div element I want those two div float left and the align center of the main div.
Something like this.
[ main div        [div1][div2]       ]

I have successfully floated the two divs but I am failing to assign the space on both the side. I mean to say align them in center.
 code to float left css
.container{
    width:100%
    height: auto;
}

.img{
    width:auto;
    height:auto;
    float:left;
}
.data{
    width:auto;
    height:auto;
}

html code

 image goes here

data goes here

A: if you write text-align:center to parent.It will align their children
thank you for comments

.container{
    width:100%
    height: auto;
    text-align:center;
}

.data{
    width:auto;
    height:auto;
}

data goes here

A: You can wrap the img and data div in a div, then float that div right with a 50% width. I prefer not to use floats; flexbox would be a better option in my opinion, but if you like floats, I put some code below you can try.
HTML:

 image goes here

data goes here

Add below to the CSS sheet:
.dataImgContainer {
   width: 50%;
   float: right;
 }


text:
Q: How to determine which Python compiler was used to create an executable I have a fun predicament:
I wrote a little Python program a few years ago that needs an update. Unfortunately, I have lost the source code. I do however have the .exe that was created and is being used.
The problem is, I cannot seem to extract the .pyc files because apparently I didn't use pyinstaller or py2exe, and those are the only two compilers I can find scripts for. Does anyone know of a way to determine which compiler I used so I can reverse engineer this thing?