text:
Q: Define categories for data element in DHIS2 Is it possible to create a data element that can take values only in a predefined set of categories e.g. 'Not Tested', 'Result Test: Negative', 'Result Test: Positive' in DHIS2.
Exploring the use of DHIS2 for a dataset of case-based data, or anonymous "patient" data. In the DHIS User Manual, section 1.5: a variety of details may be recorded, such as the patient's temperature, their weight, and various blood tests.
I understand that it is possible to specify the Value type of a data element as either:

*

*number

*text

*yes/no

*yes only

*date

*user name

How one would add a custom value type and allow the user to select only in these 3 categories 'Not Tested', 'Result Test: Negative', 'Result Test: Positive'?

A: Yes you can have custom value type. You need to define option set for example Malaria result and option as ("Not Tested", "Result Test: Negative", "Result Test: Positive"). When you define data element you can select the option set you defined, in this case Malaria Result.
Option sets can be added under apps > data administration > option sets. First define your option set, then click on it, select option management and add your options.


text:
Q: ASP Net Core MVC Polymorphic Deserialization I'm trying to deserialize the JSON from a POST request body with ASP.net Core MVC to its respective class object.
class Form
{
    public string name { get; set}
    // Other string properties
    // ...
    public List<Field> fields { get; set; }
}

Field is a super/parent class of a couple of different field types
class Field
{
    public string type { get; set; }
    public bool filledIn { get; set; }
}

class TextField : Field
{
    public string value { get; set; }
}

class Checkbox : Field
{
    public bool value { get; set; }
}

My controller at the moment looks like this
using Microsoft.AspNetCore.Mvc;

using My_Project.Models;

[ApiController]
[Route("/")]
public class MyController : ControllerBase
{
    [HttpPost("test")]// http://mysiteandporthere/test
    public void ParseAndSave(Form myForm)
    {
        // The rest of the code
    }
}

How can I ensure that my Field objects are deserialized into instances of their correct subclass? I'd be happy to do it using either the "type" property, or the type of the "value" property (Checkboxes will always be true/false, TextFields will always have string values).
Here's an example of the JSON in the POST body. This is a pretty simplified view of what I'm working with. I have other field types that I'm sure I could figure out if I can understand how to do this for these 2 fields.
{
    "name": "Bob"
    "fields": [
        {
            "type": "text",
            "filledIn": true,
            "value": "Here's some value"
        },
        {
            "type": "checkbox",
            "filledIn": true,
            "value": true
        }
    ]
}

In this first link, I found an example of how to handle if the root object needs special attention. Would implementing something like this be possible for my Form class and then handle the deserialization of the Fields within it? I suppose the other thing I could do is move all of the properties out of the subclasses or
https://www.c-sharpcorner.com/article/polymorphism-in-web-api-net-core-6/
In this second link, I wasn't quite able to follow what was happening in the answer. If this is what I need, could you please explain it with a little more detail?
How to override default deserialization for Controller Action in ASP.NET Core?
I haven't worked much with anything http request related in c#. I was following this tutorial and had success until I started trying to make different subclasses/derived classes for my fields
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-6.0&tabs=visual-studio-code
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0#verb

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I include(load) more than one jsp files in spring mvc controller class? How can I include(load) more than one jsp files in spring mvc conroller class?
eg:
@RequestMapping("/")
public void welcome() {

    include("file1.jsp");
    include("file2.jsp");
    include("file3.jsp");
}

A: At framework level, No you cannot do it. However, there is a hack you could try.
Create an array of name of pages you need to merge. Send it as a parameter to a dummy empty page.
The dummy page does this:
<c:forEach var="page" items="${pages}">
<c:import url="${page}"></c:import>
</c:forEach>

This will iterate all the JSP files that you wish to show as a single view.
Hope this helps. Let me know if any further help is required.


text:
Q: Using a capacitor as a battery? I have a 95microF +5% 250v.ac c 50/60 capacitor. And I would like to use it as a  battery even if it only last a couple hours. I have a charger I made for it but the cap. Drains way to fast. I was thinking about using a dimmer switch to reduce it. Or maybe even some resistors to reduce the output voltage to like 10v roughly. I was planning on heating up nichrome wire (68ohm resistance) with this cap. So I can heat the wire up without damaging my power source.

A: Perhaps a 250 V, AC capacitor can be charged to 350 V, DC. That would give you 0.5 X 95 X 10^-6 X 350^2 = 5.8 Joules or 5.8 watt-seconds. If you can recover 75% of that you would have 4.4 watt-seconds. If you use that over two hours, you would have 4.4 / 7200 = 0.6 milliwatts.

A: TWO HOURS?  Your capacitor cannot store the amount energy that's required to heat up nichrome wire for even one minute.   Well, it might work for a second or so.   That's why we use batteries instead of capacitors.
At 250V, a 95uF capacitor stores about three joules of energy.    Compare this to a single triple-A battery which stores about 1000 joules of energy.  Three joules?  That can run a three-watt heater for only one second.
See the problem?  Capacitors can't provide heating unless they're really huge.
How long is your nichrome?  If it's not tiny, then to heat it significantly you probably want five or ten watts of energy flow.
Try using a 9v power supply to heat up 68ohms nichrome wire.  That gives 1.2W heating at 130mA current.  Barely warm.   If you want to burn your fingers, try using 24V power supply on your same wire.
Yes, supercapacitors would work, but their voltage is a bit too low to use with 68 ohms.  A large supercapacitor the size of a soup can stores about the same energy as one alkaline C-cell.   The usual supercapacitor trick is to short the capacitor with extremely thin copper or steel wire.  The wire resistance is a fraction of one ohm.  The wire gets very hot, very quickly, and can even glow red.

A: As capacitor is 95microF +5% 250v.ac 50/60Hz.
Energy of capacitor = C * V^2 / 2
Q= 0.000095*240^2 = 2.736 J = 2.7W
if you provide 2.7W to nichrome  for 1 second you won't feel any heat.
heat ?
specific heat of nichrome = 455 J/kg.K
eg. 10 gram of nichrome needs around 4.55 J to bring up 1 Celsius of it's  current temperature.
you need to try with lithium battery or acid lead battery  or supercapacitor


text:
Q: SpriteKit changing .atlas contents doesn't remove from memory The problem i'm having is when changing contents of .atlas files in XCode. if I change file names or add another image into the atlas folder the changes are not taken by application.
As far as i understand Xcode builds .atlas folder contents as one image and propably created .plist files with coordinates where is which image in the atlas. Is that correct presumption?
If yes where can i find those files to delete them? It's kind of tedious to change the whole atlas name and images every time i need to change the atlas itself.
Thanks

A: Perform a clean (Product/Clean) holding down Shift to get a complete resource rebuild next time. If that's not enough, delete project's derived data and restart Xcode. Xcode is known for caching and reusing everything, so simply deleting the app from device or simulator may not be enough.


text:
Q: How can I change NumberFormatter::parseCurrency() behavior of accepting white space and non breaking space? I'm trying to parse localized currency strings to currency and float value.
Everything works well for a while, now we experiencing some problems. It seems that NumberFormatter::parseCurrency uses an additional invisible character:
Testcode:
<?php
$formatter = new NumberFormatter("de_DE", NumberFormatter::CURRENCY);
var_dump(array(
    $formatter->parseCurrency("88,22 €", $curr), // taken from output of $formatter->format(88.22)
    $formatter->parseCurrency("88,22 €", $curr), // input with keyboard
    $formatter->parseCurrency("88,22 \xE2\x82\xAc", $curr), // just a test
    $formatter->format(88.22),
    "88,22 €" // keyboard input
));

Output:
array(5) {
  [0]=> float(88,22)
  [1]=> bool(false)
  [2]=> bool(false)
  [3]=> string(10) "88,22 €" // this as input works
  [4]=> string(9) "88,22 €" // this not...
}

As you can see, there is a difference in string length of output 3 and 4.
I get same results in PHP 5.3 (ubuntu with mbstring enabled) and 5.4 (Zend Server on Mac OS X).
The main problem is, input values from my form (ZF1 Application) are equally to output with index 4...
any suggestions? thanks in advance
Edit1:
hexdump of working value:
00000000  38 38 2c 32 32 c2 a0 e2  82 ac 0a                 |88,22......|
0000000b

hexdump of non working value:
00000000  38 38 2c 32 32 20 e2 82  ac 0a                    |88,22 ....|
0000000a

Edit2:
It seems to be a problem with the used whitepsace. c2 a0 is NO-BREAK SPACE and (maybe?) required by NumberFormatter::parseCurrency(). but 0x20 is the default space (which is entered in the input form).
Current workaround is replacing the whitespace with NO-BREAK SPACE with $value = str_replace("\x20", "\xC2\xA0", $value);
Edit3:
On another System (Mac OS X with Zend Server 5.6, mbstring enabled, PHP 5.3.14) everything works as expected:
array(5) {
  [0]=> float(88,22)
  [1]=> float(88,22)
  [2]=> float(88,22)
  [3]=> string(9) "88,22 €"
  [4]=> string(9) "88,22 €"
}

Edit4:
The main difference between working with space and working with non break space configuration is the ICU version:
working version:
intl

Internationalization support => enabled
version => 1.1.0
ICU version => 3.8.1

Directive => Local Value => Master Value
intl.default_locale => no value => no value
intl.error_level => 0 => 0

not working version:
intl

Internationalization support => enabled
version => 1.1.0
ICU version => 4.8.1.1
ICU Data version => 4.8.1

Directive => Local Value => Master Value
intl.default_locale => no value => no value
intl.error_level => 0 => 0

A: NumberFormatter::parseCurrency is a thin wrapper around the ICU library function unum_parseDoubleCurrency (see source).
The ICU library function is restrictive in that it will only parse strings that would result from its dual function unum_formatDoubleCurrency. The format is driven by the Unicode locale data, which specifies a non-breaking space between the currency value and the numeric value. Evidently the earlier version of the library accepted other whitespace characters.
In short, you can't make NumberFormatter::parseCurrency accept spaces. However, Zend_Currency should also output non-breaking spaces by default:
$currency = new Zend_Currency(array(
     'currency' => 'EUR',
     'value'    => 88.22,
), 'de_DE');

var_dump(
    strval($currency),             // 88,22 €
    strpos($currency, "\x20"),     // false
    strpos($currency, "\xc2\xa0")  // 5
);

The question is which part of your application is outputting a space and how you address it. You mention it's part of your form, so maybe you could look at having the form return the currency and the value as separate fields, so that you don't have to worry about parsing the number. If the user is entering the string "88,22 €" themselves, you could potentially run in to more problems than just the whitespace issue. Having said that, the workaround you mention (replacing \x20 with \xc2\xa0) is the only way to address that if you want to use NumberFormatter.


