text:
Q: difference in the values for AVG windowing function between teradata and postgres There is a difference in AVG values when applied as windowing function in Teradata and Postgresql. Please find the code below
create table tab1
(pop integer,
act  varchar(100),
rate numeric(38,15),
year_month date,
a_obs  integer,
cat1 varchar(1000)
);

insert into tab1 values(19150551,'SAMPLE',0.002047878413524,'2017-09-01 00:00:00',39218,'CONSUMERDecrease');
insert into tab1 values(19092796,'SAMPLE',0.014806317524159,'2017-09-01 00:00:00',282694,'CONSUMERIncrease');
insert into tab1 values(1611642,'SAMPLE',0.001293091145552,'2017-09-01 00:00:00',2084,'OPENDecrease');
insert into tab1 values(1626776,'SAMPLE',0.010981843843283,'2017-09-01 00:00:00',17865,'OPENIncrease');
insert into tab1 values(19257622,'SAMPLE',0.002375007672287,'2017-10-01 00:00:00',45737,'CONSUMERDecrease');
insert into tab1 values(19263407,'SAMPLE',0.011992842179994,'2017-10-01 00:00:00',231023,'CONSUMERIncrease');
insert into tab1 values(1623765,'SAMPLE',0.001870344538773,'2017-10-01 00:00:00',3037,'OPENDecrease');
insert into tab1 values(1633775,'SAMPLE',0.008691527291090,'2017-10-01 00:00:00',14200,'OPENIncrease');
insert into tab1 values(19291826,'SAMPLE',0.002548384999948,'2017-11-01 00:00:00',49163,'CONSUMERDecrease');
insert into tab1 values(19364688,'SAMPLE',0.018412586869461,'2017-11-01 00:00:00',356554,'CONSUMERIncrease');
insert into tab1 values(1626310,'SAMPLE',0.001650976751050,'2017-11-01 00:00:00',2685,'OPENDecrease');
insert into tab1 values(1643574,'SAMPLE',0.010273343335925,'2017-11-01 00:00:00',16885,'OPENIncrease');
insert into tab1 values(19521183,'SAMPLE',0.002472135013539,'2017-12-01 00:00:00',48259,'CONSUMERDecrease');
insert into tab1 values(19607991,'SAMPLE',0.017408718720852,'2017-12-01 00:00:00',341350,'CONSUMERIncrease');
insert into tab1 values(1631794,'SAMPLE',0.001417458331137,'2017-12-01 00:00:00',2313,'OPENDecrease');
insert into tab1 values(1654019,'SAMPLE',0.009217548286930,'2017-12-01 00:00:00',15246,'OPENIncrease');
insert into tab1 values(19649539,'SAMPLE',0.002312878688910,'2018-01-01 00:00:00',45447,'CONSUMERDecrease');
insert into tab1 values(19735372,'SAMPLE',0.014637930311119,'2018-01-01 00:00:00',288885,'CONSUMERIncrease');
insert into tab1 values(1629580,'SAMPLE',0.001304016985972,'2018-01-01 00:00:00',2125,'OPENDecrease');
insert into tab1 values(1657584,'SAMPLE',0.008844197337812,'2018-01-01 00:00:00',14660,'OPENIncrease');
insert into tab1 values(19697940,'SAMPLE',0.002322831727582,'2018-02-01 00:00:00',45755,'CONSUMERDecrease');
insert into tab1 values(19758091,'SAMPLE',0.014947243638062,'2018-02-01 00:00:00',295329,'CONSUMERIncrease');
insert into tab1 values(1636323,'SAMPLE',0.001345088958598,'2018-02-01 00:00:00',2201,'OPENDecrease');
insert into tab1 values(1652098,'SAMPLE',0.008980702113313,'2018-02-01 00:00:00',14837,'OPENIncrease');
insert into tab1 values(20303042,'SAMPLE',0.002804899876580,'2018-03-01 00:00:00',56948,'CONSUMERDecrease');
insert into tab1 values(20285060,'SAMPLE',0.013430327541550,'2018-03-01 00:00:00',272435,'CONSUMERIncrease');
insert into tab1 values(1647063,'SAMPLE',0.001465031999383,'2018-03-01 00:00:00',2413,'OPENDecrease');
insert into tab1 values(1661797,'SAMPLE',0.008485392620158,'2018-03-01 00:00:00',14101,'OPENIncrease');
insert into tab1 values(20430539,'SAMPLE',0.002837663754246,'2018-04-01 00:00:00',57975,'CONSUMERDecrease');
insert into tab1 values(20437053,'SAMPLE',0.013785451356416,'2018-04-01 00:00:00',281734,'CONSUMERIncrease');
insert into tab1 values(1659544,'SAMPLE',0.001523310017692,'2018-04-01 00:00:00',2528,'OPENDecrease');
insert into tab1 values(1675019,'SAMPLE',0.007977819953087,'2018-04-01 00:00:00',13363,'OPENIncrease');
insert into tab1 values(20646020,'SAMPLE',0.002641380760069,'2018-05-01 00:00:00',54534,'CONSUMERDecrease');
insert into tab1 values(20601704,'SAMPLE',0.015858202797206,'2018-05-01 00:00:00',326706,'CONSUMERIncrease');
insert into tab1 values(1660905,'SAMPLE',0.001308322872169,'2018-05-01 00:00:00',2173,'OPENDecrease');
insert into tab1 values(1684229,'SAMPLE',0.010146482455771,'2018-05-01 00:00:00',17089,'OPENIncrease');
insert into tab1 values(20790580,'SAMPLE',0.002539130702462,'2018-06-01 00:00:00',52790,'CONSUMERDecrease');
insert into tab1 values(20733151,'SAMPLE',0.011445679433869,'2018-06-01 00:00:00',237305,'CONSUMERIncrease');
insert into tab1 values(1683987,'SAMPLE',0.001293359153010,'2018-06-01 00:00:00',2178,'OPENDecrease');
insert into tab1 values(1690818,'SAMPLE',0.007794452152745,'2018-06-01 00:00:00',13179,'OPENIncrease');
insert into tab1 values(20920348,'SAMPLE',0.002633034593880,'2018-07-01 00:00:00',55084,'CONSUMERDecrease');
insert into tab1 values(20821752,'SAMPLE',0.013583487114821,'2018-07-01 00:00:00',282832,'CONSUMERIncrease');
insert into tab1 values(1684491,'SAMPLE',0.001687156535713,'2018-07-01 00:00:00',2842,'OPENDecrease');
insert into tab1 values(1695645,'SAMPLE',0.013209722553954,'2018-07-01 00:00:00',22399,'OPENIncrease');
insert into tab1 values(20962139,'SAMPLE',0.002833489464028,'2018-08-01 00:00:00',59396,'CONSUMERDecrease');
insert into tab1 values(20974476,'SAMPLE',0.013324862084755,'2018-08-01 00:00:00',279482,'CONSUMERIncrease');
insert into tab1 values(1687619,'SAMPLE',0.001673363478368,'2018-08-01 00:00:00',2824,'OPENDecrease');
insert into tab1 values(1705427,'SAMPLE',0.023551872932702,'2018-08-01 00:00:00',40166,'OPENIncrease');
insert into tab1 values(21186671,'SAMPLE',0.003380616048647,'2018-09-01 00:00:00',71624,'CONSUMERDecrease');
insert into tab1 values(21118710,'SAMPLE',0.011539672640990,'2018-09-01 00:00:00',243703,'CONSUMERIncrease');
insert into tab1 values(1697221,'SAMPLE',0.001652701681160,'2018-09-01 00:00:00',2805,'OPENDecrease');
insert into tab1 values(1716502,'SAMPLE',0.010922212732639,'2018-09-01 00:00:00',18748,'OPENIncrease');
insert into tab1 values(21192289,'SAMPLE',0.003490703623379,'2018-10-01 00:00:00',73976,'CONSUMERDecrease');
insert into tab1 values(21247435,'SAMPLE',0.012780225001277,'2018-10-01 00:00:00',271547,'CONSUMERIncrease');
insert into tab1 values(1713316,'SAMPLE',0.001665775607068,'2018-10-01 00:00:00',2854,'OPENDecrease');
insert into tab1 values(1731032,'SAMPLE',0.008466625689184,'2018-10-01 00:00:00',14656,'OPENIncrease');
insert into tab1 values(21418469,'SAMPLE',0.003610855659198,'2018-11-01 00:00:00',77339,'CONSUMERDecrease');
insert into tab1 values(21341613,'SAMPLE',0.014239551621520,'2018-11-01 00:00:00',303895,'CONSUMERIncrease');
insert into tab1 values(1728070,'SAMPLE',0.001842517953555,'2018-11-01 00:00:00',3184,'OPENDecrease');
insert into tab1 values(1740742,'SAMPLE',0.008774419184463,'2018-11-01 00:00:00',15274,'OPENIncrease');
insert into tab1 values(21357655,'SAMPLE',0.003238230039768,'2018-12-01 00:00:00',69161,'CONSUMERDecrease');
insert into tab1 values(21405448,'SAMPLE',0.013063076278525,'2018-12-01 00:00:00',279621,'CONSUMERIncrease');
insert into tab1 values(1766407,'SAMPLE',0.003247835861158,'2018-12-01 00:00:00',5737,'OPENDecrease');
insert into tab1 values(1774356,'SAMPLE',0.009075968971277,'2018-12-01 00:00:00',16104,'OPENIncrease');
insert into tab1 values(21480474,'SAMPLE',0.003105937047758,'2019-01-01 00:00:00',66717,'CONSUMERDecrease');
insert into tab1 values(21503589,'SAMPLE',0.011378472681932,'2019-01-01 00:00:00',244678,'CONSUMERIncrease');
insert into tab1 values(1785520,'SAMPLE',0.003119539405887,'2019-01-01 00:00:00',5570,'OPENDecrease');
insert into tab1 values(1791290,'SAMPLE',0.008353756231543,'2019-01-01 00:00:00',14964,'OPENIncrease');
insert into tab1 values(21540829,'SAMPLE',0.003581477760211,'2019-02-01 00:00:00',77148,'CONSUMERDecrease');
insert into tab1 values(21591541,'SAMPLE',0.010447934216460,'2019-02-01 00:00:00',225587,'CONSUMERIncrease');
insert into tab1 values(1797190,'SAMPLE',0.002124427578609,'2019-02-01 00:00:00',3818,'OPENDecrease');
insert into tab1 values(1807594,'SAMPLE',0.007535431075784,'2019-02-01 00:00:00',13621,'OPENIncrease');

select rate,AVG(rate) OVER (PARTITION BY category ORDER BY year_month) avg,category
from tab1;

When the same data is available in postgres then the avg value is not matching with teradata. I need the values to be matched in Postgres

A: There are two potential problems.
Teradata doesn't follow Standard SQL in this case, which requires the ORDER BY to default to RANGE UNBOUNDED PRECEDING (which is not supported in TD). You need to add an explicit ROWS UNBOUNDED PECEDING (as long as there are no duplicates in year_month, otherwise you're in trouble).
Teradata (as many DBMSes) returns the result of an AVG as FLOAT, which has a precision of 15 digits. So not matching probably means that PG returns a higher precision. In that case you need to calculate the average manually, i.e. sum/count:
Sum(Cast(rate AS number))
Over (PARTITION BY category
      ORDER BY year_month
      ROWS Unbounded Preceding)