text:
Q: How do I encode/decode this BeautifulSoup string in Python so that non-standard Latin characters are output? I am scraping a page with Beautiful Soup, and the output contains non-standard Latin characters that are showing up as hex.
I am scraping https://www.archchinese.com. It contains pinyin words, which use non-standard latin characters (ǎ, ā, for example). I've been trying to loop through a series of links that contain pinyin, using the BeautifulSoup .string function along with utf-8 encoding to output these words. The word comes out with hex in the places of non-standard characters. The word "hǎo" comes out as "h\xc7\x8eo". I'm sure I'm doing something wrong with encoding it, but I don't know enough to know what to fix. I tried decoding with utf-8 first, but I'm getting an error that the element has no decode function. Trying to print the string without encoding gives me an error about the characters being undefined, which, I figure, is because they need to be encoded to something first.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import re

url = "https://www.archchinese.com/"

driver = webdriver.Chrome() #Set selenium up for opening page with Chrome.
driver.implicitly_wait(30)
driver.get(url)

driver.find_element_by_id('dictSearch').send_keys('好') # This character is hǎo.

python_button = driver.find_element_by_id('dictSearchBtn')
python_button.click() # Look for submit button and click it.

soup=BeautifulSoup(driver.page_source, 'lxml')

div = soup.find(id='charDef') # Find div with the target links.

for a in div.find_all('a', attrs={'class': 'arch-pinyin-font'}):
    print (a.string.encode('utf-8')) # Loop through all links with pinyin and attempt to encode.

Actual results:
b'h\xc7\x8eo'
b'h\xc3\xa0o'
Expected results:
hǎo
hào
EDIT: The problem seems to be related to the UnicodeEncodeError in Windows. I've tried to install win-unicode-console, but no luck. Thanks to snakecharmerb for the info.

A: You don't need to encode the values when printing - the print function will take care of this automatically.  Right now, you're printing the representation of the bytes that make up the encoded value rather than just the string itself.
>>> s = 'hǎo'
>>> print(s)
hǎo

>>> print(s.encode('utf-8'))
b'h\xc7\x8eo'

A: Use encode while you are calling BeautifulSoup, not after.
soup=BeautifulSoup(driver.page_source.encode('utf-8'), 'lxml')

div = soup.find(id='charDef') # Find div with the target links.

for a in div.find_all('a', attrs={'class': 'arch-pinyin-font'}):
    print (a.string)


text:
Q: Magento 2: Way to Show Customer IP on "Customers Now Online" I've seen in Magento 2 documentation, it should show IP of "Now Online" customers. However I cannot find any setting related to enable this from admin, and there is no filter option for IP.
Is there a way to show IP of customer who are currently online in website ?

A: Magento 2 native doesn't have feature to show customer IP who is online. There is other way, you have to create one module for display ip in back-end online customer grid. In that module create one di.xml file and use customer login event for get and save customer ip in 'customer_visitor' table. Create one column in customer online grid at back-end and display this ip from 'customer_visitor' table. You can get IP via below code.
$om = \Magento\Framework\App\ObjectManager::getInstance();
$obj = $om->get('Magento\Framework\HTTP\PhpEnvironment\RemoteAddress');
$ip =  $obj->getRemoteAddress();

I hope this will help you.

A: This answer from Waqar Ali is pretty much what you need.
https://magento.stackexchange.com/a/287427/106164
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;

class Index extends Action {
    private $remoteAddress;

    public function __construct(RemoteAddress $remoteAddress) {
        $this->remoteAddress = $remoteAddress;
    }

    public function execute()
    {
        $ip = $this->remoteAddress->getRemoteAddress();
        echo "Visitor's IP = ".$ip;
    }
}


text:
Q: Не могу изменить цвет кнопки через кастомный xml файл создал кастомный xml файл, где указал оранжевый цвет, и немного скруглил углы, после создания кнопки указал в качестве бекграунда созданный xml файл, но цвет кнопки остался прежним, в чем может быть дело ?

A: Скорей всего у вас стоит Material тема и поэтому все Button превращаются в MaterialButton
В документации написано, что для MaterialButton лучше не использовать android:background:

All attributes from R.styleable.MaterialButton are supported. Do not use the android:background attribute. MaterialButton manages its own background drawable, and setting a new background means MaterialButton can no longer guarantee that the new attributes it introduces will function properly. If the default background is changed, MaterialButton cannot guarantee well-defined behavior.

Если вы хотите изменить радиус углов, то используйте app:cornerRadius, а для цвета app:backgroundTint
<Button
    ...
    app:backgroundTint="#FFCE14"
    app:cornerRadius="10dp" />


text:
Q: CLR20r3 event stopped working Recently I have made a windows recovery after that every time I start my PC this error pop-up at start-up. Saying : ecc2e7c8601d3dbbd56eea6b0cc42475.exe has stopped working

This is very irritating. How can I solve this?

A: Run CCleaner and use fix registry function to solve this problem.Worked here !


text:
Q: Nested React list not working I am trying to recursively render JSON data to nested list using React. Right now I am using simple data object like this:
[{"id": "1",
 "name": "Luke"
},
{"id": "2",
 "name": "Jim",
  "childNodes":[{
    "id": "3",
    "name": "Lola"
   }]
}]

using this class:
export default class NestedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = (child) => {
    if (child.childNodes) {
      return (

          {child.myData.map(item => {
            return this.renderChild(item);
          })}

      );
    }
    else if (child.name) {
      return <input type="checkbox"><Child name={child.name}/></input>;
    }
    return null;
  }

  render() {
    return (

Data Sets

            {this.renderChild(this.props.myData)}

    );
  }
}

which calls a Child class that creates list element:
export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (

{name}

    );
  }
}

but it doesn't print anything. I have tried removing attribute childNodes altogether and tried to print the list but it doesn't work still. I don't understand where I am doing wrong. I would appreciate some help regarding how to fix this.

A: You need to map through myData first so the rendering process begins:

  {this.props.myData.map(data => this.renderChild(data))}

Also, on childNodes you need to loop through child.childNodes:
if (child.childNodes) {
  return (

      {child.childNodes.map(node => this.renderChild(node))}

  );
}

A: there were couple of issues here:

*

*You passed myData to renderChild which doesn't hold childNodes
property nor name property. Hence none of the conditions were met
(null was returned).
So maybe you should loop through myData and
pass each member of the array to renderChild.

*Even if we will pass a valid "child" to the renderChild method,
inside this condition:
if (child.childNodes) {

Again you are using a wrong property:

  {child.myData.map(item => {
  return this.renderChild(item);
  })}

this should be:
{child.childNodes.map(item => {...

*Last thing, You can't nest child elements inside an input element.
so change the layout, maybe like this? :
  <input type="checkbox"/>
  <Child name={child.name} />

Here is a running example with your code:

const data = [
  {
    id: "1",
    name: "Luke"
  },
  {
    id: "2",
    name: "Jim",
    childNodes: [
      {
        id: "3",
        name: "Lola"
      }
    ]
  }
];

class NestedList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = child => {
    if (child.childNodes) {
      return (

          {child.childNodes.map(item => {
            return this.renderChild(item);
          })}

      );
    } else if (child.name) {
      return (

          <input type="checkbox"/>
          <Child name={child.name} />

      );
    }
    return null;
  };

  render() {
    return (

Data Sets

{this.props.myData.map(item => this.renderChild(item))}

    );
  }
}

class Child extends React.Component {
  render() {
    let { name } = this.props;
    return
{name}
;
  }
}

ReactDOM.render(<NestedList myData={data} />, document.getElementById("root"));


text:
Q: Prove that if $E \in \mathcal{S} \otimes \mathcal{S}$ then $\{x\in X: (x,x) \in E\} \in \mathcal{S}$ Problem: Suppose $(X,\mathcal{S})$ is a measurable space. Prove that if $E \in \mathcal{S} \otimes \mathcal{S}$, then $\{x \in X: (x,x) \in E\} \in \mathcal{S}$
I know that for any $E \in \mathcal{S} \otimes \mathcal{S}$, $[E]_a$ and $[E]^b \in \mathcal{S}$, for any $a, b \in E$.  So, by setting $a=b$, we get that $([E]_a \cap [E]^a) \otimes ([E]_a \cap [E]^a)=\{(a,a)\} \in \mathcal{S}$. Now, when $E=X$, we have that $\{(x,x)\}\in \mathcal{S}\otimes \mathcal{S}$, $\forall x \in X$.
However, I cannot grasp how to proceed anywhere from this towards a solution to the given problem. Any hint/solution is welcome.
Thank you.

A: The collection of all sets $E \in \mathcal S\otimes \mathcal S$ such that $\{x: (x,x) \in E\}$ belongs to  $\mathcal S$  is a $\sigma-$ algebra which contains sets of the type $E=A\times B$ where $A$ and $B$ belong to $\mathcal S$. Hence this class contains $S\otimes \mathcal S$ and this is what we are asked to prove. [This is the idea of the proof. Details are very straightforward].


text:
Q: Progressbar not showing when using Theme.NoTitleBar I want show my progress bar when loading my data and to make my activity full screen without a title bar.
I set my activity to be full screen by adding this to my manifest:
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

When I remove that theme on my manifest the progress bar is showing normally.
Any ideas to make my activity full screen and my progress bar show??
Thanks..
Please help me...

A: Try android:theme="@android:style/Theme.NoDisplay"

A: Instead of using Theme.NoTitleBar.fullscreen, use this,have the same effect.
 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

    <item name="colorPrimary">@color/colorLightBlue</item>
    <item name="colorPrimaryDark">@color/colorLightBlue</item>
    <item name="colorAccent">@color/colorAccent</item>
     <!-- use below. -->
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
   </style>


text:
Q: Excel Interop Range.Value = arr[,] crashes with 0x800A03EC when arr[,] contains Date less than 1900-01-01 I understand the basic problem is that Excel represents 1900-01-01 as the value of 1.  However, in Excel it's possible to manually type in values pre-1900.
// this converts the DataTable to an Object[,]
DataTable table = ...
Object[,] arr = DataTableUtils.toObjectArray(table, false);

Range r00 = r0.get_Resize(arr.GetLength(0), arr.GetLength(1));
r00.Value = arr; // <-- this will crash if ...

If the arr[,] contains a DateTime object pre 1899-12-31 then a 0x800A03EC exception will result.  Oddly enough, 1899-12-31 is fine, Excel adds one day to the value.  Originally I replaced pre 1900 dates with 1900-01-01, but in the output file, they were 1900-01-02!
For now, I'm living with the workaround solution to replace the bad DateTime values.  However, if someone has a better solution then please let me know.


text:
Q: When will this design pattern break? I was trying to write a plugin for d3.js recently and have been confused with something perhaps trivial. There is an explanation on d3's website on how to go about creating reusable charts. The pattern looks something like this (only the most important details, full code is here):
Design Pattern 1: From d3 website
function timeSeriesChart() {
  var margin = {top: 20, right: 20, bottom: 20, left: 20},
      ...
      area = d3.svg.area().x(X).y1(Y),
      line = d3.svg.line().x(X).y(Y);

  function chart(selection) {
    selection.each(function(data) {

      // Convert data to standard representation greedily;
      // this is needed for nondeterministic accessors.
      data = data.map(function(d, i) {
        return [xValue.call(data, d, i), yValue.call(data, d, i)];
      });

      // Update the x-scale.
      ...

      // Update the y-scale.
      ...

      // Select the svg element, if it exists.
      var svg = d3.select(this).selectAll("svg").data([data]);
      ...

      // Otherwise, create the skeletal chart.
      var gEnter = svg.enter().append("svg").append("g");
      ...
  }

  // The x-accessor for the path generator; xScale ∘ xValue.
  function X(d) {      }

  // The x-accessor for the path generator; yScale ∘ yValue.
  function Y(d) {      }

  chart.margin = function(_) {
    if (!arguments.length) return margin;
    margin = _;
    return chart;
  };

  chart.width = function(_) {
    if (!arguments.length) return width;
    width = _;
    return chart;
  };

  chart.height = function(_) {
    if (!arguments.length) return height;
    height = _;
    return chart;
  };

  chart.x = function(_) {
    if (!arguments.length) return xValue;
    xValue = _;
    return chart;
  };

  chart.y = function(_) {
    if (!arguments.length) return yValue;
    yValue = _;
    return chart;
  };

  return chart;
}

I have no doubt that this pattern is robust especially because it was suggested by the creator of d3 himself. However, I have been using the following pattern for some time without problems before I came across that post (similar to how plugins are created in general):
Design Pattern 2: General way of creating plugins
(function() {
    var kg = {
        version: '0.1a'
    };

    window.kg = kg;

    kg.chart = {};

    // ==========================================================
    // CHART::SAMPLE CHART TYPE
    // ==========================================================
    kg.chart.samplechart = {

        // ----------------------------------------------------------
        // CONFIGURATION PARAMETERS
        // ----------------------------------------------------------
        WIDTH: 900,
        HEIGHT: 500,
        MARGINS: {
            top: 20,
            right: 20,
            bottom: 20,
            left: 60,
            padding: 40
        },
        xRange: d3.time.scale(),
        yRange: d3.scale.linear(),
        xAxis: d3.svg.axis(),
        yAxis: d3.svg.axis(),
        data: {},

        // ----------------------------------------------------------
        // INIT FUNCTION
        // ----------------------------------------------------------
        init: function() {
            // Initialize and add graph to the given div
            this.update();
        },

        // ----------------------------------------------------------
        // Redraws the graph
        // ----------------------------------------------------------
        update: function() {
            var parentThis = this;
            var newData = parentThis.data;

            // Continue with adding points/lines to the chart

        },
        // ----------------------------------------------------------
        // Gets random data for graph demonstration
        // ----------------------------------------------------------
        getRandomData: function() {
            // Useful for demo purposes

        }
    };

    // ==========================================================
    // HELPER FUNCTIONS
    // ==========================================================

}());

// EXAMPLE: This renders the chart.
kg.chart.samplechart.vis = d3.select("#visualization");
kg.chart.samplechart.data = kg.chart.samplechart.getRandomData();
kg.chart.samplechart.init();

I have been using Design Pattern 2 for some time without any problems (I agree it is not super clean but I'm working on it). After looking at Design Pattern 1, I just felt it had too much redundancy. For instance, look at the last blocks of code that make the internal variables accessible (chart.margin = function(_) {} etc.).
Perhaps this is good practice but it makes maintenance cumbersome because this has to be repeated for every different chart type (as seen here in a library called NVD3, currently under development) and increases both development effort and risk of bugs.
I would like to know what kind of serious problems I would face if I continue with my pattern or how my pattern can be improved or made closer to spirit of Design Pattern 1. I am trying to avoid changing patterns at this point because that would require a full rewrite and will introduce new bugs into a somewhat stable mini-library. Any suggestions?

A: In fact, you can find your second pattern in the d3 source code.
(function(){
...
d3 = {version: "2.9.6"}; // semver
...

d3.svg = {};
d3.svg.arc = function() {
  var innerRadius = d3_svg_arcInnerRadius,
      outerRadius = d3_svg_arcOuterRadius,
...

But the components and generators, like scale, axis, area and layout, tend to use the pattern we can call "charts as closures with getter-setter methods" or " higher-order programming
through configurable functions". You can follow this discussion on the Google Group thread for rationale.
Personally, I don't like this redundancy neither, even if it is useful and fairly readable. So  I generate these getters and setters automatically using a custom function:
d3.helper.createAccessors = function(visExport) {
    for (var n in visExport.opts) {
        if (!visExport.opts.hasOwnProperty(n)) continue;
        visExport[n] = (function(n) {
            return function(v) {
                return arguments.length ? (visExport.opts[n] = v, this) : visExport.opts[n];
            }
        })(n);
    }
};

Which I use like this at the end of my chart module:
d3.helper.createAccessors(chart, opts);

Where opts is the name of all the public function:
var opts = {
            width: 200,
            margin: [5, 0, 20, 0],
            height: 200,
            showPoints: true,
            showAreas: false,
            enableTooltips: true,
            dotSize: 4
        };

Here is a complete example: http://jsfiddle.net/christopheviau/YPAYz/


text:
Q: How to show autocompletion for empty Gtk+ Entry How can i use Gtk+ 3 EntryCompletion and Entry to show auto completion suggestions even if the entry is empty?
I tried forcing the entry to show the auto completion with completion.complete() but it does not work.
My code looks something like this:
class MainWindow(Gtk.Window):
    def init(self):
        Gtk.Window.init(self, title="...")
        # ...
        self.liststore = Gtk.ListStore(str)
        self.completion = Gtk.EntryCompletion()
        self.completion.set_model(self.liststore)
        self.completion.set_text_column(0)
        #...
        for h in history:
            self.liststore.append((h,))
        #...
        self.query_entry = Gtk.Entry()
        self.query_entry.set_completion(self.completion)
        self.completion.complete()

Another thing i would like to know: If i want to auto-complete file paths, how can i force showing the auto completion suggestions right after i selected an auto completion?

A: You can force the completion to popup using:
self.completion.set_minimum_key_length(0)
self.query_entry.emit('changed')

This sets the completion to show the completion even with no text, and the emit('changed') is what happens when the text changes.


text:
Q: How to display Japanese characters passed through an ajax query on a jsp page I have a .jsp page and that makes an ajax request to a different .jsp page. The query parameter contains Japanese characters. I have confirmed by looking at the request that the characters are getting passed correctly. However the string is not received correctly on the other side.
Here are the files:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            url = "ajaxHandler.jsp";
            $.ajax({
                type : "GET",
                url : url,
                data: {  parameter : "\u306f" },
                dataType : "html", //expect html to be returned
                success : function(response) {
                    console.log("successful query");
                }
            });
        });
    </script>
</head>
<body>

ajaxHandler.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
    String val = request.getParameter("parameter");
%>
<br>
<%=val %>

When I hit the url "https:.../ajaxHandler.jsp?parameter=%E3%81%AF",  a completely different character is displayed.
I suspect that there is an issue with the character encoding for the page. I have tried with "utf-8" and now with "shift-jis" , but still I cannot get the string displayed.
So I want to know basically why do we specify the charset and how is it used here. Also please tell how can I get the string.
PS: "\u306f" is an actual japanese character thats getting displayed in eclipse and not its unicode as here.

A: Edit server.xml file, located in tomcat conf folder.
according to the relevant connector specify URIEncoding as UTF-8
For instance, I am using https connector, so the connector configuration in the server.xml looks like that:

As you have updated server.xml, restart your Tomcat.
That's it.


text:
Q: Pyspark - Sample without replacement As I noticed, I have a very unbalanced variable. So, I want to sample it by giving weights to each class of my variable. This is my dataset (dd):
l = [('Alice', 1),('Alice', 1),('Alice', 1),('Alice', 1),('Alice', 1),('Alice',1),('Mary', 1),('Alice', 1),('Alice', 1),('Mary', 1)]
dd == spark.createDataFrame(l)

dd.show()
+-----+------+
| Name| Label|
+-----+------+
|Alice|     1|
|Alice|     1|
|Alice|     1|
|Alice|     1|
|Alice|     1|
|Alice|     1|
| Mary|     1|
|Alice|     1|
|Alice|     1|
| Mary|     1|
+-----+------+

I want Alice and Mary to have the same percentage on my dataset.I used this :
  sampledDf = dd.sampleBy("_1", fractions={"Alice":0.5, "Mary":0.5}, seed=1234)

and I got no error. But, when I try to see the sampledDf (sampledDf.show()), my command is not running.
Which is the proper way to do this?

A: Is this the result you are hoping for:
+-----+---+
|   _1| _2|
+-----+---+
|Alice|  1|
|Alice|  1|
| Mary|  1|
|Alice|  1|
| Mary|  1|
+-----+---+

Can you provide desired output?
Also check if the command is running in background or crashed


text:
Q: Is there a way to access local files without having to use upload() option in Google Colab or uploading the data to the drive and then accessing it I have data in my local drive spread over a lot of files. I want to access those data from Google Colab. Since it is spread over a large area and the data is susceptible to constant change I don't want to use the upload() option as it can get tedious and long.
Uploading to Drive is also something I am trying to avoid, due to the changing data values.
So I was wondering if there is another method to access the local data something similar to the code presented.
def list_files(dir):
    r = []
    for root, dirs, files in os.walk(dir):
        for name in dirs:
            r.append(os.path.join(root, name))
    return r

train_path = list_files('/home/path/to/folder/containing/data/')

This does not seem to work since GC cannot access my local machine. So I  always get an empty array (0,) returned from the function

A: The short answer is: no, you can't. The long answer is: you can skip the uploading phase each time you restart the runtime. You just need to use google.colab package in order to have a similar behaviour to the local environment. Upload all the files you need to your google drive, then just import:
from google.colab import drive
drive.mount('/content/gdrive')

After the authentication part, you will be able to access all your files stored in google drive. They will be imported as you have uploaded them, so you just have to modify the last line in this way:
train_path = list_files('gdrive/path/to/folder/containing/data/')

or in this way:
train_path = list_files('/content/gdrive/home/path/to/folder/containing/data/')


text:
Q: Certain programs on Lulu app (Objective see) are not filtered I am finding that certain apps (on Monterey) are not being filtered. These are native apple apps. Even if I disable network access, on reboot, it resets. When I deny access, it adds another deny rule. That results in 2 rules, one saying allow the other saying deny.
This can happen in pf like firewalls as well, but pf has strict rules on how any line will be evaluated from top to bottom.
How does lulu evaluate rules from top to bottom? Will it take the topmost rule and stop evaluating rules at the bottom, for the same program?
P.S. I do see that certain apple programs are not bypassing Lulu and LittleSnitch firewalls: https://news.ycombinator.com/item?id=24838816

A: If Apple doesn't pass their traffic through the network extension that LuLu uses, then you are correct.
The FAQ doesn't address this directly, but I seem to recall the author calling out a few notable exceptions in a talk recently but don't see details posted publicly on specifics.
If you have some, opening an issue (see GitHub link at the end of the FAQ) might get you a more authoritative confirmation of this.

*

*https://objective-see.org/products/lulu.html
The allow rule for all signed Apple apps is a recent feature, so if you're on LuLu v 1.2.0 you could try disabling the signed Apple app check box and perhaps have better blocking ( and likely some breakage of functions in the OS too ).

*

*https://github.com/objective-see/LuLu/issues/97#issuecomment-466268797


text:
Q: Add dynamic description and canonical via Middleman and HAML Trying to add acanonical link tags to the head of my Middleman App document via HAML but not sure how to do it.
%link(rel="canonical" href="current_page.data.canonical")

Using YAML such as
---
title: Swan Physio
description: This is the description
canonical : http://swanphysio.co.uk
---

A: You can do it like this:
%link(rel="canonical" href='http://example.com#{current_page.url}')


text:
Q: No auto configuration classes found in META-INF/spring.factories I am trying to create a executable jar file with Eclipse from my Spring Boot application. The plugin I have in my pom.xml is below
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <mainClass>nl.insiteweb.acc.Application</mainClass>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

The complete error I get is:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [nl.insiteweb.acc.Application]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
    at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:520) ~[testproject.jar:na]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:184) ~[testproject.jar:na]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:308) ~[testproject.jar:na]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:228) ~[testproject.jar:na]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:270) ~[testproject.jar:na]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93) ~[testproject.jar:na]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686) ~[testproject.jar:na]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524) ~[testproject.jar:na]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[testproject.jar:na]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [testproject.jar:na]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [testproject.jar:na]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [testproject.jar:na]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [testproject.jar:na]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [testproject.jar:na]
    at nl.insiteweb.acc.Application.main(Application.java:16) [testproject.jar:na]