/
Row_Number()
Over (PARTITION BY category
      ORDER BY year_month)

number and decimal/numeric all got 38 digits of precision, but for a number you don't have to specify the exact precision, thus this is the closest possible match to the PG result. Of course you could cast the result to a fixed precison, e.g. cast(... as decimal(38,20)).


text:
Q: Sveltekit, Depencencies working in dev but not loading directly in the routed page after build In a sveltekit project where everything works in dev,  some dependencies seems not to be working when build at routed pages.
In specific charts.js is working in dev well, but is not working in a routed page /page when the it is build for production.
It is hard to debug as there is no error messages, but there are significantly less GET request when going to /page and if I go to the main page and then use a <a/> link to the route, everything works fine.
What could be the reason behind this? Am I missing some configuration? Probably the route is not expected to be fetched directly?
pd: I'm using svelte-chartjs library.
the component looks like this:
<script lang="ts">
  import { Doughnut } from 'svelte-chartjs';
  export datax = 10
  export datay = 20

  import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    ArcElement,
    CategoryScale,
  } from 'chart.js'

  let chart: Doughnut;
  let data = {
      labels: ['Pension', 'Monthly paid out salary', 'Tax Under', 'Tax Over'],
    datasets: [
      {
      label: 'Danish Kronws',
      data: [datax , datay],
      backgroundColor: [
        'rgba(255, 134,159,0.4)',
        'rgba(98,  182, 239,0.4)',
      ],
      borderWidth: 2,
      borderColor: [
        'rgba(255, 134, 159, 1)',
        'rgba(98,  182, 239, 1)',
      ],
      },
    ],
  };

  ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale);

  $: {if (chart) {
      chart.data.datasets[0].data = [datax ,datay]
    }
  }

</script>

<div class="chart">
  <Doughnut bind:chart data={data} options={options} />

</div>

<style>
  .chart{
    border-radius: 10px;
    box-shadow:0 0 15px 4px rgba(0,0,0,0.06);
    padding: 10px;
    width: 600px;
  }

</style>

A: When navigation to the page works but direct access does not, that is a sign that there are issues with server-side rendering. The first access to a page is rendered on the server by default which can cause issues.
E.g. your page code has to avoid accessing any browser APIs outside of onMount as those will not be available on the server. Check the console of the server process and the console in the browser for errors.
You can also turn off SSR by adding an export to +page.js/ts.
export const ssr = false;

I would only recommend this for finding out whether SSR is the problem. Turning it off permanently should only be done in rare occasions when absolutely necessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: can't pickle PyCapsule objects when using tf.transform and Apache Beam I am new to Apache Beam and am trying to run the following code:
import math
import os
import pprint
import time
import pathlib
import tempfile

import tensorflow as tf
import apache_beam as beam

import tensorflow_transform as tft
import tensorflow_transform.beam as tft_beam

from tfx_bsl.public import tfxio
from tfx_bsl.coders.example_coder import RecordBatchToExamples

from apache_beam.io.gcp.gcsio import GcsIO
from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions

from sklearn.preprocessing import scale

train = 'gs://path/to/adult.data'
test = 'gs://path/to/adult.test'

CATEGORICAL_FEATURE_KEYS = [
    'workclass',
    'education',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'native-country',
]
NUMERIC_FEATURE_KEYS = [
    'age',
    'capital-gain',
    'capital-loss',
    'hours-per-week',
]
OPTIONAL_NUMERIC_FEATURE_KEYS = [
    'education-num',
]
ORDERED_CSV_COLUMNS = [
    'age', 'workclass', 'fnlwgt', 'education', 'education-num',
    'marital-status', 'occupation', 'relationship', 'race', 'sex',
    'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'label'
]
LABEL_KEY = 'label'

RAW_DATA_FEATURE_SPEC = dict(
    [(name, tf.io.FixedLenFeature([], tf.string))
     for name in CATEGORICAL_FEATURE_KEYS] +
    [(name, tf.io.FixedLenFeature([], tf.float32))
     for name in NUMERIC_FEATURE_KEYS] +
    [(name, tf.io.VarLenFeature(tf.float32))
     for name in OPTIONAL_NUMERIC_FEATURE_KEYS] +
    [(LABEL_KEY, tf.io.FixedLenFeature([], tf.string))]
)

SCHEMA = tft.tf_metadata.dataset_metadata.DatasetMetadata(
    tft.tf_metadata.schema_utils.schema_from_feature_spec(RAW_DATA_FEATURE_SPEC)).schema

testing = False
NUM_OOV_BUCKETS = 1
if testing:
  TRAIN_NUM_EPOCHS = 1
  NUM_TRAIN_INSTANCES = 1
  TRAIN_BATCH_SIZE = 1
  NUM_TEST_INSTANCES = 1
else:
  TRAIN_NUM_EPOCHS = 16
  NUM_TRAIN_INSTANCES = 32561
  TRAIN_BATCH_SIZE = 128
  NUM_TEST_INSTANCES = 16281

# Names of temp files
TRANSFORMED_TRAIN_DATA_FILEBASE = 'train_transformed'
TRANSFORMED_TEST_DATA_FILEBASE = 'test_transformed'
EXPORTED_MODEL_DIR = 'exported_model_dir'

def preprocessing_fn(inputs):
  """Preprocess input columns into transformed columns."""
  outputs = inputs.copy()

  def sk_scale_to_z_score(X):
    scaled = scale(X)
    return scaled

  def tf_scale_to_z_score(X):
    X_shape = X.shape
    [X_scaled, ] = tf.py_function(sk_scale_to_z_score, [X], [tf.float32])
    X_scaled.set_shape(X_shape)
    return X_scaled

  # Scale numeric columns to have range [0, 1].
  for key in NUMERIC_FEATURE_KEYS:
    outputs[key] = tf_scale_to_z_score(inputs[key]) # tft.scale_to_0_1(inputs[key])

  for key in OPTIONAL_NUMERIC_FEATURE_KEYS:
    sparse = tf.sparse.SparseTensor(inputs[key].indices, inputs[key].values,
                                    [inputs[key].dense_shape[0], 1])
    dense = tf.sparse.to_dense(sp_input=sparse, default_value=0.)
    # Reshaping from a batch of vectors of size 1 to a batch to scalars.
    dense = tf.squeeze(dense, axis=1)
    outputs[key] = tft.scale_to_0_1(dense)

  for key in CATEGORICAL_FEATURE_KEYS:
    outputs[key] = tft.compute_and_apply_vocabulary(
        tf.strings.strip(inputs[key]),
        num_oov_buckets=NUM_OOV_BUCKETS,
        vocab_filename=key)

  # For the label column we provide the mapping from string to index.
  table_keys = ['>50K', '<=50K']
  initializer = tf.lookup.KeyValueTensorInitializer(
      keys=table_keys,
      values=tf.cast(tf.range(len(table_keys)), tf.int64),
      key_dtype=tf.string,
      value_dtype=tf.int64)
  table = tf.lookup.StaticHashTable(initializer, default_value=-1)
  # Remove trailing periods for test data when the data is read with tf.data.
  label_str = tf.strings.regex_replace(inputs[LABEL_KEY], r'\.', '')
  label_str = tf.strings.strip(label_str)
  data_labels = table.lookup(label_str)
  transformed_label = tf.one_hot(
      indices=data_labels, depth=len(table_keys), on_value=1.0, off_value=0.0)
  outputs[LABEL_KEY] = tf.reshape(transformed_label, [-1, len(table_keys)])

  return outputs

def transform_data(train_data_file, test_data_file, working_dir, options):
  """Transform the data and write out as a TFRecord of Example protos."""

  with beam.Pipeline(options=options) as pipeline:
    with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
      csv_tfxio = tfxio.BeamRecordCsvTFXIO(
          physical_format='text',
          column_names=ORDERED_CSV_COLUMNS,
          schema=SCHEMA)

      raw_data = (
          pipeline
          | 'ReadTrainData' >> beam.io.ReadFromText(
              train_data_file, coder=beam.coders.BytesCoder())
          | 'FixCommasTrainData' >> beam.Map(
              lambda line: line.replace(b', ', b','))
          | 'DecodeTrainData' >> csv_tfxio.BeamSource())

      raw_dataset = (raw_data, csv_tfxio.TensorAdapterConfig())

      # The TFXIO output format is chosen for improved performance.
      transformed_dataset, transform_fn = (
          raw_dataset | tft_beam.AnalyzeAndTransformDataset(
              preprocessing_fn, output_record_batches=True))

      # Transformed metadata is not necessary for encoding.
      transformed_data, _ = transformed_dataset

      # Extract transformed RecordBatches, encode and write them to the given
      # directory.
      _ = (
          transformed_data
          | 'EncodeTrainData' >>
          beam.FlatMapTuple(lambda batch, _: RecordBatchToExamples(batch))
          | 'WriteTrainData' >> beam.io.WriteToTFRecord(
              os.path.join(working_dir, TRANSFORMED_TRAIN_DATA_FILEBASE)))

      # Will write a SavedModel and metadata to working_dir, which can then
      # be read by the tft.TFTransformOutput class.
      _ = (
          transform_fn
          | 'WriteTransformFn' >> tft_beam.WriteTransformFn(working_dir))

def run(run_local):

    now = time.strftime("%Y%m%d-%H%M%S")
    temp = os.path.join('gs://test_bucket/test_dataflow', 'transformed_data', f'data-{now}')

    if run_local:
        # Execute pipeline in your local machine.
        runner_options = {
            "runner": "DirectRunner",
        }
    else:
        runner_options = {
            "runner": "DataflowRunner",
            "temp_location": os.path.join(temp, "temp_location"),
            "staging_location": os.path.join(temp, "staging_location"),
            "max_num_workers": 6,
            "num_workers": 1
        }

    options = PipelineOptions(
        project='prject_id',
        job_name='dataflow-job-test' + f"-{now}",
        region='us-west1',
        **runner_options
    )

    options.view_as(SetupOptions).save_main_session = True
    options.view_as(SetupOptions).setup_file = os.path.join(
        pathlib.Path(__file__).parent.absolute(), "setup.py")

    transform_data(train, test, temp, options)

if __name__ == "__main__":
    run_local = True
    run(run_local)

This is a part of the following Tensorflow Documentation as mentioned here: Preprocessing data with TensorFlow Transform
However when trying to use the DirectRunner I keep running into the following error:
TypeError: can't pickle PyCapsule objects

And I can't make head nor tail out of it. I checked out this link as well, however the author of the library himself says he can't help. I have tried to run the notebook given in the Tensorflow documentation and the notebook works.
Any help towards this resolving this will be appreciated.

A: I'm guessing you accidentally have a PyCapsule object in your main module due to one of your imports. Try running without save_main_session. (If you need some of the globals, move your pipeline code to a "real" module and only import/invoke run from the main module.)