Caused by: java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
    at org.springframework.util.Assert.notEmpty(Assert.java:276) ~[testproject.jar:na]
    at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.getCandidateConfigurations(AutoConfigurationImportSelector.java:152) ~[testproject.jar:na]
    at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.selectImports(AutoConfigurationImportSelector.java:94) ~[testproject.jar:na]
    at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:512) ~[testproject.jar:na]
    ... 14 common frames omitted

I have no idea what I'm doing wrong here. Im trying to make a executable JAR file with the Export within Eclipse. All help is much appreciated.


text:
Q: adding metadata to filtering in django rest framework I have a generic ListCreateAPIView view. I've implemented a get_queryset function that performs a search. The function parses the query, extract tags and terms and returns a query set.
def get_queryset(self):
        query = self.request.QUERY_PARAMS.get('query', None)

        # No deleted items
        queryset = Items.objects.filter(deleted__isnull=True)

        if query is None:
            return queryset

        predicates = []

        # Generate predicates from query

        queryset = queryset.filter(reduce(__and__,predicates))
        return queryset

What is the best way to add metadata to the response with data from the get_queryset function ?
I'm looking for something similar to the way pagination works.
{
 query : {
     terms : ['term1','term2'],
     tags  : ['tag1','tag2'] ,
    }
 results : [
      { name : 'item1', .... }
      { name : 'item2', .... }
   ]
}

EDIT
So i created a custom FilterBackend for the filtering and I now have an instance of the request and the response. Looking at the pagination code for django rest i see it's wrapping the results in serializer. The pagination is build into the view class so the fw invokes the serialization if a paginator is detected. Looking at the search api did not produce any new ideas.
My question remains, What is the best, and least intrusive way, of adding metadata from the filter backend to the response ?
One way i can think of (and one that i don't like) is to overload the matadata onto the request in the filter backend and override finalize_response in the view - without a doubt the worst way to do it.

A: I'm not sure it's the best way, but I would probably override get to simply intercept the response object and modify response.data however you wish. Something as simple as
from rest_framework import generics

class SomeModelList(generics.ListCreateAPIView):
    """
    API endpoint representing a list of some things.
    """

    model = SomeModel
    serializer_class = SomeModelSerializer

    def get(self, request, *args, **kwargs):
        response = super(SomeModelList, self).get(request, *args, **kwargs)

        # redefine response.data to include original query params
        response.data = {
            'query': dict(request.QUERY_PARAMS),
            'results': response.data
        }

        return response

If you found yourself repeating this for multiple list views you could keep yourself DRY using a Mixin and include it in your list API classes:
from rest_framework import generics
from rest_framework.mixins import ListModelMixin

class IncludeQueryListMixin(ListModelMixin):
    def list(self, request, *args, **kwargs):
        response = super(IncludeQueryListMixin, self).list(request, *args, **kwargs)

        # redefine response.data to include original query params
        response.data = {
            'query': dict(request.QUERY_PARAMS),
            'results': response.data
        }

        return response

class SomeModelList(IncludeQueryListMixin, generics.ListCreateAPIView):
    """
    API endpoint representing a list of some things.
    """

    model = SomeModel
    serializer_class = SomeModelSerializer


text:
Q: Write file to HDFS from (non-cluster) local machine I am trying to find some tips to solve my problem. But I really have no idea how to do it.
I have a HADOOP HDFS and I need to write data from my local machine to HDFS using Java. Currently, I've solved it in this way:

*

*Create file on my local machine

*Create SSH connection to cluster where Hadoop is installed

*Copy file to cluster(local OS)

*Copy file from local cluster OS to HDFS(hadoop fs -put).

It works fine but now I need to copy files without SSH. I mean, I need to do in this way:

*

*Create file on my local machine(not in Cluster)

*Copy file directly to HDFS

All examples what can I could find show how to copy files from local OS (cluster) to HDFS. Has anyone solved a problem like this?
I write code like this:

    System.setProperty("java.security.auth.login.config", "jaas.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");

    UsernamePasswordHandler passHandler = new UsernamePasswordHandler("user", "pass");

    LoginContext loginContextHadoop = new LoginContext("Client", passHandler);
    loginContextHadoop.login();

    Configuration configuration = new Configuration();
    configuration.set("hadoop.security.authentication", "Kerberos");
    org.apache.hadoop.security.UserGroupInformation.setConfiguration(configuration);
    org.apache.hadoop.security.UserGroupInformation.loginUserFromSubject(loginContextHadoop.getSubject());

    FileSystem hdfs = FileSystem.get(new URI("hdfs://URI:50020"), configuration);

    System.out.println(hdfs.getUsed());

And getting error like this:
org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.ipc.RpcNoSuchProtocolException): Unknown protocol: org.apache.hadoop.hdfs.protocol.ClientProtocol
I think i use wrong port, i get it from dfs.datanode.ipc.address. Does anybody has any ideas?


text:
Q: Extract value from RStudio manipulate package control Is there a way to extract current value from a slider control in manipulate package? For example:
library(manipulate)

xx <- seq(-pi, pi, pi/20)

manipulate(
  plot(xx, sin(par.a*xx)),
  par.a = slider(-3, 3, step=0.01, initial = 1))

After playing with the slider I would like to get the value of par.a for further calculations without having to look at the control and write it by hand each time.

A: Figured it out myself.
It is possible to do with global variables
manipulate(
  {plot(xx, sin(par.a*xx))
  a <<- par.a},
  par.a = slider(-3, 3, step=0.01, initial = 1))

Maybe it will be of assistance to somebody.


text:
Q: Modeshape - removing node binary files In our test server we want to delete nodes. We use below code
        Repository repository = .... ;
        Session session = null;
        session = repository.login(new SimpleCredentials(getApplicationName(), getPassword().toCharArray()));

        JcrTools jcrTools = new JcrTools();

        if (!session.nodeExists(fileInfo.getRealPath())) {
            return;
        }
        Node node = session.getNode(fileInfo.getRealPath());
        //delete children nodes if exists
        jcrTools.removeAllChildren(node);
        //delete all properties include mixins
        PropertyIterator pIt = node.getProperties();
        while (pIt.hasNext()) {
            javax.jcr.Property property = pIt.nextProperty();
            property.remove();
        }
        node.remove();
        session.save();
        session.logout();

The method works, we see that the files are deleted from modeshape-explorer web application. But we also see that binary files are in the binaries folder of the repository, so the nodes are not removed physically, the disk usage does not alter. What may be the problem?

A: Unused binary values will eventually be removed in a background thread, which by defaults executes once per day.
You can easily configure this via the repository's JSON configuration. For example:
{
  ...
  "garbageCollection" : {
    "threadPool" : "modeshape-gc-pool",
    "initialTime" : "00:00",
    "intervalInHours" : 24,
  }
  ...
}

The values shown above are the defaults, but obviously you can change them and include only those non-default fields that make sense.


text:
Q: Git commands - how to get the code from master branch to my branch I'm working on a group project where we have a branch for each member and a master branch.
My question is, how can I get the code that is in the master branch into my own branch locally? If you can tell me the commands I need to do? Been worried I will mess it up somehow.
I am using Git Bash and the project is on GitLab
Would be appreciated, I've searched online and I'm just getting more confused, hoping someone here could tell me more simply.

A: You can do a git rebase:
git rebase <your-branch-name-here> master

NOTE: Don't forget to stash any unstaged changes by doing git stash before performing rebase. After rebase, do git stash pop to unload those changes. Mind you there might be merge conflicts depending what your local changes were.


text:
Q: Getting the emitted value by pyqtsignal in QThreads in PyQt I am trying to get the value emitted by Class Qthread's signal without using the function
I am calling alert box when the user chooses to exit and press [X] button on GUI so I called this alert box by the means of threading to ensure that my GUI doesn't freeze.
Below is the code for that:
class ABC:
    def __init__(self):
             self.close = CloseThread() # Creating instance of QThread Class
........
........
........
    def closeEvent(self, event):
    button = self.close.CloseResult
    self.close.start()
    if button == 1:
        event.accept()
    else:
        event.ignore()

class CloseThread(QThread):
"""Threading class which is emitting the return value according to the choice
   of the user(When the message appears, if the user chooses
   'Ok' then return value is 1 and if the user chooses
   'Cancel'return value is 2)"""
CloseResult = QtCore.pyqtSignal(object)

def __init__(self):
    QThread.__init__(self)

def close(self):
    button = win32api.MessageBox(0, 'Do you want to Exit?', 'Message')
    self.CloseResult.emit(button)

def run(self):
    self.close()

I know I can get the emitted value by self.close.CloseResult.connect(self.fn_name) instead of using self.close.CloseResult but I don't want to call another function because here I am extending the scope of closeEvent function so I don't want to call another function.(Actually by calling another function things aren't working out as they are supposed to)

Note: By using self.close.CLoseResult I am getting an object so is there any way to access this object's value or not?

So is there any way I can get emitted value just in a variable without having to call any other function?


text:
Q: regexp_replace string I'm using regexp_replace to standardize mailing addresses and I've encountered a situation I'm having trouble with.
Consider the following two addresses and what their result should be:

*

*115 1/2 East 6th St   ->   115 1/2 E 6th St

*818 East St -> 818 East St

In the second address, "East" is the actual name of the street, not a directional indicator.
For my query, I've attempted
SELECT
     regexp_replace(address, 'East[^ St]', 'E ')

but this fails to convert the first address to it's proper format.
How can I write my regexp_replace such that the word East is converted to an 'E' in the first address, but leaves the word intact in the second address?

A: Your current pattern matches the literal text East followed by any single character that isn't space, S, or t.  I'm assuming you probably meant to use a negative lookahead to make sure that "East" doesn't come before " St", but sadly Oracle doesn't support negative lookaheads.  Instead, you'll need to make the REGEXP_REPLACE conditional:
CASE
    WHEN address LIKE '%East%' AND address NOT LIKE '%East St%'
        THEN REGEXP_REPLACE(address, your_pattern, your_replacement)
    ELSE address
END

A: This answers your question with REGEXP_REPLACE().  It looks for the string ' EAST' (don't want to catch the case where 'east' is the end of another word) followed by a space, one or more characters, another space and the string 'St' which is remembered in a group.  If found, replace it with ' E' followed by the second remembered group (the space followed by the one or more characters followed by the space and 'St'.  This is needed as they are 'consumed' by the regex engine as it moves left to right analyzing the string so you need to put them back.  Note I added a bunch of different test formats (always test for the unexpected too!):
SQL> with tbl(address) as (
     select '115 1/2 East 6th St'       from dual union
     select '115 1/2 NorthEast 6th St'  from dual union
     select '115 1/2 East 146th St'     from dual union
     select '115 1/2 East North 1st St' from dual union
     select '818 East Ave'              from dual union
     select '818 Woodward'              from dual union
     select '818 East St'               from dual
   )
   select regexp_replace(address, '( East)( .+ St)', ' E\2') new_addr
   from tbl;

NEW_ADDR
------------------------------------------------------------------------
115 1/2 E 146th St
115 1/2 E 6th St
115 1/2 E North 1st St
115 1/2 NorthEast 6th St
818 East Ave
818 East St
818 Woodward

7 rows selected.


text:
Q: How to make sure a Private DNS zone is resolving a given private ip? The use case scenario here is that the private DNS resolves an internal IP acting as the default gateway of an API Manager - APIM.
In front of APIM, there is an Application Gateway with a backend pool targeting the private DNS.
I can see that the backend health status is unknown, and it might be related to the FQDN - associated with an internal Ip, not being resolved, but how can I make sure that it is the actual problem?

*

*I'd rather not have to create a whole VM just to ping it by name.

A: You can try either of the following ways to make sure Private DNS zone is resolving a given private IP.

Workaround 1:

*

*Create an Azure VNet with a DNS private zone like private.test.com.

*Create a VM and a VPN gateway on that VNet. Enable VNet integration.

*with my Azure web app service.

Workaround 2:

*

*Deploy new Azure Private DNS Zones
in your Azure environment part of private endpoint deployment.
(Default option)

*Use existing Azure Private DNS Zones.
Use this option if you using a private endpoint in a hub-and-spoke
model from a different subscription or even within the same
subscription.

*Use your own DNS Servers
if you do not use DNS forwarders and instead you manage A records
directly in your on-premises DNS servers.

Reference: Azure DNS zone record not resolving to specified IP from App service to Virtual Machine - Stack Overflow and Configure DNS Name Resolution for private endpoints - Azure Purview | Microsoft Docs


text:
Q: How can I isolate the cause of poor performance whne running X-Plane 11 in windowed mode? I used to run X-Plane 11 (flight simulator) when I was on Ubuntu 16.04 and had no performance issues other than when I pushed the limitations of my hardware. So, everything worked exactly as expected. However, after upgrading the 18.04, I can only achieve good performance when running XP11 in fullscreen mode and when XP11 has focus. If I carry my mouse to another monitor and shift focus to another program (e.g., firefox), my entire computer stutters. Furthermore, if I try to run the game in windowed mode my computer stutters horribly regardless of which program has focus. I do not believe my problem is with a necessary bottleneck in the system, because my CPU, GPU, and RAM are never maxed out when running the game. Furthermore, XP11 says I'm getting 40-60FPS while I'm experiencing the stuttering.
I submitted a support ticket to the XP11 devs, but received a very short response to the effect of "Sorry, we don't support Linux". This leaves me a bit uncertain about how to proceed. It seems like the problem is on the OS side rather than with XP11, but I'm not certain how to begin eliminating possible causes. Here are some relevant details:
System Specs:

*

*Graphics card: Sapphire Radeon R9 280

*Graphics drivers: Default Open-Source AMD drivers

*CPU: i5-4690K

*RAM: 16GB DDR3

*Three monitors (can provide more detail if needed)

*Game is X-Plane 11 version 11.36r2 run through Steam

I'm considering trying to use a different set of drivers, but in the past when I've experimented with graphics driver's I've ended up a sad panda for one reason or another (e.g., monitors go blank when booting up). Furthermore, I have no other issues with other games or programs so I'm a bit concerned about creating more problems. In any case, I'm willing to try messing around with graphics drivers if I need to, but I wanted to get some input before I start toying with an otherwise perfectly stable system.


text:
Q: Show ergodicity of transformation of ergodic map Let $(\Omega,\mathcal{A},\mathbb{P})$ and $(\Omega',\mathcal{A}',\lambda)$ be two measure spaces. If we have an ergodic map $f\colon \Omega \rightarrow\Omega$ and a bijection $h\colon \Omega'\rightarrow \Omega$ I would like to be able to make the conclusion that $$T:=h^{-1}\circ f\circ h$$ is ergodic if $T$ is measure preserving.
Is this even possible? I can only show ergodicity modulo the bijective transformation, e.g. $A\in\mathcal{A}$ is $f$ invariant (wrt. $\mathbb{P}$) iff $h(A)$ is $T$ invariant (wrt. $\lambda$). But this is a trivial result.

A: Lemma: Suppose $(\Omega,\mathcal{A},\mathbb{P},f)$ is ergodic and let $(\Omega^\prime,\mathcal{A}^\prime)$ be measurable space. If $h:\Omega\to\Omega^\prime$ is measurable and such that for some measure preserving $g:\Omega^\prime\to\Omega^\prime$
$$
g\circ h=h\circ f,
$$
Then $(\Omega^\prime,\mathcal{A}^\prime,h^*\mathbb{P},g)$ is ergodic.
From this your question is immediate.
Proof: Let $A^\prime\in\mathcal{A}^\prime$ be invariant under $g$. Then $f^{-1}(h^{-1}(A^\prime))=h^{-1}(g^{-1}(A^\prime))=h^{-1}(A^\prime)$. Hence, by ergodicity of $\mathbb{P}$, $h^*\mathbb{P}(A^\prime)\in\{0,1\}$.


text:
Q: Copy all words from widget on a website to a word file with a single operation How could I select all words in a widget on a website simultaneously? For example, I'd like to select all words in the widget called "Skills" on the following website:
https://opportunities.aiesec.org/search?type=1
The goal is copy in a word file the words: 3D MAX, ABAP etcetera that appear in the "Skills" box with a single operation.
Thank you for your help.

A: *

*Under Firefox, use contextual menu on the widget, choose "inspect element".

*In the console use contextual menu on the code of the div, choose "edit as HTML".

*Select all (ctrl+a) and copy (ctrl+c).

*Open a text editor supporting regular expression (I use jedit).

*In a new file, paste (ctrl+v).

*Remove HTML tags (replace "<[^>]+>" by "").

*Remove empty lines (replace "^$\n" by "").

Here is the result.


text:
Q: punctuation: chicken-fried steak Does anyone know why the adjective in "chicken-fried steak" is
hyphenated by some people but not by others? What do writing guides
on both sides of the pond say about this issue?
The following is its definition:

a thin piece of beef that is lightly battered and fried until crisp.

A: Frederic Cassidy, Dictionary of American Regional English (1985) spells the term with a hyphen, although it acknowledges at least one variant spelling:

chicken-fried steak n Also chicken-fry steak chiefly West A steak, usu an inexpensive cut, breaded and fried. [Examples from the 1960s and 1970s—including one unhyphenated instance of "Chicken Fry Steak"—omitted.]

Merriam-Webster's Eleventh Collegiate Dictionary (2003) insists on a single spelling, with hyphenation:

chicken-fried steak n (1952) : steak coated with batter, fried, and served with gravy.

The American Heritage Dictionary of the English Language, fifth edition (2010) views "chicken-fried" as an all-purpose modifier, not inextricably bound to "steak":

chicken-fried adj. Coated with butter and seasoned flour and fried: chicken-fried steak.

The idea that this compressed term conveys is "steak cooked in approximately the same manner as fried chicken"—not "steak prepared by a gallinaceous fry-cook." It is an extremely popular menu item in small-town eateries in Texas (where I grew up), although in my experience "chicken-fried bootleather" might in some cases be a more accurate term for it. Such restaurants tend not to seek out authoritative sources of spelling and punctuation for the items they offer before committing them to paper (and lamination), which probably contributes to the real-world variations one may encounter in the spelling and punctuation of "chicken-fried steak."
On a peripheral matter, I note that Merriam-Webster's first occurrence date of 1952 for the term is way off. Instances of "chicken-fried steak" appear in newspapers at least as early as June 1, 1924 (in Indianapolis, Indiana), October 21, 1926 (in Stephenville, Texas) and January 31, 1930 (in Eagle Rock [a neighborhood in Los Angeles], California). Instances of "chicken fried steak" appear as early as November 17, 1920 (in Breckenridge, Texas). Overall, Elephind newspaper database searches turn up 458 instances of "chicken-fried steak" and 5,920 instances of "chicken fried steak," suggesting that lots of folks feel no obligation to hyphenate the dang thing, regardless of what the dictionaries may say.

A: In its homeland of the American South, to chicken-fry is a verb, meaning to batter and deep-fry some chunk of beef (called a "steak" by convention, but usually pounded to reduce toughness).
The name comes from the fact that Southern fried chicken is cooked the same way (though usually without the pounding). Steaks cooked this way are said to have been chicken-fried. Traditionally they are served with sausage pan gravy.
As for the hyphen, since you can't hear it in speech, it's optional and therefore random in use, which is largely on restaurant menus.  (Chicken-fry the verb has its own entry in a Dutch dictionary.)

A: I'm British and I've never heard the phrase before. However, since you have defined it, I would punctuate it:
chicken-fried steak
This makes it clear that chicken-fried is a adjective describing the steak.
The only other possibility would be "chicken fried-steak".  This would refer to chicken steaks (if such a things exists) that had been fried.
Leaving out the punctuation means the phrase is ambiguous to those who aren't familiar with the phrase.
Answer
chicken-fried steak

A:
What do writing guides on both sides of the pond say about this issue?

As far as I am aware "chicken fried steak" is unknown in British English. I would have no idea what it meant with or without hyphens.


text:
Q: Relation has_and_belongs_to_many doesn't save data I've migration tags_words
class CreateTagsWords < ActiveRecord::Migration
  def change
    create_table :tags_words, id: false do |t|
       t.references :tag
       t.references :word
     end
     add_index :tags_words, :tag_id
     add_index :tags_words, :word_id
  end
end

model words and tags:
class Word < ActiveRecord::Base
    attr_accessible :namelanguage1, :namelanguage2, :tags_attributes

    has_and_belongs_to_many :tags

    def self.search(search)
        if search
            find(:all, :conditions => ['namelanguage1 LIKE ?', "%#{search}%"])
        else
            find(:all)
        end
    end
end

class Tag < ActiveRecord::Base
    attr_accessible :name, :language_user_id

    has_and_belongs_to_many :words

    def self.search(search)
        if search
            find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
        else
            find(:all)
        end
    end
end

and when I'll add tags to words and then save it doesn't save in db (when I write in rails console Words.find(1).tags i get empty array.

A: You'd need to use the << ActiveRecord method to add to the respective collections you have:
#app/controllers/words_controller.rb
def add_tag
    word = Word.find(params[:id])
    tag = Tag.find(params[:id])

    word.tags << tag
end

Your problem will either be caused by you not saving your data correctly, or not calling it properly

Update
If you want to add tags to the word's tags collection after you've created a new word, you'll be able to do something like this:
#app/controllers/words_controller.rb
def create
    @word = Word.new(word_params)
    @word.save
end

private

def word_params
    params.require(:word).permit(:namelanguage1, :namelanguage2, tag_ids: [])
end

#app/models/word.rb
Class Word < ActiveRecord::Base
    attr_accessor :tag_ids
    after_create :add_tags

    def add_tags
       if tag_ids
           tag = Tag.find(tag_ids)
           tags << tag
       end
    end
end


text:
Q: Is there memory leak in javascript of firefox/webkit? (except IE) I'm new to HTML5 application. And I'm making in-house software. This means I can force users to use only most recent version of firefox/webkit.
I saw many documents concerning about JS memory leaks in these point:

*

*Circular references.

*Event handlers.

*Closures.

As I think, it's just a problem of only (old version of) IE. But I cannot sure about this. So I'm asking do I have to address this issue in my situation. If I should, what's the solution, and what's the additional issues I have to care?

A: Use a javascript library and you will be fine.  jQuery makes it so you can have circular references, closures that refer back to jQuery objects, and event handlers that you never clean up.  jQuery will automatically pick up all the pieces on unload if necessary and will also keep memory from leaking in any browser it supports.
If you are developing a JS-based application in which the page never (or rarely) refreshes, then you might have to worry about leaks, but they are easily overcommable by making plugins which have a deconstructors that destroys all member objects and dom elements.  The jQuery .remove function removes the dom elements, the handlers, and anything else attatched to that element.
So just use a JS library and if you have to develop a lot of JS code, be careful and use a design pattern that is easy to clean up (like jQuery's plugin design pattern).


text:
Q: Window object as Global Variables Inside Function always undefined Hi I dont know what I'm missing but if its always says undefined.
function report_grid() {
$.ajax({
    type: "POST",
    url: "filter_option.php?action=filter",
    data: $('#form1').serialize(),
    async: false,
    success: function(rdata) {
        window.my_var = rdata
    }
})
}
$('#onscreen').click(function() {
    alert(my_var);
    return false;
})

All my searches to googles shows that this should work, any idea why its not working.

A: Well, seems like you just forgot to invoke report_grid()


text:
Q: Getting the index of a row in Asp.net Gridview i have used this code.and it shows an error:
Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
The error is as folows:
An exception of type 'System.InvalidCastException' occurred in FFK.DLL but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type 'System.Web.UI.WebControls.GridViewRow'.

A: I am assuming that what you want is the index of the selected row of a GridView?
If so, you can try something like:
Me.GridView1.SelectedIndex

... This will give you the zero-based index position of the row in the GridView.
Hope this helps,


text:
Q: pass query to execute to a jdbc component How can I have a jdbc channel adapter of gateway to execute a query that is passed through input message or its properties. Not sure if there a way to use query this way. So instead of below
<int-jdbc:outbound..
        query="select * from ...."
        ...

I would like to have something like
<int-jdbc:outbound...
        query="payload.sqlQuery"
        ..>

Thank you for your help.
We have a flow where the adapter need to run various queries as specified by  request so i can not put the query there.

A: No, it isn't possible by adapters. They aren't designed for such a low-level protocol linking. It breaks a bit messaging principles.
If you really need so generic behavior of the Integration endpoint, consider to use JdbcTemplate directly from some POJO and refer it to the <service-activator>.


text:
Q: VB.NET - counting days between two dates with exclusions I'm trying to count the days between two dates, excluding Saturdays and Sundays. I've written this code so far
Dim startDay As Integer
Dim endDay As Integer
Dim days As Integer
Dim count As Integer

startDay = dtpStartDate.Value.DayOfWeek
endDay = dtpEndDate.Value.DayOfWeek

For days = startDay To endDay
    If days = 0 Or days = 6 Then           'Sunday = 0, Saturday = 6
        count += 1
    End If
Next

    lblNoOfDays.Text = count

It works fine if you choose the two dates within the same week. (ex: 23rd Jan to 27th Jan, gives the result 5)
But if I set them to dates in different weeks, (ex : 23rd Jan to 30th Jan, gives the result 1), it gives incorrect results.
I know it happens because of the loop but I can't think of a way to overcome this. Can anyone give me a suggestion, solution??
Thank you

A: Dim count = 0
Dim totalDays = (dtpEndDate - dtpStartDate).Days

For i = 0 To totalDays
    Dim weekday As DayOfWeek = startDate.AddDays(i).DayOfWeek
    If weekday <> DayOfWeek.Saturday AndAlso weekday <> DayOfWeek.Sunday Then
        count += 1
    End If
Next

lblNoOfDays.Text = count

A: This function calculates the non-weekend days between two dates:
    Public Shared Function WorkingDaysElapsed(ByVal pFromDate As Date, ByVal pToDate As Date) As Integer

        Dim _elapsedDays As Integer = 0
        Dim _weekendDays As DayOfWeek() = {DayOfWeek.Saturday, DayOfWeek.Sunday}

        For i = 0 To (pToDate - pFromDate).Days
            If Not _weekendDays.Contains(pFromDate.AddDays(i).DayOfWeek) Then _elapsedDays += 1
        Next

        Return _elapsedDays

    End Function


text: Q: is there a way to create generic OIDC SSO framework using python to support all OpenID connect providers our requirement is to create a generic SSO framework for OpenID Connect (OIDC) using python. Our framework should support any OpenID provider by changing the client Id and secrets. I have tried using flask-oidc but it still needs the corresponding provider's SDK. Please suggest some framework or libraries


text:
Q: Levi-Civita connection from idempotents Let $(M,g)$ be a closed Riemannian manifold. Let $V$ be a smooth complex vector bundle over $M$. We can write $V$ as the range of an idempotent $E$ in a matrix algebra $M_n(C^\infty(M))$ acting on a trivial bundle $M\times\mathbb{C}^n$. Here $C^\infty(M)$ denotes the complex-valued functions on $M$.
Let $D$ be the trivial connection on $M\times\mathbb{C}^n$ defined by applying the de Rham differential to each entry separately. Then the expression $EDE$ defines a connection on $V$.
Some books call the connection $EDE$ the "Levi-Civita connection" on $V$, "by analogy to the classical situation", and I am trying to understand how this analogy works. In particular, when $V$ is the tangent bundle $TM$ (ignoring the fact that this is a real vector bundle), the Levi-Civita connection depends on the metric $g$, while the expression $EDE$ does not seem to depend on $g$.
Question: Is there a precise sense in which $EDE$ produces the "classical" Levi-Civita connection on $TM$?

A: $\newcommand{\R}{\mathbb{R}}$
Yes, it uniquely defines a connection in the case where $V$ is the tangent bundle(the connection won't depend on the choice of orthogonal idempotent) and its the Levi Civita connection. But in general different idempotents from the same metric will define different connections(I think, I'm not sure on this one though).
Let $ V^l \to M^k $ be the vector bundle of rank $l$ over a $k$ manifold and take an isometric embedding of the vector bundle into $\R^{2n}$ with the standard metric.   Let $s$ be a section of the vector bundle.  Let $e: M \to Mat_{n\times n}$ be the orthogonal  projection onto the tangent bundle of $M$.
If we differentiate $s$ in a given direction using the ambient $\R^{2n}$, (we can just take all the directions into account by taking the exterior derivative $ds$), then the result will not be in the vector bundle any more.  But $eds$ will be.  Hence we define the derivative of $s$ in the $v$ direction to be $\nabla_v s =e\frac{ds}{dv}$
Let us consider the case where $E$ is the tangent bundle of the manifold and $M^k \subset \R^n$.  It is possible to write down the expression $e\frac{ds}{dv}$ just using the metric on the manifold.
To show this we show that $eds$ satisfies the axioms of the Levi Civita connection:

If $X,Y,Z$ are sections of our vector bundle, then
\[ X \langle Y,Z \rangle = \langle \nabla_X Y, Z \rangle + \langle
Y, \nabla_X Z \rangle \]

Proof:
\[ \nabla_X Y-\nabla_Y X=[X,Y]  \]
If we expand the rhs,   \[ \langle \nabla_X Y, Z \rangle + \langle Y, \nabla_X Z \rangle = \langle e \frac{dY}{dX},  Z \rangle + \langle Y , e \frac{dZ}{dX} \rangle = \]
\[\langle  \frac{dY}{dX}, e^T Z \rangle + \langle e^TY ,  \frac{dZ}{dX} \rangle \]
Now $e^T=e$ because $e$ is an orthogonal projection.  So this is
\[=\langle  \frac{dY}{dX}, eZ \rangle + \langle eY ,  \frac{dZ}{dX} \rangle=\langle  \frac{dY}{dX}, Z \rangle + \langle Y ,  \frac{dZ}{dX} \rangle=X \langle Y,Z \rangle \]
\[ \nabla_X Y-\nabla_Y X= e \frac{dY}{dX} -e \frac{dX}{dY}=e[X,Y]=[X,Y] \]
Exercise:
Using the above identities, and cyclically permuting $X,Y,Z$ write down an expression for $\nabla_X Y$ in terms of the inner product.
Using the above expression, write down a matrix $A$ of 1-forms in terms of the inner product such that
\[\nabla s=ds-As \]
If you do this exercise, the matrix $A$ you get will be the matrix of christoffel symbols.
Another good exercise is to write out what $A$ is in terms of the idempotent.  (You should get $(1-e)de$)
Note that you can't cyclically permute the indices $X,Y,Z$ for an arbitrary vector bundle.  I don't think that you get a canonical connection on a vector bundle just given the metric(I think this was one of your questions), and at the very least, the trick above doesn't work.
Aside:  I came up with this answer after reading through the comment above about it being in Dirac's General relativity book.  I've been trying for the past few months and I can't quite tell what he is doing.  I did see though that his argument factors through proving that the axioms of the Levi Civita connection are satisfied without saying that that is what he's doing.


text:
Q: About exclamatives with interrogative form
Did I do something stupid last night!

I suppose it can be expressed by: What a stupid thing I did last night!

Wow! Can she sing!

It means that She is really good at singing.

Look at those ones!  Aren't they amazing!

In this case, I feel confused. It means they are so amazing but why a negative form? Can I say "Are they amazing!"?

A: "Aren't they amazing!" (or "Are they not amazing!")
are rhetorical questions, whose meaning could be expanded like this:
"I think they are amazing! Do you disagree?"
A rhetorical question isn't expecting an answer, but expressing an opinion.
American Heritage Dictionary "rhetorical question"
n. A question to which no answer is expected, often used for rhetorical effect.
The sentence is a question grammatically, but it can be ended with an exclamation point to express the intensity of the expression.


text:
Q: Equivalent for the Russian idiom "to write into the drawer" There is following idiom in Russian "to write into the drawer" which is being used to describe situation when writer or scientist writes (sometimes prolifically) without publishing anything. Are there direct equivalent or some other idiom/expression which conveys the same idea in English?

A: There is a phrase on the shelf which means

in a state of inactivity or uselessness

The verb form, shelve is also used

Decide not to proceed with (a project or plan), either temporarily or permanently

The phrase back burner is also used

A state of inaction or suspension; a position of relatively little importance:
  priorities that have been placed on the back burner year after year

All of these terms can be used for a range of projects in addition to writing.

A: Considering that you are saying there is no waste in the eyes of the writer, maybe x for its own sake or x for himself could fit?

He spent years working for that damned company, but his true ambition had always been writing for himself.
After writing fiction for its own sake for years, Nikolai considered publishing it as his memoirs, but eventually decided against it.

I'm at a loss for better suggestions.

A: The expression about which the OP inquires is the now largely historical term that is usually translated into English from the Russian писать в стол or писать в ящик ( http://phraseology_ru_en.academic.ru/27881/писать_в_стол ) as to write for the drawer, the significance of which is well described in an Economist article dating from 11 November 1969. One of the principal themes of the article is the central importance for writers in the USSR of enjoying the goodwill of the Writers' Union:

Prominent writers are a privileged section of Soviet society. Men like Boris Pasternak can survive a period of disgrace by living on their savings. Young men can take a job outside literature and go on writing in their spare time. Those who refuse to conform can write for the "drawer"—for posterity—or, in the case of the younger rebels, for underground publication. They can all show their work to their friends.

Along similar lines, this 2002 article from the Los Angeles Times describes the tragic life of the Hungarian writer Sandor Marai, from which I quote:

Marai survived the Nazis and their World War II collaborators, and even published some works during those years. The Communists who solidified power in 1948, though, proved to be more difficult. Writers were expected to publish works of socialist realism, ennobling both the worker and the revolutionary while denouncing the bourgeois values that framed Marai's life and his art.
Marai sought to remain silent, "to write for the drawer." But the Communists, he wrote, "would not let me be silent freely."

A: No, there is no idiom that describes the process of prolific and futile writing in English. While there are many idioms for wasting time (flushing it down the drain), or egotistical behavior (getting high on your own supply), or excessive self-focus (navel-gazing), none captures the exact spirit.

A: This idiom also exists in Hebrew, probably migrated from Russian.
The best translation IMHO is "Closet writer", that was suggested by P.O. in one of the first comments above.


text:
Q: could not resolve hostname with ~/.ssh/config and aliases I have a config file ~/.ssh/config that looks something like this:
Host *.texas
  User john

Host *.texas !gateway.texas
  HostName %h.unitedstates.com
  ProxyJump gateway.texas

Host gateway.texas
  HostName ssh.texas.unitedstates.com

Host dallas austin
  HostName %h.texas
  RemoteCommand zsh -l

In summary, I expect that ssh dallas resolves to something like ssh -J ssh.texas.unitedstates.com john@dallas.texas.unitedstates.com zsh -l while ssh houston.texas resolves to ssh -J john@ssh.texas.unitedstates.com john@houston.texas.unitedstates.com. The second example works as expected but not the first one (unresolved hostname). I suspect that it has something to do with the %h.texas which should in turn be resolved as %h.unitedstates.com
Could anyone help?
Thanks!

A: As mentioned in the comments, by default recursive hostname resolution is not possible, but several options can help, including Match and CanonicalDomains/CanonicalHostName. In the end, I turned the problem around with something like this:
CanonicalDomains texas.unitedstates.com
CanonicalizeFallbackLocal no
CanonicalizeHostname yes

Host *.texas.unitedstates.com
  User john
  IdentityFile ~/.ssh/texas

Host *.texas.unitedstates.com !ssh.texas.unitedstates.com
  HostName %h
  ProxyJump ssh.texas.unitedstates.com

Host dallas austin
  HostName %h.texas.unitedstates.com
  RequestTTY yes
  RemoteCommand tmux new -As remote

More information on Canonicalization and on Match.


text:
Q: How to disable the MacBook trackpad click but keep the tap enabled? I have a 3-year-old Mac and either the battery or something else is broken (does not matter because it's not worth fixing) and due to this the trackpad keeps getting stuck.
Now my question is: can I disable the MacBook trackpad click function but keep tap enabled? This is so that I can still use the mac even though the trackpad is stuck.

A: Unfortunately, there is no way to do that using vanilla Mac OS X. The trackpad allows to use tap function with click. It doesn't allow to use the tap exclusively.
However, there may be third-party software/kexts that allow to do that.


text:
Q: AWS ALB + ECS + gRPC + NestJS, '14 UNAVAILABLE: Trying to connect an http1.x server' Here is the thing:
We have NestJS microservices talking through gRPC. We deploy it to AWS ECS on Fargate.
In the current (working) configuration we're using one instance per service and a CloudMap for service discovery.
Now we want to have multiple instances per service. We've tried to configure the ALB.
In the target group, we see targets in a "Healthy" state.
But when we try to call services through the Load Balancer we receive '14 UNAVAILABLE: Trying to connect an http1.x server'
Any ideas?
Here is the part of our CDK code that is responsible for creating the load balancer:
export class ServicePrivateStack extends ServiceFargateStack<PrivateServiceStackProps> {
  constructor(scope: Construct, id: string, props: PrivateServiceStackProps) {
    super(scope, id, props);

    const { discoveryStack, vpc, securityGroup, certificateArn } = props;
    const { stagedName, service } = this;

    // create target group
    const grpcTG = new elbv2.ApplicationTargetGroup(this, 'TG_GRPC', {
      vpc,
      port: 50051,
      targetGroupName: this.makeTGName('GRPC'),
      deregistrationDelay: Duration.seconds(10),
      targetType: elbv2.TargetType.IP,
      protocol: elbv2.ApplicationProtocol.HTTPS,
      protocolVersion: elbv2.ApplicationProtocolVersion.GRPC,
      healthCheck: {
        enabled: true,
        protocol: Protocol.HTTPS,
        port: '50051',
        path: '/grpc.health.v1.Health/Check',    // <— custom, it works
        healthyGrpcCodes: '1',
      },
    });
    grpcTG.addTarget(service);

    // create ALB
    const grpcLB = new elbv2.ApplicationLoadBalancer(this, 'LB_GRPC', {
      vpc,
      securityGroup,
      internetFacing: false,
      http2Enabled: true,
      loadBalancerName: `${stagedName}-LB`,
    });

    // attach grpc listener
    grpcLB.addListener('Listener_GRPC', {
      port: 50051,
      open: true,
      certificates: [{ certificateArn }],
      protocol: elbv2.ApplicationProtocol.HTTPS,
      defaultTargetGroups: [grpcTG],
    });

    // register in cloudmap
    discoveryStack.registerLoadBalancer(NameUtils.serviceDiscoveryName(id), grpcLB);
  }
  // <…>
}

A: You need to set the protocol version to use gRPC explicitly as mentioned in the @aws-cdk/aws-elasticloadbalancingv2 module documentation:
const tg = new elbv2.ApplicationTargetGroup(stack, 'TG', {
  targetType: elbv2.TargetType.IP,
  port: 50051,
  protocol: elbv2.ApplicationProtocol.HTTP,
  protocolVersion: elbv2.ApplicationProtocolVersion.GRPC,
  healthCheck: {
    enabled: true,
    healthyGrpcCodes: '0-99',
  },
  vpc,
});


text:
Q: Galois Group of Ordered Field containing Square Roots Given a ordered field $K$ such that every positive element $0<x$ has a root in $K$ we can show that any endomorphism $f:K\rightarrow K$ preserves the ordering of $K$ and turns out to be $\text{id}_K$. It follows that $\text{Gal}(K/\mathbb{Q})=\{\text{id}_K\}$.
So now I want to find some examples of such $K$, we of course have $K=\mathbb{R}$. Another example I have found is $K=\mathbb{A}\cap\mathbb{R}$ where $\mathbb{A}\subset\mathbb{C}$ is the algebraic closure of $\mathbb{Q}$. Do you know any other examples (or families of such examples for that matter)?
Regards

A: A large class of reasonably well-studied examples is given by the real closed fields, which can be defined as the ordered fields such that every positive element has a square root and such that every polynomial of odd degree has a root. The Wikipedia article gives several examples, such as the nonstandard reals.
By the way, I would not personally refer to the automorphism group of a non-Galois extension as a Galois group; such extensions e.g. don't have a Galois correspondence. They're just automorphism groups.


text:
Q: C++ ( function, cosine) not giving the correct answer I just started taking this C++ course like a month ago.
Now I'm assigned to write a program to calculate this. I don't know what I did wrong.
#include <stdio.h>
#include <math.h>

float gatherl1();
float gatherl2();
float gatheran();
void values(float,float,float);
float findlength(float,float,float);
float findan2(float,float,float);
float findan3(float,float,float);
void name(float,float,float);

int main(void)
{
    float length1,length2;

    float length3;

    float angle1,angle2,angle3;

    length1 = gatherl1();
    length2 = gatherl2();
    angle1 = gatheran();

    values(length1,length2,angle1);

    length3 = findlength(length1,length2,angle1);

    angle2 = findan2(length1,length2,length3);
    angle3 = findan3(length1,length2,length3);

    name(angle1,angle2,angle3);
}

float gatherl1()
{
        float l1;

        printf("Enter the length of one of the sides of any triangle\n");

        scanf("%f",&l1);

        return l1;
}

float gatherl2()
{
        float l2;

        printf("Enter the length of the other side\n");

        scanf("%f",&l2);

        return l2;
}

float gatheran()
{
        float angle;

        printf("Enter the angle between them.\n");

        scanf("%f",&angle);

        return angle;
}

void values(float l1, float l2, float angle)
{
    printf("\n The two sides are %f and %f. The angle between them is %f \n",l1,l2,angle);
}
float findlength(float l1, float l2, float angle)
{
    float l3,pyt,boy;

    if (angle==90)
    {
        pyt = pow(l1,2) + pow(l2,2);
        l3 = sqrt(pyt);

    }
    else
    {
        boy = pow(l1,2) + pow(l2,2) - 2*l1*l2*cos(angle);
        l3 = sqrt(boy);
    }

    printf("\nthe third side is = %f",l3);
    return l3;
}

float findan2(float l1, float l2, float l3)
{
    float cosangle2,angle2;

    cosangle2 = (pow(l2,2) + pow(l3,2) - pow(l1,2)) / (2*l2*l3);
    angle2 = acos(cosangle2);
    return angle2;

}
float findan3(float l1, float l2, float l3)
{
    float cosangle3,angle3;

    cosangle3 = (pow(l1,2) + pow(l3,2) - pow(l2,2)) / (2*l1*l3);
    angle3 = acos(cosangle3);
    return angle3;

}

void name(angle,angle2,angle3)
{
    printf("\n\n\n the other two angles are %f and %f",angle2,angle3);

    printf("\n\n\n The angle you put is %f",angle);

    if(angle == 90)
    {
        printf("\n The triangle is a right triangle\n");
    }
    else if(angle < 90)
    {
        printf("\n The triangle is a acute triangle\n");
    }
    else
    {
        printf("\n The triangle is a obtuse triangle\n");
    }

}

I have never use cos and arccos function before so I'm not sure if that's the cause.
or the function because I'm new to function too. Please Help Me!! thank you.

A: Are the values that you pass to your functions in terms of radians? Because cos and arccos assume radians as an input.

A: The C trigonometry functions operate in radians, not degrees. You have to multiply by pi/180 to convert degrees to radians.


text:
Q: Why after git rebase should do : git add? Why after git rebase should do : "git add changedfile"?
More explanation for my Question:

*

*add command taking file to staging not commit him

*What git rebase --continue doing?
Thanks

A: If Git is telling you to type git rebase --continue, it's because the rebase isn't finishing. It sounds like you're stopping mid-rebase because of one or more conflicted files.
When you are in a conflicted state, you can type git status and look for "Unmerged paths" and files marked as "both modified":
# Unmerged paths:
#   (use "git add/rm ..." as appropriate to mark resolution)
#
#   both modified:      README

Git is asking you to manually resolve the conflicted file, remove the change markers, and then git add <file> to mark the conflict resolved. This moves the changes into the staging area, telling Git to include them in the rebased commit which it will generate when the rebase continues.
Once you've done this, you can continue rebasing with git rebase --continue.


text:
Q: Difference between exit(0) and exit(1) in Python What's the difference between exit(0) and exit(1) in Python?
I tried looking around but didn't find a specific question on these lines. If it's already been answered, a link would be sufficient.

A: The number you pass to the exit() function is simply your program's return code, which is given to the operating system. From your program's point of view, there is no difference: execution will end in both cases, and the value supplied to the function will be given to the OS. But some tools and scripts take into account the program's exit code. Most tools return 0 when they succeed and nonzero to indicate an error.
So, if your program will be run from a script, an automated tool or from some other software that takes into account the return code (such as an IDE), you must be careful on what you return.
When in doubt, just return 0 to indicate everything is OK.

A: 0 and 1 are the exit codes.
exit(0) means a clean exit without any errors / problems
exit(1) means there was some issue / error / problem and that is why the program is exiting.
This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was. A zero error code means a successful exit.
This is useful for other programs, shell, caller etc. to know what happened with your program and proceed accordingly.

A: This determines the exit status of the program when it finishes running (generally, 0 for success and 1 for error).
It is not unique to Python, and the exact effect depends on your operating system and how the program is called (though 99% of the time, if you're just running Python scripts, it doesn't matter).

A: The standard convention for all C programs, including Python, is for exit(0) to indicate success, and exit(1) or any other non-zero value (in the range 1..255) to indicate failure.  Any value outside the range 0..255 is treated modulo 256 (the exit status is stored in an 8-bit value).  Sometimes, that will be treated as signed (so you might see -128, -127, etc) but more usually it is treated as unsigned.
This status is available to the code that invoked Python.  This convention applies across platforms, though the meaning of non-zero exit status can vary on different platforms.

A: exit(0): This causes the program to exit with a successful termination.
exit(1): This causes the program to exit with a system-specific meaning.
On many systems, exit(1) signals some sort of failure, however there
is no guarantee.
As I recall, the C standard only recognizes three standard exit
values:

*

*EXIT_SUCCESS -- successful termination

*EXIT_FAILURE -- unsuccessful termination

*0 -- same as EXIT_SUCCESS


text:
Q: How to spy with sinon on callback calls triggered by EventEmitter events? Javascript, ES6, Unit-tests, Chai I need to test whether my callback was called n number of times and always returned true.
Here is my test callback function in typescript:
const checkBlockTransaction = (block: ILogsBlock) => {
  const tx = transactions.find(element => element.block === block.blockNumber);
  try {
    assert.strictEqual(block.transactions[0].amount, tx.amount);
  } catch (e) {
    return false;
  }
  return true;
};

here is my test which currently fails, because the spy doesn't register any function calls
describe('Erc20DepositsWatcher', () => {
  it('handles blocks correctly', async () => {
    const spy = sinon.spy(checkBlockTransaction);
    for (const tx of transactions) {
      await deployedContract.methods.transfer(tx.address, tx.amount)
      .send({ from: addresses[0] });
    }

    depositsWatcher.subscribe(checkBlockTransaction);
    await depositsWatcher.startBroadcasting();
    await depositsWatcher.handleNewBlock(await web3.eth.getBlock('latest'));
    assert.equal(spy.callCount, 7);
    //sinon.assert.callCount(spy, 7);
    //assert(spy.alwaysReturned(true));
  });
});

maybe there is a better solution than spying with sinon but I didn't find it yet

A: My current solution is without spies, but it's not very nice looking:
function checkCallbackCalled(done: any, callsNumber: number) {
  let counter = 0;
  return (block: ILogsBlock) => {
    const tx = transactions.find(element => element.block === block.blockNumber);
    try {
      assert.strictEqual(block.transactions[0].amount, tx.amount);
    } catch (e) {
      done(e);
    }
    counter += 1;
    if (counter === callsNumber) done();
  };
}

describe('Erc20DepositsWatcher', () => {
  it('handles blocks correctly', async (done) => {
    for (const tx of transactions) {
      await deployedContract.methods.transfer(tx.address, tx.amount)
      .send({ from: addresses[0] });
    }

    depositsWatcher.subscribe(checkCallbackCalled(done, 7));
    await depositsWatcher.startBroadcasting();
    await depositsWatcher.handleNewBlock(await web3.eth.getBlock('latest'));
  });
});


text:
Q: Trying to move cube when arrow pressed and swap 2 cubes I want to move a cube with an arrow key right and left in 2D mode of Unity.
I want to swap positions of cube with colliders attached but the code doesn't seem to work at all.
public float Jump = 0.6f;
Vector3 positionP, positionS, position, pos;
public GameObject Swapable;
public GameObject Player;

void Start ()
{
        positionS = Swapable.transform.position;
        positionP = Player.transform.position;
}

// Update is called once per frame
void Update ()
{

        if (Input.GetKey (KeyCode.RightArrow)) {
                transform.position = Vector2.right * Jump;
        }
        if (Input.GetKey (KeyCode.LeftArrow)) {
                transform.position = -Vector2.right * Jump;
        }
}

void OnTriggerEnter2D (Collider2D col)
{
        if (col.Equals ("Red")) {
                Debug.Log ("Touched");
                position = positionS;
                pos = positionP;
                Player.transform.position = position;
                Swapable.transform.position = pos;

        }
}

What am I doing wrong?

A: Your cubes are only moving to (0.6,0), NOT translating.
In your update method you call:
transform.position = Vector2.right * Jump;

Vector2.right ALWAYS returns (1,0). Jump is ALWAYS 0.6
So you're always setting your position to (0.6,0) whereas you need to increment it.
transform.position = transform.position + Vector2.right * Jump

Try this change and see if your cubes at least move now. From there we can try to fix any collision errors.
EDIT:
Ok, this will handle swapping for you. You'll want a master game object with this script managing the whole grid. When you want to swap positions, call the Swap function.
public class TilePositions
{
    //The objects in your grid
    public Transform[,] objects;

    //Offset from (0,0) that your grid's top-left is at.
    public Vector3 offset;

    //Scale of your grid
    public Vector2 scale;

    //Swap the objects at position one and position two in the grid
    public void Swap(Point one, Point two)
    {
        var temp = objects[one.x,one.y];

        objects[one.x,one.y] = objects[two.x,two.y];
        objects[two.x,two.y] = temp;

        objects[one.x,one.y].Position = new Vector3(one.x,one.y,0) * scale + offset;
        objects[two.x,two.y].Position = new Vector3(two.x,two.y,0) * scale + offset;
    }

    /// <summary>
    /// Converts a transform's vector3 position to a Point struct
    /// </summary>
    /// <param name="obj">The transform whose position is to be converted</param>
    /// <returns>System.Drawing.Point for the grid's position</returns>
    private Point PositionToPoint(Transform obj)
    {
        var position = (obj.Position - offset) / scale;
        return new Point((int)position.x, (int)position.y);
    }
}