text:
Q: How to: await / async in a node.js lambda function? I am trying to create an async lambda function that makes a http Get call put it's not working correctly and I believe it has to do with it being async.  If I remove await/async, and make it synchronous, my function works correctly.  I'm not sure what I am doing wrong.  Thank you for your help!
exports.handler = async function (event, context) {

    await setBattery();

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

async function setBattery() {
    'use strict';

    const https = require('https');

    const options = {
        hostname: 'testsite.com',
        port: 443,
        path: '/proxy/api/setting?EM_OperatingMode=1',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    };

    const req = https.request(options, res => {
        console.log(`statusCode: ${res.statusCode}`);

        res.on('data', d => {
            process.stdout.write(d);
        });
    });

    req.on('error', error => {
        console.error(error);
    });

    req.end();

}

A: According with MDN Web Docs:

The async function declaration defines an asynchronous function, which
  returns an AsyncFunction object. An asynchronous function is a
  function which operates asynchronously via the event loop, using an
  implicit Promise to return its result. But the syntax and structure of
  your code using async functions is much more like using standard
  synchronous functions.

So, You need to return a Promise object in order to be handled by your async function (You could also use another promise to handle it), I converted setBattery to a normal function and the return of this function is now a promise that will be handled by your handler (exports.handler). I haven't tested the code but it should work.
exports.handler = async function (event, context) {

    await setBattery();

    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

function setBattery() {
    'use strict';

    const https = require('https');

    const options = {
        hostname: 'testsite.com',
        port: 443,
        path: '/proxy/api/setting?EM_OperatingMode=1',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    };

    // Return it as a Promise
    return new Promise((resolve, reject) => {

        const req = https.request(options, res => {
            console.log(`statusCode: ${res.statusCode}`);

            res.on('data', d => {
                process.stdout.write(d);

                // If successful
                resolve(d);
            });
        });

        req.on('error', error => {
            console.error(error);

            // If failed
            reject(error);
        });

        req.end();

    });

}


text:
Q: How to round to 2 decimals in Java with floats So, assuming, for some reason, floats are absolutely required in the programme one is creating despite the inaccuracy regarding decimal points, is there any method one can use to round them to 2 decimal places without converting them into doubles?

A: Try this:
public static float roundFloat(float number, int scale)
{
    int pow = 10;

    for (int i = 1; i < scale; ++i)
        pow *= 10;

    float tmp = number * pow;

    return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}

Solid and fast.


text:
Q: What is the return address that is pushed onto the stack if interrupt occurs during the execution of the last instruction of a program? Computer organisation and architecture
When an interrupt occurs during the execution of a program then the CPU executes that instruction and stores the address of next instruction in the stack and services the interrupt and then again resumes the execution of the previous programs instructions using the help of stack
Now what if the CPU is executing the last instruction of a program and then an interrupt occurs and what return address is pushed onto stack

A: There does not exist a last instruction of a program.
The CPU will keep fetching instructions - following whatever path those instructions tell it to.
Some architecture have a specific instruction to halt the CPU - this is either a permanent halt (so that interrupts are not served anymore) or a temporary halt.
In the latter case  when the CPU resumes it will re-start fetching instructions from the one after the halt and the program must be aware of this.
In case a program executed inside an operating system, when a program ends it must notify the OS of such condition (may be as simple as doing a return) so that it can "point" the CPU at another program.
The OS itself never ends, it there is nothing to do, a dummy task is scheduled - usually one that halts the CPU until the next interrupt.
There are situations where an interrupt should not occur (e.g. while at the begin of processing another interrupt) - in that case they are disabled.
To put it simple, in the worst a program has to spin in a loop (while (1);) to keep the CPU from fetching behind the end of the code.

At the architecture level interrupts are served at instruction boundaries, i.e. after the "last" instruction ended and before the "next" one.
Some architecture may not enforce this but that's a total different ball of wax.
So when an interrupt is served the state of the CPU is always architecturally defined.
As an interrupt cannot be served during a ret instruction of a call but rather either before or after, the return address either points to the ret itself (if the interrupt is served before) or to the instruction after the call (if it is server after).


text:
Q: Doubly Linked List: Deleting all occurrences of a given key #include<stdio.h>
#include<stdlib.h>

typedef struct node
{
    int data;
    struct node *rlink;
    struct node *llink;
}NODE;

NODE* insert(NODE* header,int info)
{
    NODE *new,*temp;
    new=(NODE*)malloc(sizeof(NODE));
    new->data=info;
    new->rlink=NULL;
    new->llink=NULL;
    if(header->rlink==NULL)
    {
      header->rlink=new;
      new->llink=header;
    }
    else
    {
      temp=header->rlink;
      header->rlink=new;
      new->llink=header;
      new->rlink=temp;
      temp->llink=new;
    }
    return header;
}

NODE* delete(NODE* header,int info)
{
    NODE *temp,*pred,*succ;
    temp=header->rlink;
    while(temp!=NULL)
    {
        while(temp!=NULL&&(temp->data!=info))
        {
            pred=temp;
            temp=temp->rlink;
        }
        if(temp->rlink!=NULL)
        {
            temp->rlink->llink=pred;
        }
        if(temp->llink!=NULL)
        {
            pred->rlink=temp->rlink;
        }
        free(temp);
        temp=pred->rlink;
    }

    return header;
}

void main()
{
    int ch,info;
    NODE* header;
    header=(NODE*)malloc(sizeof(NODE));
    header->rlink=NULL;
    header->llink=NULL;
    ........

The delete function works properly only if the key specified is at the end of the list.
Suppose if the input list is 20 10 20 10 and the key specified is 10, deletion takes place seamlessly but if the key specified is 20, there's a segmentation fault.
What's wrong and how do I fix it?

A: Two issues :

*

*When you get to this check :
if(temp->rlink!=NULL)

temp could be NULL (because the preceding while loop has a stop condition of temp == NULL - when the last node does not match).
Dereferencing NULL typically causes a segmentation fault.
If temp is NULL at that point, just end the loop - you've reached the end of the list without finding more nodes to delete.

*Similarly, when you get to :
temp=pred->rlink;

pred could be uninitialized (if the innermost while loop was skipped - when the first node matches).
Dereferencing an uninitialized pointer can also cause a segmentation fault.
To avoid that, you could initialize pred with header.


text:
Q: A tensor product of power series Let $k$ be a field. I am wondering if there is an easy description of the ring
$$k[[x]] \otimes_{k[x]} k[[x]]$$
that is the tensor product of the power series ring $k[[x]]$ with itself over the ring of polynomials $k[x]$.
Any hints would be appreciated.
Edit: As suggested in the comments I am asking: is this ring isomorphic to $k[[x]]$?

A: The rings $R:=k[[x]]\otimes_{k[x]}k[[x]]$ and $k[[x]]$ are not isomorphic. Here is a mild simplification of Georges Elencwajg's proof.
Assume by contradiction $R\simeq k[[x]]$. Let $K$ be the fraction field of $R$, and $S$ the multiplicative system $k[x]\backslash\{0\}$. As $R$ is a maximal subring of $K$, and $x\otimes1$ is invertible in $$S^{-1}R=k((x))\otimes_{k(x)}k((x)),$$ but not in $R$, we have
$$K=S^{-1}R=k((x))\otimes_{k(x)}k((x)).$$
If $a$ is in $k((x))\backslash k(x)$, then $a\otimes1-1\otimes a$ is a nonzero element of $K$ which is mapped to $0$ by the natural morphism to $k((x))$, a contradiction.

A: No,  the rings $k[[x]] \otimes_{k[x]} k[[x]]$ and $k[[x]]$ are not isomorphic because they have different Krull dimensions:$\; \infty$ and $1$ respectively
I) The ring $k[[x]]$ has Krull dimension one since it is a discrete valuation ring.
II) The ring $k[[x]] \otimes_{k[x]} k[[x]]$ has at least the Krull dimension of its localization $k((x)) \otimes_{k(x)} k((x))$. It is thus sufficient to prove that the latter ring has infinite Krull dimension.
This results from Grothendieck's formula
for the Krull dimension of the tensor product of two field extensions $K,L$ of a field $k$ as a function of the transcendence degrees of the extensions:
$$ \dim (K \otimes_k L) =\min(\operatorname{trdeg}_k K, \operatorname{trdeg}_k L)      $$
Since $\operatorname{trdeg}_{k(x)} k((x))=\infty$, we deduce that, as anounced,
$$\dim(k[[x]] \otimes_{k[x]} k[[x]]) \geq \dim(k((x)) \otimes_{k(x)} k((x))) = \infty$$
Addendum: some properties of our tensor products
i) Let me show, as an  answer to Pierre-Yves's first question in the comments, that $R=k[[x]] \otimes_{k[x]} k[[x]]$ is not a noetherian ring.
 Any ring of fractions of a noetherian ring is noetherian and since, as already mentioned, the ring $T=k((x)) \otimes_{k(x)} k((x))$ is such a ring of fractions , it is enough to show that the latter tensor product $T$ of extensions is not noetherian.
 This results from the following theorem of Vamos: given a field extension $F\subset K$, the tensor product $K\otimes_F K$ is noetherian iff the extension is finitely generated  (in the field sense). Since in our case the extension $k(x) \subset k((x))$ is not finitely generated , we conclude that $T$ is not noetherian.
By the way, since the discrete valuation ring $k[[x]]$ is noetherian this gives another proof that it  $R$ is not isomorphic to $k[[x]]$
ii) Pierre-Yves also asks if the ring $T$ is  local. It is not because a theorem of Sweedler states that a tensor product of algebras over a field is local only if one of the factors is algebraic.
Since  $k(x) \subset k((x))$ is not algebraic, non-locality of $T$ follows.
iii) The ring $R=k[[x]] \otimes_{k[x]} k[[x]]$ is not a domain (another thing  Pierre-Yves has asked about) because if it were, its ring of fractions $T=k((x)) \otimes_{k(x)} k((x))$ would also be a domain ( that reduction again!) and I'm going to show that actually $T$ has zero divisors.
The key remark is that  if $F\subset F(a)$ is a non trivial simple algebraic extension the tensor product $F(a)\otimes _F F(a)$ is not a domain. Indeed we have an isomorphism
$F(a)\otimes _F F(a)=F(a)[T]/(m(T))$ where $m(T)$ is the minimal polynomial of $a$ over $F$. Since $m(T)$ has $a$ as a root, it is no longer irreducible over $F(a)$  and the quotient $F(a)[T]/m(T)$ has zero-divisors.
And now the rest is easy. Just take  an element $a\in k((x))\setminus k(x)$ algebraic over $k(x)$ . Since
$(k(x))(a)\otimes _{k(x)} (k(x))(a)$ is a subring  of $T=k((x)) \otimes_{k(x)} k((x))$ containing zero-divisors, the ring $T$  a fortiori has zero-divisors.


text:
Q: ASP.NET 5 Beta 8 Hosting error: HTTP Error 502.3 - Bad Gateway I created a new ASP.NET 5 Beta 8 project using simply the default template.
When I publish the project and host it on a server using IIS 8.5 I get the error:
HTTP Error 502.3 - Bad Gateway
There was a connection error while trying to route the request.

The CGI application did not return a valid set of HTTP errors.
A server acting as a proxy or gateway was unable to process the request due to an error in a parent gateway.

*

*I am using Windows Server 2012 R2 with IIS 8.5;

*I have the application running on a No Managed code application pool

*I have HttpPlataformHandler 1.2 installed.

What might be wrong?


text:
Q: Bash read dictionary file I have a dictionary file, call it 1.txt with the following content:
app1=1

app2=10

app3=2

app1=8

and so on.
From a bash script I would like to:

*

*call 1.txt

*read its content line by line

*get key into variable A

*get value into variable B

I tried:
var1=${for KEY in "${!dict[@]}"; do echo $KEY; done
var2=${for KEY in "${!dict[@]}"; do echo $dict[$KEY]}; done
which works just fine but I do not know how to wrap this into a bash function that calls the dictionary set on another file.
Would you please point out on this?

A: Probably this is what you want.
#!/bin/bash

declare -A dict

# Read the file into associative array "dict"
read_into_dict () {
    while read -r line; do
        [[ $line = *=* ]] && dict[${line%%=*}]=${line#*=}
    done < "$1"
}

read_into_dict 1.txt

# Print out the dict
for key in "${!dict[@]}"; do
    printf '%s=%s\n' "$key" "${dict[$key]}"
done

A: @M. Nejat Aydin,
I tried the following at localhost.
``
$ cat 73095065.sh
#!/bin/bash
declare -A dict
for EACHLN in $(cat 1.txt)
do
KEY=$(echo "$EACHLN" | sed "s/=.//;")
VALUE=$(echo "$EACHLN" | sed "s/.=//;")
if [ "${dict[$KEY]}" = "" ]
then
dict["$KEY"]="$VALUE"
else
echo "FOUND DUPLICATE KEY AT 1.txt"
echo "HENCE NOT SETTING dict["$KEY"] TO $VALUE AGAIN."
echo "CURRENT LINE: $EACHLN"
echo "OLD dict value: $KEY=${dict["$KEY"]}"
fi
done
echo "EXISTING DICT VALUES:"
for KEY in "${!dict[@]}"
do
echo "KEY $KEY VALUE ${dict[$KEY]}"
done

Sample output:

$ ./73095065.sh
FOUND DUPLICATE KEY AT 1.txt
HENCE NOT SETTING dict[app1] TO 8 AGAIN.
CURRENT LINE: app1=8
OLD dict value: app1=1
EXISTING DICT VALUES:
KEY app3 VALUE 2
KEY app2 VALUE 10
KEY app1 VALUE 1


text:
Q: How to order by Query dsl NumberExpression column In mariadb, I created the function to calucate distance between user point and place point
    /* create function */
    DELIMITER $$

    CREATE
    FUNCTION `u_st_distance_sphere`(`user_point` POINT, `place_point` POINT)
    RETURNS double
    BEGIN
    return (6371*acos(cos(radians(ST_X(user_point)))*cos(radians(ST_X(place_point)))*cos(radians(ST_Y(place_point))
        -radians(ST_Y(user_point)))+sin(radians(ST_X(user_point)))*sin(radians(ST_X(place_point)))));
    END$$
    DELIMITER ;

To use the function, register function in CustomDialect class and apply in .yml
public class MariadbCustomDialect extends MariaDB103Dialect {
    public MariadbCustomDialect() {
        super();
        this.registerFunction(
                "u_st_distance_sphere",
                new StandardSQLFunction("u_st_distance_sphere", StandardBasicTypes.DOUBLE)
        );
    }
}

spring:
  ...
  jpa:
    ...
    database-platform: ...global.config.MariadbCustomDialect

And I want to make distance column that calculated with points and sort by distance ascending order
//in PlaceCustomRepository
//making filtered JPQLQuery

String pointWKT = String.format("POINT(%s %s)",
                                 placeFilterParam.getLatitude(),
                                 placeFilterParam.getLongitude());

NumberTemplate<Double> expr = Expressions.numberTemplate(
    Double.class,
    "u_st_distance_sphere( ST_GeomFromText({0}), ST_GeomFromText({1}) )",
    pointWKT,
    place.point);

JPQLQuery<PlaceResponseTest> query = jpaQueryFactory
    .select(
            new QPlaceResponseTest(place.id,
                                   expr.as("distance")))
    .from(place)
    .orderBy();

How to specify distance column??
Thanks


text:
Q: Modifying bibliography items to have alias names I defined the following macro:
\newcommand{\cmdAlias}[2]{\defcitealias{#1}{#2}\citetalias{#1} \citep{#1}}

Can I modify the .bib file such that the alias name is automatically retrieved from the bibliography (instead of running: \cmdAlias{author:year}{AuthorFirstName AuthorLastName}) For example, how can I modify the following reference to include an alias name for it, something like adding an alias key:
@article{dasi2007vorticity,
  alias = {Dasi {\it et. al}}
  title={Vorticity dynamics of a bileaflet mechanical heart valve in an axisymmetric aorta},
  author={Dasi, LP and Ge, L and Simon, HA and Sotiropoulos, F and Yoganathan, AP},
  journal={Physics of Fluids},
  volume={19},
  pages={067105},
  year={2007}
}

A: \documentclass{article}
\usepackage[square,numbers]{natbib}
\usepackage{hyperref}

\newcommand{\citeAlias}[1]{\defcitealias{#1}{\citeauthor{#1}}\citetalias{#1} \citep{#1}}
\newcommand{\citeAliasTwo}[2]{\defcitealias{#1}{#2}\citetalias{#1} \citep{#1}}

\begin{document}

A reference with one author: \citeAlias{knuth:1974}. It is also possible to manually define the alias name: \citeAliasTwo{knuth:1974}{Donald E. Knuth}.

A reference with more than one author: \citeAlias{dasi2007vorticity}.

\bibliographystyle{plainnat}

\bibliography{mybib}

\end{document}

The following is the content of the mybib.bib:
@ARTICLE{knuth:1974,
  author = {Knuth, Donald E.},
  title = {{C}omputer {P}rogramming as an {A}rt},
  journal = {Communications of the ACM},
  year = {1974},
  volume = {17},
  pages = {667--673},
  number = {12},
  month = {December },
  address = {New York, NY, USA},
  publisher = {ACM Press}
}

@article{dasi2007vorticity,
  title={Vorticity dynamics of a bileaflet mechanical heart valve in an axisymmetric aorta},
  author={Dasi, LP and Ge, L and Simon, HA and Sotiropoulos, F and Yoganathan, AP},
  journal={Physics of Fluids},
  volume={19},
  pages={067105},
  year={2007}
}

The result of the document is the following:

A: With biblatex this is pretty straightforward:
\documentclass[12pt]{article}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@ARTICLE{knuth:1974,
  author = {Knuth, Donald E.},
  title = {{C}omputer {P}rogramming as an {A}rt},
  journal = {Communications of the ACM},
  year = {1974},
  volume = {17},
  pages = {667--673},
  number = {12},
  month = {December },
  address = {New York, NY, USA},
  publisher = {ACM Press}
}
\end{filecontents}

\usepackage{biblatex}
\addbibresource{\jobname.bib}

% from biblatex.def
\DeclareCiteCommand{\citeauthor}
  {\boolfalse{citetracker}%
   \boolfalse{pagetracker}%
   \usebibmacro{prenote}}
  {\ifciteindex
     {\indexnames{labelname}}
     {}%
   \printtext[bibhyperref]{\printnames{labelname}}} % <-- this line changed
  {\multicitedelim}
  {\usebibmacro{postnote}}

\DeclareCiteCommand{\citefullauthor}
  {\boolfalse{citetracker}%
   \boolfalse{pagetracker}%
   \DeclareNameAlias{labelname}{first-last}%
   \usebibmacro{prenote}}
  {\ifciteindex
     {\indexnames{labelname}}
     {}%
   \printtext[bibhyperref]{\printnames{labelname}}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\newcommand\citealiasfull[2]{\citefullauthor{#1} \cite{#1}}
\newcommand\citealiasshort[2]{\citeauthor{#1} \cite{#1}}

\usepackage{hyperref}

\begin{document}

A macro with one parameter that provides the citation
and the author's name: \citealiasshort{knuth:1974}.
\citealiasfull{knuth:1974}

\printbibliography

\end{document}

A: The following is an example of what I am trying to have. I want to define a macro which has only one input and be able to produce both the alias name and the reference number hyper-linked.
\documentclass{article}
\usepackage[square,numbers]{natbib}
\usepackage{hyperref}

\newcommand{\citeAliasOne}[1]{\defcitealias{#1}\citetalias{#1} \citep{#1}}}
\newcommand{\citeAliasTwo}[2]{\defcitealias{#1}{#2}\citetalias{#1} \citep{#1}}

\begin{document}

Here, both the alias name and the reference number are hyper-linked:
\citeAliasTwo{knuth:1974}{Donald E. Knuth}.

Here, I am trying to only use one parameter to the macro and be able to mimic the
result of the macro {\tt citeAliasTwo}. Unfortunately, the result of {\tt citeAliasOne}
is: \citeAliasOne{knuth:1974}, which is not what I want. In fact, I want to define a
macro which gets one input and outputs both the alias name and the reference number
hyper-linked. However, {\tt citeAliasOne} fails for this task.

\bibliographystyle{plainnat}

\bibliography{mybib}

\end{document}

Here is the content of mybib:
@ARTICLE{knuth:1974,
  author = {Knuth, Donald E.},
  title = {{C}omputer {P}rogramming as an {A}rt},
  journal = {Communications of the ACM},
  year = {1974},
  volume = {17},
  pages = {667--673},
  number = {12},
  month = {December },
  address = {New York, NY, USA},
  publisher = {ACM Press}
}

Here is the result:


text:
Q: Assembler Language: Error A2075 Jump destination too far: by 30 bytes What is the  best way to check and debug if jumping too far?
So I have a var inBuffer which contains a BYTE lenght of 115.
I move that into bufSize and try xor'ing it against a set of 3 keys to decrypt the message.
My code compiles but I am unable to to build except this part where it says I am jumping too far.
bufSize DWORD ?
mov eax,115
mov bufSize,eax

;-------------------------------------------------
AnalyzeBuffer PROC
;receives nothing
;returns nothing
;-------------------------------------------------
pushad          ; pushes all data in this method into a stack
mov ecx,bufSize ; loop count
mov esi,0       ; start at index 0 in translated buffer

top:
    cmp buffer[esi],20h    ; checks if character is space which is ok
    je yes

    cmp buffer[esi],2ch    ; checks if character is comma wich is okay
    je yes

    cmp buffer[esi],2eh    ; checks if character is period which is okay
    je yes

    cmp buffer[esi],41h     ; checks if character is above A in the ascii chart
    jb no

    ;the following are all unacceptable characters
    cmp buffer[esi],5bh     ;checks if character is [
    je no
    cmp buffer[esi],5ch     ; checks if character is \
    je no
    cmp buffer[esi],5dh     ;checks if character is ]
    je no
    cmp buffer[esi],5eh      ; checks if character is ^
    je no
    cmp buffer[esi],5fh     ; checks if character is _
    je no
    cmp buffer[esi],60h     ; checks if character is `
    je no
    cmp buffer[esi],7bh     ; checks if characre is {
    je no
    cmp buffer[esi],7ch     ; checks if character is |
    je no
    cmp buffer[esi],7dh     ; checks if }
    je no
    cmp buffer[esi],7eh     ; checks if ~
    je no
    cmp buffer[esi],7fh     ; checks if
    je no

    yes:
        inc esi             ; going to next character
        loop top
        ;getting to this step means these keys worked for all characters in buffer

        mov edx,OFFSET goodMsg
        call WriteString
        call DisplayAllKeys ; shows 3 keys used
        call Crlf
        call Crlf
        mov edx,OFFSET buffer   ; displays decrypted message
        call WriteString
        call Crlf
        call Crlf

    no:
    ;the current character wasnt good so trying next key
    popad
    ret

AnalyzeBuffer ENDP

A: Next time you should tell which line is causing the error. I am guessing it is the loop instruction, because that only exists with a 8 bit offset. Due to optimization reasons, it's it's recommended to avoid using it anyway, and that will solve your jump range problem too. So, just replace it with a dec ecx; jnz top.
You could also optimize your checks, but that's another story.


text:
Q: CoreData: Mogenerator vs. Categories I have recently inherited a CoreData project from an outside developer. Where I expected to find all my auto-generated NSManagedObject sub-classes, I instead have (what some googling reveals to be) classes generated by Mogenerator, a tool that I have no experience with.
I understand that the purpose of using this tool is to make it so that you can add custom code into the classes corresponding to the CoreData entities without worrying about it being lost when the model changes and the classes are regenerated... but I can do this anyways by using categories.
I currently do not see a real advantage to using Mogenerator over categories.
What are the advantages/disadvantages of using Mogenerator vs. categories? Does Mogenerator serve any additional purposes?

A: An advantage of using classes vs categories, is that you can extend functionality by subclassing and overriding.
For instance, if your model has subentities, it is possible for them to inherit functionality from a common master class.  Subclasses could define specific behavior by overriding the desired methods.  On the other hand, it is possible to override methods defined in categories, but it is not recommended.  This means logic implemented as categories would have to be repeated in every subclass.
A lot of code in managed objects is boilerplate, so it's really nice to have mogenerator do it automatically.

A: From their 'site'  http://rentzsch.github.com/mogenerator/ :

mogenerator generates Objective-C code for your Core Data custom
  classes
Unlike Xcode, mogenerator manages two classes per entity: one for
  machines, one for humans
The machine class can always be overwritten to match the data model,
  with humans' work effortlessly preserved

So basically it got nothing to do with categories. Mogenerator (Model Object Generator) generates code which you've seen the results from in the project you've gotten handed over.


text:
Q: Differentiability on boundaries For example, consider the function $f: \  [0, 1] \mapsto \mathbb{R} $, $f(x)=x^2 $. Is it differentiable at $x=0$ and $x=1$? Intuitively I would guess no, because it doesn't make sense to talk about limits when the function is not defined on both sides of the considered point. If some more general definition was presented would it be possible?
This came to my mind when I was reading some basic calculus book. When trying to find the extrema of a function (for example $ \mathbb{R}^3 \mapsto \mathbb{R} $) it is said separately that one needs to check the points were the gradient is not defined but also the boundaries. I thought that talking about gradient on boundaries doesn't make any sense. But does a function have a gradient on a boundary point?

A: It's really a matter of convention, but I would say yes. For any function $f\colon A\to\Bbb R$, where $A\subseteq\Bbb R$, we say $f'(c)=d$ if
$$\lim\limits_{x\to c}\frac{f(x)-f(c)}{x-c}=d.$$
By definition, this means for any $\varepsilon>0$, there exists $\delta>0$ such that
$$0<|x-c|<\delta\qquad\text{implies}\qquad \left|\frac{f(x)-f(c)}{x-c}-d\right|<\varepsilon.$$
Here's where you must decide exactly what the last phrase means. There are two options:

*

*For all $x\in A$ such that $0<|x-c|<\delta$, we have $\left|\frac{f(x)-f(c)}{x-c}-d\right|<\varepsilon$.

*For all $x\in \Bbb R$ such that $0<|x-c|<\delta$, we have $\left|\frac{f(x)-f(c)}{x-c}-d\right|<\varepsilon$.

Option $2$ doesn't really make sense because the expression $\left|\frac{f(x)-f(c)}{x-c}-d\right|$ is not defined unless $f(x)$ is defined. On the other hand, option $1$ applies more generally, and one can indeed say "the function $f\colon[0,1]\to\Bbb R$ with $f(x)=x^2$ is differentiable at $0$." HOWEVER now you have some potentially unwanted results. For example, take $g\colon\{0\}\to\Bbb R$ with $g(0)=0$. According to the option $1$, $g$ is differentiable, but only because there are never any points $x\in A$ such that $0<|x-c|$. But then $f'(0)$ is not well-defined since it could be any value.
To deal with this, some authors simply define the derivative for interior points, and extend this to boundary points as we just did. This makes sense because the derivative, if it exists, is determined by looking at a one-sided limit on whichever side is actually in the domain.
Finally, I'll give another slight variation I like:

*For all $\varepsilon>0$, there exists $\delta>0$ such that $B(c,\delta)=A\cap ((c-\delta,c)\cup(c,c+\delta))$ is nonempty, and for any $x\in B(c,\delta)$, we have $\left|\frac{f(x)-f(c)}{x-c}-d\right|<\varepsilon$.

This agrees with the usual definition and also works on boundary points. It also works on any limit point of the domain. This ensures that, if $f$ is differentiable at $c$, then $f'(c)$ is well-defined. As an example, take $f\colon\{1/n:n\in\Bbb N\}\to\Bbb R$ where $f(x)=x^2$. The derivative is defined at only $x=0$, and we can say $f'(0)=0$.

A: As you say, it does not make sense to talk about differentiability in a boundary point. In general, $x$ must be an interior point of the domain $A\subset\mathbb{R}^n$ of the function ($f:A\to\mathbb{R}^m$) in order to properly talk about what we mean by differentiability in $x$. The reason, as you also point out (but in this case, more generally) is that the directional derivative at $x$ must be defined for all directions, and this doesn't happen if $x$ is not an interior point of $A$ (i.e., if there doesn't exist a ball centered at $x$ which is completely contained in $A$).


text:
Q: How to update TextureView SurfaceTextureListener I am developing a camera app and I will use front and back camera. I am using TextureView like this:
<TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        />

and code behind:
renderer = new CameraRenderer(this, isFrontCamera);
textureView.setSurfaceTextureListener(renderer);

CameraRenderer class implemet SurfaceTextureListener
public class CameraRenderer implements Runnable, TextureView.SurfaceTextureListener{...

and I set camera in onSurfaceTextureAvailable method like this:
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            if (renderThread != null && renderThread.isAlive()) {
                renderThread.interrupt();
            }
            renderThread = new Thread(this);

            surfaceTexture = surface;
            gwidth = width;
            gheight = height;

            // Open camera
            int cameraId;
            if(isFrontCamera)
                cameraId = getFrontCamera();
            else
                cameraId = getBackCamera();

            camera = Camera.open(cameraId);

renderThread.start();
    }

Problem:
When I want to change camera and click button I am creating a new CameraRenderer instance and set to textureView
textureView.setSurfaceTextureListener(renderer);

but onSurfaceTextureDestroyed method in CameraRenderer class never called, also onSurfaceTextureAvailable method is not called too.
I can call onSurfaceTextureDestroyed method myself but I can't set second camera preview to textureView because onSurfaceTextureAvailable method is not called second time.
Here is my onSurfaceTextureDestroyed method:
    @Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
    if (camera != null) {
        camera.stopPreview();
        camera.release();
    }
    if (renderThread != null && renderThread.isAlive()) {
        renderThread.interrupt();
    }
    CameraFilter.release();

    return true;
}

Last note: I tried set listener as null but not working.
So How can I re-set textureView Listener. Thanks in advance!


text:
Q: Perl SOAP timeout does not work I am calling a webservice which is returning 80.000 records. Because record count is too big, call ends with timeout. But the issue I culd not understand is that call ends earlier or later than the time I defined. My code is below, I defined timeout as 10 minutes (600 sec.)
my $soap = SOAP::Lite
    -> on_action( sub { join '/', @_ } )
     -> uri($uri)
     -> proxy($proxy, timeout => 600)
     -> ns($ns1,"soapenv")
     -> ns($ns2,"ns2");

But call sometimes ends with timeout in 5 minutes , sometimes ends in 18 minutes. What is the reason of this? Why it does not end in 10 minutes?
And what can I do more to prevent timeout? It is sure that reason of timeout is record cout because when record count is decreased it works.

A: I ran into this issue as well, the proxy timeout wasnt working for me. This code worked however:
$soap->transport->timeout(600);
or
$self->{soap}->transport->timeout(600);


text:
Q: Could not get dependencies for project reference when mixing .NET Core and .NET Framework projects I recently pulled down a project that had upgraded to .NET Core 3.1.  The rest of my projects are running .NET Framework 4.5.1, and use references from that .NET Core project.  When I try to add these references, I get the error "Could not get dependencies for project reference".  In Visual Studio, IntelliSense still completes code in the .NET Framework for the .NET Core code, but I still get the error.
Is there any way to import and reference this package?

A: See Lex Li's answer from above.  They did turn out to be incompatible, prompting me to replace the old projects with .NET core projects.  It was a hassle but worth it by far.  Using entity framework make life much easier, too.


text:
Q: move block and figures arbitrarily I would like to put a figure in the right part of a slide and text in the left part, in order to explain the figure.
Then i would like to put another block at the bottom of the slide.
I'm using Beamer.
How can I move blocks and figures in a single slide?

A: You can use the columns environment as follows:
\documentclass{beamer}
\usepackage{mwe} %For dummy image

\author{The author}
\title{The title}

\begin{document}
\begin{frame}{Frame title}{Frame subtitle}

\begin{columns}
    \begin{column}{0.3\textwidth}
    The Explanation
    \end{column}
    \begin{column}{0.7\textwidth}\centering
    \includegraphics[width=.6\linewidth]{example-image-a}
    \end{column}
\end{columns}

\vspace{1cm}

\begin{block}{title}
content
\end{block}
\end{frame}

\end{document}


text:
Q: Refactor UIButton to UILabel in storyboard I've a view in my storyboard with a lot of UIButton with constraints.
Is there a way to transform these buttons to labels without removing each button and create a label with constraints?

A: *

*UIButton actually contains a UILabel for displaying its titleLabel. So You can set the button UserInteractionEnabled: property to NO.

*UIButton may have border color. So set the border color as clear color.

*Make the UIButton as custom type.
As you need to reconfigure the constrains again if you added the labels, you can go for the above solution.
Reason for couldn't change in IB/Storyboard:
You have dragged the UIButton from the library to your view. Even you try to change the class name to UILabel or its subclass it won't change the class name.
because UILabel is just a UIView type, Where as UIButton is UIControl type.
That's why you couldn't change the UIButton class name to UILabel or Subclass of UILabel in IB.
Updates:
No Guarantee/Not Recommended on upcoming XCode release


text:
Q: There is a way to avoid navigator.geolocation.getCurrentPosition from be cached? I'm using in my React Native App the navigator.geolocation.getCurrentPosition() function to get the location of  my device but I have been reading that sometimes if the function notes that you have no good signal it could return the cached location. There is a way to avoid the returning cached location and return an error instead?

A:
geolocation.getCurrentPosition(geo_success, [geo_error],
  [geo_options]);

Use the option value in the function. You can use maximumAge

*

*maximumAge(ms)-positive value representing the maximum life in
milliseconds of a reversible cache location. If set to 0, it means
that the device cannot use the cached location and must actually
retrieve the current location. When set to Infinity, the device
always returns a cached position, regardless of its lifetime. The
default is INFINITY.

var options = {
  enableHighAccuracy: true, // true: use GPS false : WIFI
  maximumAge: 0 // default Infinity
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log('Latitude : ' + crd.latitude);
  console.log('Longitude: ' + crd.longitude);
  console.log('More or less ' + crd.accuracy + ' meters.');
};

function error(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

A: I found the solution!
The problem was that I wasn't passing the timeout time to the options and then the device was trying to get the location immediately, so it wouldn't be able to do that and was getting from the cache.
Now it is getting like 3 seconds to get the location but works fine!

A: I had similar problem.
First location from
navigator.geolocation.watchPosition(onLocationFound, onLocationError, {maximumAge:60000, timeout:12000, enableHighAccuracy:true});
was to old.
Compare e.timestamp and current timestamp
now = new Date();
if((now - e.timestamp)<10000){ //OK if less than 10 sek (10000ms)
//YES, new location
//stop updating navigator.geolocation.clearWatch(window.watchId);
}
else
{
//old lacation, wait
}


text:
Q: Метод замены элемента в массиве У меня есть массив
[
  {
    "name":"BMW",
    "price":"55 000",
    "color":"red",
 },
 {
   "name":"MERSEDEC",
   "price":"63 000",
   "color":"blue",
 }
];

Нужно написать функцию которая будет на входе принимать массив и на выходе будет вместо name  будет вылетать class
"class":"MERSEDEC",
"price":"63 000",
"color":"blue",

Какой метод использовать?

A:

var data = [{
    "name": "BMW",
    "price": "55 000",
    "color": "red",
  },
  {
    "name": "MERSEDEC",
    "price": "63 000",
    "color": "blue",
  }
];
function nameToClass(arr) {
  arr.forEach(i => {
    i.class = i.name;
    delete i.name;
  });
  return arr;
}
console.log(nameToClass(data));

Как сделать так что бы class был первым, а не в конце?

var data = [{
    "name": "BMW",
    "price": "55 000",
    "color": "red",
  },
  {
    "name": "MERSEDEC",
    "price": "63 000",
    "color": "blue",
  }
];
function nameToClass(arr) {
  var str = JSON.stringify(arr);
  str = str.replace(/name/g, "class");
  arr.splice(0, arr.length, ...JSON.parse(str));
  return arr;
}
console.log(nameToClass(data));

A: Если нужно заменить name на class, то можно просто сделать всё в цикле:
var items; // Ваш массив с данными.
var i;
for(i = 0; i < items.length; i++){
    items[i].class = items[i].name;
    delete items[i].name;
}

A: Если почему-либо требуется оставить исходный массив в первозданном виде:

let data = [{
    "name": "BMW",
    "price": "55 000",
    "color": "red",
  },
  {

    "name": "MERSEDEC",
    "price": "63 000",
    "color": "blue",
  }
];

function transform(arr) {
  return arr.map(item => {
    let newItem = Object.assign({}, item);
    newItem.class = item.name;
    delete newItem.name;
    return newItem;
  })
}

console.log(transform(data));


text:
Q: Angular best practice - where store applicaiton settings from API In my application I want to get initial call with some settings for application. These will include forms data (validation rules, dropdowns' options...), maybe some other settings (tbd).
What is best practice of storing this data?
Just object in server? Local storage?....
In AngularJS I remember using rootScope (which was not ideal).
Thanks for advice.

A: There are two recommended practices,
When you create your angular application with Angular CLI  you always have a folder with environment files:
<APP_FOLDER>/src/environments/
                       └──environment.ts
                       └──environment.prod.ts

you can create additional target-specific configuration files, such as environment.qa.ts and environment.staging.ts.
and use them in your service (the correct environment file is chosen automatically).
Other way is to add your json files to assets folder and use http get to serve those files.


text:
Q: How do I use ChangeNotifier? From the docs I understood that one can call addListener() on a ChangeNotifier instance to add a custom listener to the stack.
This method accepts a callback with zero arguments (according to notifyListeners()), e.g.:
class MyClass extends ChangeNotifier {

  MyClass() {
    addListener(() {
      // ...
    });
  }
}

From within the callback, how does one find out what properties or parts of MyClass have been changed?

A: ChangeNotifier does not have such capabilities inherently. You will have to implement your own logic. Specifically, you either have access to all of the properties of your ChangeNotifier implementation because you add the listener in its scope or you have access to it because you have a reference to it in your scope.
ChangeNotifier simply implements Listenable and provides some utilities for managing listeners. Furthermore, the documentation states the following about it:

ChangeNotifier is optimized for small numbers (one or two) of listeners. It is O(N) for adding and removing listeners and O(N²) for dispatching notifications (where N is the number of listeners).

I am not sure about options with better runtime complexity for notifying listeners, but you will not run into any issues in a regular Flutter app.
ValueNotifier
ValueNotifier is a pre-made implementation of ChangeNotifier that will notify its listeners when its value property is changed.
This is sufficient for most case, but since it appears that you want to create a custom ChangeNotifier, you can use the source code of ValueNotifier to take a look at an example implementation (it is very straight forward).

If you are just looking to do state management in general, ValueNotifiers usually work great. However, they are not applicable in every scenario. Hence, here is an extensive list with different state management options.
Considering the questions, I think the techniques that fit your needs best and the most popular options are the following:

*

*InheritedWidget as it lets you notify dependents based on what data changed. Additionally, there is InheritedModel as an extension of this and InheritedNotifier that works with Listenable, just like ChangeNotifier does.

*The BLOC pattern, which works with streams.

*The provider package which is mostly a convenience wrapper for various Flutter state management techniques (InheritedWidget, StatefulWidget, ValueNotifier, etc.).


text:
Q: assigning an item in a list using a function to get the desired address how can I return the address of the value in the list I wish to change?
I can change a value in a list in this manner:
a = [1, 2, 3]
a[0] = 0

but how can I change a value that a helper function choose?
helper = lambda x: x[0]
a = [1, 2, 3]
helper(a) = 0

will produce a runtime error type syntax error
(because python interpret it like 1 = 0)
my question is how can I build a function that chooses the index for me?
functions that return only the index are not helpful:
example:
helper = lambda x: 0
a = [1, 2, 3]
a[helper(a)] = 0

will not solve the problem for (for example) 2d lists:
helper_1 = lambda x: 0, 0
a = [[1, 2, 3]]
a[helper(a)[0]][helper(a)[1]] = 0

as you can see this makes the code very ugly very fast.
I will provide two simple examples for this issue:
first example code, 1d list:
lst = [1, 2, 3]
for x in lst:
    x *= 2
# will not change the list

if there were pointers:
for &x in lst:
    *x *= 2

second example code, 2d list:
def rotate_90(image, direction):
    rows, columns = len(image), len(image[0])
    rotated = empty_2d(columns, rows) # allocate 2d list

    rotated_place = lambda row, col: rotated[col][-1- row] \
                     if direction =='R' else \
                    lambda row, col: rotated[-1-col][row]

    for row in range(rows):
        for col in range(columns):
            rotated_place(row, col) = image[row][col] # error

    return rotated
# will produce an error

if there were pointers:
def rotate_90(image, direction):
    rows, columns = len(image), len(image[0])
    rotated = empty_2d(columns, rows) # aloccate memory

    rotated_place = lambda row, col: &rotated[col][-1- row] \
                     if direction =='R' else \
                    lambda row, col: &rotated[-1-col][row]

    for row in range(rows):
        for col in range(columns):
            *rotated_place(row, col) = image[row][col]

    return rotated

A: Changing a bit for clarity, you want this to print [42, 2, 3]:
first = ...

a = [1, 2, 3]
first(a) = 42

print(a)

You can make it work with first[a] instead of first(a):
class First:
    def __setitem__(_, lst, value):
        lst[0] = value
first = First()

a = [1, 2, 3]
first[a] = 42

print(a)

Try it online!


text:
Q: How do i check if the player has cheated with the developer console? I have tried to make a clicker game with a basic way to tell if the game has been cheated with variables but it just doesnt work right even after intentionally cheating to test it.
Heres my HTML code: (has the js)

var i = 0;

function myFunc() {
  var one = document.getElementById("one");
  if (one.innerHTML == "Click the button to get your first dimension!") {
    one.innerHTML = "You have one dimension."
  } else {
    a = i
    b = a + 1
    i += 1;
    if (i == b) {
      alert("No Cheats")
    } else {
      alert("Cheater!")
    }
    one.innerHTML = "You have " + i + " dimensions."
  }
}
#one {
  width: 200px;
  height: 200px;
  border: 1px solid blue;
}

button {
  width: 200px;
  background: yellow;
  box-shadow: 4px 4px 4px #333;
}
<!DOCTYPE HTML>
<title>Clicker</title>
turn on javascript man

Click the button to get your first dimension!

  <button onclick="myFunc()"> Dimension Creator </button>

A: As comments on your original question pointed out, you need to use a backend to make your game uncheatable. However, a less devoted (and more cheat-prone) approach would be to make the page unusable if the console is opened. You can do this by checking the difference between outer browser dimensions and inner browser dimensions. Like this:
setInterval(function() {
    const widthDiff = window.outerWidth - window.innerWidth > 160;
    const heightDiff = window.outerHeight - window.innerHeight > 160;
    if (widthDiff || heightDiff) {
        console.log('You are cheating.');
        location.reload();
    }
}, 500);

However, this will not work with users who use a floating browser window. You can fix this by using the debugger keyword, but users won't be immediately punished. Like this:
setInterval(function() {
    var minimalUserResponseInMiliseconds = 100;
    var before = new Date().getTime();
    debugger;
    var after = new Date().getTime();
    if (after - before > minimalUserResponseInMiliseconds) { // user had to resume the script manually via opened dev tools
        console.log("You are cheating");
        location.reload();
    }
}, 500);

(code from this answer)


text:
Q: VS2012 Add Service Reference not updating config file I have created a new IIS hosts WCF service using the webHttpBinding which is currently running on on IIS Express on my development machine and when I try to "Add Service Reference" the service is correctly built and the Reference.cs file looks fine but the web.config or app.config files are not being updated.
No warnings or error messages are received.
Both the service and the client are targeting .Net 4.5.
Service config
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="webInteropSecureBinding" allowCookies="false" maxBufferPoolSize="2097152" maxBufferSize="2097152" maxReceivedMessageSize="2097152">
          <security mode="Transport" />
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="PsmDataProvider.PsmProvider" behaviorConfiguration="SecureRest">
        <clear />
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="webInteropSecureBinding" name="PsmProvider" contract="PsmDataProvider.IPsmProvider" listenUriMode="Explicit" behaviorConfiguration="webHttpBehavior" />
        <endpoint address="mex" binding="mexHttpsBinding" name="mex" contract="IMetadataExchange" listenUriMode="Explicit" />
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:44300/PsmProvider/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="SecureRest">
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

Client Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

Client Service Reference

Following some investigation I found these StackOverflow questions
Question 1
Question 2
Question 3
And this post
Blog post
Each of the above refer to the same problem of unticking the "Reuse types in references assemblies" flag which I have done.

The problem is it did not fix the issue. I have tried updating and deleting and recreating the service reference but it never updates the config file.
Question
Is this a problem with the server side configuration? Or is this an issue with the client side? How to I change either so that the proxy generation works as expected?

A: OK, looks like there are issues in adding a service reference to services that implement the WebHttpBinding WCF binding.
This is discussed in Carlos Figueira Blog Post

A: Remove maxBufferPoolSize="2097152" maxBufferSize="2097152" from your web.config file. Then try to update your service. Make sure your Bindings are correctly mentioned.

A: I had the same problem again today with VS2012.
I have a set of Test, PreProduction and Production web.config configurations, I could use "Preview transformation", and see that VS2012 was patching my "web.config" with the relevant settings..

...but... when I deployed, well, it just seemed to include the default "web.config" file without any changes.
The cause was that VS2012 seemed to have messed up its configurations, and in the Publish dialog, suddenly my PreProduction configuration was associated with Debug.  Huh ?

Changing this from "Debug" to "PreProduction" fixed the issue for me.
Or, at least, it nudged me a step forward, but I'm still having an issues with VS2012 messing up my configuration names when it tries to deploy.

(Depressed sigh.)
Currently downloading VS2013.  Hopefully, this release will be less buggy.

A: In my case, it was caused by I set a binding parameter wrong on the web service side.
binding.ReliableSession.InactivityTimeout = TimeSpan.Maximum;
After set this to System.TimeSpan(0, 10, 0); the binding configuration is generated in web.config file.


text:
Q: Does there exist an analytic function s.t. $f\left(\frac{1}{n}\right)=2^{-n}.$ Prove that there does not exist an analytic function $f$  in an unit disc containing $0$ such that $$f\left(\frac{1}{n}\right)=2^{-n}.$$
I tried by using Identity theorem.
Suppose that $f$ is analytic in the unit disc.
Consider the function $g(z)=f(z)-2^{-\frac{1}{z}}$.
Then the zeros of the function $g(z)$ are $\{\frac{1}{n}:n\in \mathbb N\}$ which has a limit point $0$ in the disc. So, $g$ is identically zero. Then, $f(z)=2^{-1/z}$. But, I am unable to find a point such that we arrive at a contradiction.
Please help to find it OR any other technique to prove the question.

A: Note that
$$f(z) = 2^{-1/z}$$
is not continuous at $z=0$. Indeed: For $(z_n)_{n \in \mathbb{N}} \subseteq (0,\infty)$ such that $z_n \to 0$, we have
$$f(z_n) \to 0.$$
On the other hand, for $w_n := -z_n \to 0$,
$$f(w_n) \to \infty.$$
Since an analytic function has to be continuous, this contradicts our assumption.


text:
Q: Counting exercise Three players a,b,c take turns in a game according to the following rules:

At the start A and B play (so C does not play). The winner of the first trial plays against C and so on until one of the players wins two trials in a row.
  Possible outcomes are
  aa,acc,acbb,acbaa,
  bb,bcc,bcaa,bcabb etc.

We have to prove that probability of A winning equals p(A) = 5/14, p(B) = 5/14, p(C) = 2/7
I have been stuck on this problem for a long time. The only thing I have been able to find out so far is that C can never win on even turns.
Re-edit
Players continue to play until one of them wins two times consecutively and all players are equally good at playing the game.
Apologies for leaving such crucial information.

I have finally solved this problem with a different approach
Sample space
aa ,acc ,acbb ,acbaa ,acbacc ,acbacbb ,acbabcaa ,...
bb ,bcc ,bcaa ,bcabb ,bcabcc ,bcabcaa ,bcabcabb ,...
Each point in the sample space has a probability (1/2^k) associated with it where k is the number of turns.
For example probability of point (aa) = 1/4
Now let us construct a table enumerating probabilities -

Let us consider the event that C wins overall. But C can only win if k = 3,6,9,12,...
P(C) = P(C3) + P(C6) + P(C9) ......
where P(Ck) = Probability of C winning overall after k turns.
P(C) = 1/4 + 1/32  .....
P(C) = a / (1 - r)       ( Sum of an infinite GP )
a = 1/4                  ( First Term )
r = 1/8                  ( Ratio )
P(C) = 2/7
P(A) = 5/14 = P(B)

A: First, let us assume $A$ wins the first game.  Let $a$ be the probability that $A$ wins overall, $b$ the probability that $B$ wins overall, and $c$ the probability that $C$ wins overall.  Then we can write (in this case) $a=\frac 12 + \frac b2$ because $A$ either wins the second game (and wins overall) or loses the second game and is now in $B$'s position.  Similarly, $c=\frac 12a$ because if $C$ wins his first game he is in $A$'s position, while if he loses his first game $A$ wins overall.  Finally $b=\frac 12c$ because $B$ needs $C$ to win and he is now coming in, which is $C$'s position.  This gives
$$a=\frac 12 + \frac b2\\c=\frac a2\\b=\frac c2\\a=\frac 12+\frac c4==\frac 12+\frac a8=\frac 47\\c=\frac 27\\b=\frac 17$$
This is correct for $C$, but we assumed $A$ won the first one.  Clearly $A$ and $B$ have the same winning probability at the start so we can split their total chances evenly, giving $$P(A)=\frac 5{14}, P(B)=\frac 5{14},P(C)=\frac 27$$

A: Perhaps the problem is supposed to be,
3 players A, B and C take turns at a game according to the following rules. At the start A and B play while C is out. The loser is replaced by C and at the second trial the winner plays against C while the loser is out. The game continues in this way until a player wins twice in succession, thus becoming the winner of the game. What is the probability that Player A will be the winner? What is the probability that player C will be the winner? (assume in each match, A has .6 chance to beat B, and .4 chance to beat C, B has .5 chance to beat C.)
which I found at http://www.chegg.com/homework-help/questions-and-answers/3-players-b-c-turns-game-according-following-rules-start-b-play-c--loser-replaced-c-second-q2427231
(and, yes, I know this is not an answer, but I don't think it would fit as a comment).

A: Here's my crack at the question:
Since both players $A,B$ satisfy:
$$M_k(p) = \{\{1, 1\},\{1,0,1,1\},\{1,0,1,0,1,1\},...\}$$ where $M_k(p)$ is the $k$th way for player $p$ to win the game. $\{1\}$ indicates winning the trial, and $\{0\}$ indicates loss.
As player C, and only $C$, satisfies;
$$N_k(p) = \{\{0,1, 1\},\{0,1,0,1,1\},\{0,1,0,1,0,1\},...\}$$
Trials needed to have elapsed for $C$ to win the game is $\mid N_1(C)\mid = (\mid M_1(A) \mid +\mid M_1(B)\mid)-1 = 3$
Thus, chances of player $p$ winning the game in this case is:

Define players $A,B,C$ as $0,1,2$
$t=$Trials needed to win the game.
$n=$Number of players.
$k=$Number of players with the same chances of winning($A,B$), .
$$
P(p) = \left\{\begin{matrix}
{kt-1 \over k((M_1(p)\;t)+1)} & p < 2\\
{t \over (N_1(p)\;t)+1} & p = 2
\end{matrix}\right.
,\quad -1 < p < n
$$
Where $P(p)$ is the probability of player $p$ winning.
Edit:
To clarify: The reason that the chance of player $C$ winning is highest, is because there is a greater chance that player ($A,B$) won't win because they share the same set of combinations needed to win.
Disclaimer:  I have not tested this thoroughly in any way, and drafting was started prior to question being answered.


text:
Q: SwifType Rate limit exceeded I currently have a demo account. I am trying to make a POC using SwifType for my employer. We have a very big database that is indexec every 1h and creates a JSON file. I thought the integration with Elastic would be very easy considering it's only a mater of sending the string when it's generated. I used PHP Curl and got a connection to the API. The code sends out part of the data and then freaks out with a "Rate limit exceeded" error.
How can I manage around that error and get the full JSON indexed?
My code looks like this at the moment:
// SENDING DATA TO ELASTIC SEARCH
$arr = array_change_key_case($arr, CASE_LOWER); // Keys to lower case
$arrlist = array_chunk($arr,100); // Split to chunks of 100
foreach($arrlist as $key=>$arr){
    $json = json_encode($arr); // Making the JSON string from the array
    $ch = curl_init('https://host-***.api.swiftype.com/api/as/v1/engines/***/documents');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: Bearer private-***';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);

    echo $result."<hr>";
}

Also, considering this code is going to be indexed every hour, if I am sending the same data over and over, will it UPDATE the previous one or will it duplicate it? If so, how can I manage that?

A: You need to look at the X-RateLimit-Remaining header (see details here) when it hits 0 (or gets close to it) or when you receive a 429 response, you sleep() and then retry. I'd recommend using exponential backoff if you receive multiple 429 responses in a row (double the sleep time every time you receive a 429, reset it down to default value when your request succeeds).


text:
Q: How to store data in form of object into firestore using swift I want to store data into object form using swift language.The data structure of the data base is like
collection/
document/
collection/
document1/:
           Invitess1(object) :
                              name :"santosh"
                              phone :1234567890
          Invitee2(object) :
                              name :"sam"
                              phone:1234654768
          .....
document 2/
          Initee1(object) :

                           name:"red"
                           phone:4654343532
         .......

is it possible to store data like this? if possible how to do it? i tried like this :
for var i in 0..<n { // n is no.of selected contacts
            for var j  in i...i {
                print("amount is \(d[i])")
                print("phone number is \(num[j])")
                let dataToSave:[String: Any] = ["name" :"vijayasri",
                                                "PhoneNumber":num[j],
                                                "Amount": d[i],
                                                ]
            }

        }
        var ref:DocumentReference? = nil
        ref = self.db.collection("deyaPayUsers").document("nothing").collection("Split").addDocument(data: dataToSave){
            error in
            if let error = error {
                print("error adding document:\(error.localizedDescription)")

            } else {
                print("Document ades with ID:\(ref!.documentID)" )
            }

        }

    }

But it doesn't work. How to do it..

A: Your example code is never going to work as intended since dataToSave is overwritten every iteration of the j loop. Your inner j loop probably has a typo at i...i
To store multiple objects in one document, create the document in Swift with multiple objects in it. Since you know how to encode your object as [String:Any], just take those dictionaries combine into a larger [String:Any]document.
I would change your code to be more like:
var dataToSave: [String:Any] = []()
for var i in 0..<n { // n is no.of selected contacts
    var inProcess: [String:Any] = []()
    for var j  in i...i {
        print("amount is \(d[i])")
        print("phone number is \(num[j])")
        let detail: [String: Any] = ["name" :"vijayasri",
                                     "PhoneNumber":num[j],
                                     "Amount": d[i]]
        inProcess["NextKey\(j)"] = detail
     }
    dataToSave["SomeKey\(i)"] = inProcess
 }

 var ref:DocumentReference? = nil
 ref = self.db.collection("deyaPayUsers").document("nothing").collection("Split").addDocument(data: dataToSave){
        error in
        if let error = error {
            print("error adding document:\(error.localizedDescription)")

        } else {
            print("Document ades with ID:\(ref!.documentID)" )
        }

    }

}


text:
Q: How to convert Word track changes markup to document content? I would like to edit a Word document with Track Changes on, and then save the document with the track changes markup as the actual document. For instance, deleted words should be in the final document with strike-through. In addition, I would like to keep the formatting from Advanced Track Changes Options.

A: I am using Word 2010, so I am not sure how the menus are in Word 2003, I think it's Tools > Options > Tracked Changes. What you are looking to do is set it to Show all revisions inline which will show changes within the text rather than in balloons at the side or bottom. It should look like this;


text:
Q: XPATH mulitple condition to exclude some elements I would like to parse schema data using XPATH.
Here's a simple structure.

  May 10th 2009

 Product name

     USD 500

The result I would like to parse is like this:
1. Category: http://www.schema.org/Product
  v name: Product name
  v Offers
      - price: USD 500
2. Category: http://www.schema.org/Person
  v birthday: May 10th 2009

To categorize "http://www.schema.org/Product" and "http://www.schema.org/Person", I used this code:
var category = $x("//*[@itemtype and not(@itemprop)]");

So category[0]:

  May 10th 2009

 Product name

     USD 500

Category[1]:

  May 10th 2009

Before parsing itemprop, I have to purge this one on category[0] to prevent duplicated data,
...

  May 10th 2009

...

How can I exclude those things on category[0]?
I would like to exclude this one under category[0]->
Final expression I would like to make:
Select category[0] not select ([contains(@itemtype,'schema.org/') and not(@itemprop)]/descendant-or-self::*)

Please shed light on the matter.
Thank you:)


text:
Q: Common test for CYPRESS with constants I installed CYPRES but I have  thirty sites to test.
Is it possible to write tests in order to have the test only once in a common folder, and a list of constants for each site:
In a common folder:
describe('Test URL', () => {
  it('Home ', () => {
    cy.visit(LIST OF URL)
  })
})

In a folder foreach website:
LIST OF URL = '/home,/contact,/faq';

For the form for example:
describe('Form', () => {
  it('form, () => {
        cy.visit('/contact')
        })
  it('field name', () => {
    cy.get(PATH FIELD_NAME)
      .type('test')
    })
  it('mail field', () => {
    cy.get(PATH FIELD_MAIL)
      .type('test@test.com')
    })

In a folder foreach website:
PATH FIELD_NAME = 'input#name';
PATH FIELD_MAIL = 'input#mail';

It would be easier to maintain.
I don't see how to do this. Is was possible?

A: If by sites you mean pages of a single site, then you can take a data driven approach
const urls = ['/home', '/contact', '/faq']

describe('Test URL', () => {

  urls.forEach(url =>

    it(`Testing ${url}`, () => {
      cy.visit(url)
    })
  })
})

The form does not seem to be repetitious, for example is name & email on the /home or /faq pages?
If you use the same page (e.g /contact) on multiple websites, and it's the same each time, you may be able to use component testing and test it just once.


text:
Q: What is an "XCopy version"? I am trying to download Oracle Data Access Components. Some of the components are named as XCopy version. I know that XCopy is a command but what exactly does it mean in this context ?

A: it appears to be referring to the same Xcopy command you are, and will do an Xcopy deployment, instead of using OUI. From the documentation (this, for example):

Administrators use XCopy to deploy Oracle Data Provider for .NET to
  large numbers of computers for production deployments. The XCopy has a
  smaller installation size and fine-grain control during installation
  and configuration than Oracle Universal Installer.

The install.bat for the 12c ODAC installer is doing:
xcopy asp.net %2 /E /F /R /Y >> %2\install.log

etc., for each component, where %2 is the path supplied to the installer, e.g. c:\oracle.


text:
Q: Is the a way to cancel/not list directories/files which can't be read anyways because of lacking permission by fs.readdirSync? A way to filter out those directories which need administration permission.
fs.readdirSync(currentPath, { withFileTypes: true }).forEach(element => {
   ....
})

Still shows all directories. Even those that need admin permission to be read/written to etc.

A: You can try to use the  fs.access() method:

Tests a user's permissions for the file or directory specified by path

// Check if you have permission to read the file
function isFileReadable(file) {
  try {
    fs.accessSync(file, fs.constants.R_OK);
    return true;
  } catch (err) {
    return false;
  }
}

fs.readdirSync(currentPath, { withFileTypes: true }).forEach(element => {
    // If the file is readable, log it
    if(isFileReadable(element)) {
      console.log(`${element}`);
    }
   ...
})


text:
Q: Error converting dict to json in python my dict output looks like this

What library to use to convert it to json in python?
edit 1:
my code now looks like
import boto3
import json
rds_client = boto3.client('rds', 'ap-southeast-1')
db_instance_info = rds_client.describe_db_instances()
with open('result.json', 'w') as db:
    json.dump(db_instance_info, db)

and it shows this error
Traceback (most recent call last):
  File "list.py", line 14, in <module>
    json.dump(db_instance_info, db)
  File "/usr/lib/python2.7/json/__init__.py", line 189, in dump
    for chunk in iterable:
  File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
    o = _default(o)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) is not JSON serializable

A: The error is explicit:
TypeError: datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) is not JSON serializable

By default the json module cannot serialize any of the types from the datetime module, and your dictionary contains ..., u'InstanceCreateTime': datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()), and other datetimes later.
The idiomatic way is to define a custom encoder to process the relevant objects. It is enough to override the default method, process the specific objects and pass everything else to the base class method:
class DateEncoder(json.JSONEncoder):
"""This encoder only use the default string convertion for the types
date, time and datetime of the datetime module"""
    def default(self, o):
        if (isinstance(o, datetime.date)
            or isinstance(o, datetime.datetime)
            or isinstance(o, datetime.time)):
            return str(o)                # specialize here the format...
        return json.JSONEncoder.default(self, o)

You can then use it to build your json:
with open('result.json', 'w') as db:
    json.dump(db_instance_info, db, cls=DateEncoder)

A: Just use the json module:
import json
jsonarray = json.dumps(the_dict, ensure_ascii=False)

The ensure_ascii bit is there to avoid any encoding/decoding errors.

A: You can use the json library in python
import json
x = {'s': True}
r = json.dumps(x)

This will give a json string


text:
Q: how how properties of an array can someone please help me with some code to count properties of an array, so i have an array and i want to count all the complete items the have the value 1. here is my array
[{
    "order_id": "336566",
    "customer_name": "joel",
    "customer_surname": "kabeya",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2019-01-21 15:00:27",
    "delivery_date": "2019-01-24",
    "delivery_from": "10:30",
    "delivery_to": "12:00",
    "completed": "1",
    "shopper": "joel"
}, {
    "order_id": "335719",
    "customer_name": "joel",
    "customer_surname": "kabeya",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2018-12-24 13:46:27",
    "delivery_date": "2018-12-30",
    "delivery_from": "10:30",
    "delivery_to": "12:00",
    "completed": "1",
    "shopper": "joel"
}, {
    "order_id": "336531",
    "customer_name": "Tay",
    "customer_surname": "Z",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2019-01-11 08:42:27",
    "delivery_date": "2019-01-17",
    "delivery_from": "10:30",
    "delivery_to": "12:00",
    "completed": "1",
    "shopper": "joel"
}, {
    "order_id": "336545",
    "customer_name": "joel",
    "customer_surname": "kabeya",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2019-01-17 19:00:27",
    "delivery_date": "2019-01-18",
    "delivery_from": "11:00",
    "delivery_to": "12:00",
    "completed": "0",
    "shopper": "joel"
}, {
    "order_id": "241918",
    "customer_name": "Marietjie",
    "customer_surname": "Short",
    "total_items": "44",
    "completed_items": "44",
    "percent_complete": 1,
    "datetime_received": "2018-07-25 15:18:25",
    "delivery_date": "2018-10-29",
    "delivery_from": "12:00",
    "delivery_to": "13:00",
    "completed": "0",
    "shopper": "Tay"
}, {
    "order_id": "281774",
    "customer_name": "Ashleigh",
    "customer_surname": "Hodge",
    "total_items": "16",
    "completed_items": "0",
    "percent_complete": 0,
    "datetime_received": "2018-10-04 15:59:19",
    "delivery_date": "2018-10-29",
    "delivery_from": "12:00",
    "delivery_to": "13:00",
    "completed": "0",
    "shopper": null
}]

A: Use a foreach loop to iterate and add. Also filter can be used.
//foreach

The foreach loop loops through every element and checks if the object has the completed property set to 1. If it is one the counter is incremented and returned. Otherwise the counter is returned as is.
//filter

Filter also loops through the elements one by one and if they satisfy the condition(completed==1) it returns true and send the element to a new array whose length we print. If it returns false, the value is not inserted inside the array.

var a=[{
    "order_id": "336566",
    "customer_name": "joel",
    "customer_surname": "kabeya",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2019-01-21 15:00:27",
    "delivery_date": "2019-01-24",
    "delivery_from": "10:30",
    "delivery_to": "12:00",
    "completed": "1",
    "shopper": "joel"
}, {
    "order_id": "335719",
    "customer_name": "joel",
    "customer_surname": "kabeya",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2018-12-24 13:46:27",
    "delivery_date": "2018-12-30",
    "delivery_from": "10:30",
    "delivery_to": "12:00",
    "completed": "1",
    "shopper": "joel"
}, {
    "order_id": "336531",
    "customer_name": "Tay",
    "customer_surname": "Z",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2019-01-11 08:42:27",
    "delivery_date": "2019-01-17",
    "delivery_from": "10:30",
    "delivery_to": "12:00",
    "completed": "1",
    "shopper": "joel"
}, {
    "order_id": "336545",
    "customer_name": "joel",
    "customer_surname": "kabeya",
    "total_items": "0",
    "completed_items": "0",
    "percent_complete": 1,
    "datetime_received": "2019-01-17 19:00:27",
    "delivery_date": "2019-01-18",
    "delivery_from": "11:00",
    "delivery_to": "12:00",
    "completed": "0",
    "shopper": "joel"
}, {
    "order_id": "241918",
    "customer_name": "Marietjie",
    "customer_surname": "Short",
    "total_items": "44",
    "completed_items": "44",
    "percent_complete": 1,
    "datetime_received": "2018-07-25 15:18:25",
    "delivery_date": "2018-10-29",
    "delivery_from": "12:00",
    "delivery_to": "13:00",
    "completed": "0",
    "shopper": "Tay"
}, {
    "order_id": "281774",
    "customer_name": "Ashleigh",
    "customer_surname": "Hodge",
    "total_items": "16",
    "completed_items": "0",
    "percent_complete": 0,
    "datetime_received": "2018-10-04 15:59:19",
    "delivery_date": "2018-10-29",
    "delivery_from": "12:00",
    "delivery_to": "13:00",
    "completed": "0",
    "shopper": null
}]
var count=0;
a.forEach((e)=>e.completed=="1"?count++:count)
console.log(count);
//filter
console.log(a.filter((e)=>e.completed=="1"?true:false).length)

A: Leverage Array.filter() and use the length property of Array.  Bear in mind that your completion criteria is that completed is the String value "1".  So filter based on that predicate, then count the items left.

const yourPileOfData = [{
    completed: "1"
  },
  {
    completed: "1"
  },
  {
    completed: "0"
  }
];

const count = yourPileOfData.filter(i => i.completed === "1").length;

console.log(count);


text:
Q: Does a threadlocal variable need to be static to pose a memory leak At this link here
They describe memory leaks when using classloaders. Now this comment:

A classloader will be removed by the garbage collector only if nothing else refers to it. All classes hold a reference to their classloader and all objects hold references to their classes. As a result, if an application gets unloaded but one of its objects is still being held (e.g., by a cache or a thread-local variable), the underlying classloader cannot not be removed by the garbage collector!

I understand somewhat. But in the portion when they say:

(e.g., by a cache or a thread-local variable)

am I correct to say that by cache they mean a static reference and by threadlocal, they mean a non-static threadlocal variable.  I say this because all code explanations of threadlocal memory leaks make the threadlocal variable as static. For example, this question in SO
My other question with the comment about cache is: a static variable will be GC-ed when application does down, so why does this present a problem?

A: Each Thread has (effectively) a WeakHashMap, where Data is some object, the object refers to the Class, the Class refers to the ClassLoader, the ClassLoader refers to all classes it has loaded (e.g., ThreadLocalHolder), ThreadLocalHolder class has a static that holds the ThreadLocal, and so the WeakHashMap value refers to the key, which prevents the key+value from being collected until the entire Thread object goes away.  See my this answer for a more detailed explanation and example.