text:
Q: Join a time-series dataframe with an "interval" dataframe I am struggling to join data from an interval dataframe to a time series dataframe.
For each row of my time series, I want to look in which interval it is included and return a specific value from the interval dataframe.
I got inspired by this solution : How to join two dataframes for which column values are within a certain range?
But it is not working for a too complex reason from my knowledge.
Here is my error message :
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13072/1034504056.py in <module>
      1 #df_test.index = pd.IntervalIndex.from_arrays(df_test['Start'],df_test['End'],closed='both')
----> 2 data_test['Product'] = data_test.index.to_series().apply(lambda x : df_test.iloc[df_test.index.get_loc(x)]['Product'])

~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwargs)
   4355         dtype: float64
   4356         """
-> 4357         return SeriesApply(self, func, convert_dtype, args, kwargs).apply()
   4358
   4359     def _reduce(

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply(self)
   1041             return self.apply_str()
   1042
-> 1043         return self.apply_standard()
   1044
   1045     def agg(self):

~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
   1097                 # List[Union[Callable[..., Any], str]]]]]"; expected
   1098                 # "Callable[[Any], Any]"
-> 1099                 mapped = lib.map_infer(
   1100                     values,
   1101                     f,  # type: ignore[arg-type]

~\Anaconda3\lib\site-packages\pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()

~\AppData\Local\Temp/ipykernel_13072/1034504056.py in <lambda>(x)
      1 #df_test.index = pd.IntervalIndex.from_arrays(df_test['Heure début réelle'],df_test['Hre fin réelle'],closed='both')
----> 2 data_test['Designation'] = data_test.index.to_series().apply(lambda x : df_test.iloc[df_test.index.get_loc(x)]['Désignation article'])

~\Anaconda3\lib\site-packages\pandas\core\indexes\interval.py in get_loc(self, key, method, tolerance)
    631         matches = mask.sum()
    632         if matches == 0:
--> 633             raise KeyError(key)
    634         elif matches == 1:
    635             return mask.argmax()

KeyError: Timestamp('2021-10-23 23:59:29')

The function I want to succeed .
df_test.index = pd.IntervalIndex.from_arrays(df_test['Start'],df_test['End'],closed='both')
data_test['Product'] = data_test.index.to_series().apply(lambda x : df_test.iloc[df_test.index.get_loc(x)]['Product'])

Sample value for data_test
{'Ordre': {92: 3149484,
  93: 3149484,
  94: 3149484,
  95: 3149610,
  96: 3149610,
  97: 3149610,
  98: 3149610,
  99: 3149610,
  100: 3149610,
  101: 3149610,
  102: 3149611},
 'Start': {92: Timestamp('2021-10-26 06:55:00'),
  93: Timestamp('2021-10-26 06:55:00'),
  94: Timestamp('2021-10-26 06:55:00'),
  95: Timestamp('2021-10-26 07:25:00'),
  96: Timestamp('2021-10-26 07:25:00'),
  97: Timestamp('2021-10-26 07:25:00'),
  98: Timestamp('2021-10-26 08:30:00'),
  99: Timestamp('2021-10-26 08:30:00'),
  100: Timestamp('2021-10-26 08:30:00'),
  101: Timestamp('2021-10-26 08:30:00'),
  102: Timestamp('2021-10-26 11:37:00')},
 'End': {92: Timestamp('2021-10-26 07:25:00'),
  93: Timestamp('2021-10-26 07:25:00'),
  94: Timestamp('2021-10-26 07:25:00'),
  95: Timestamp('2021-10-26 08:30:00'),
  96: Timestamp('2021-10-26 08:30:00'),
  97: Timestamp('2021-10-26 08:30:00'),
  98: Timestamp('2021-10-26 11:37:00'),
  99: Timestamp('2021-10-26 11:37:00'),
  100: Timestamp('2021-10-26 11:37:00'),
  101: Timestamp('2021-10-26 11:37:00'),
  102: Timestamp('2021-10-26 12:30:00')},
 'Product': {92: 'Product_1',
  93: 'Product_1',
  94: 'Product_1',
  95: 'Product_2',
  96: 'Product_2',
  97: 'Product_2',
  98: 'Product_2',
  99: 'Product_2',
  100: 'Product_2',
  101: 'Product_2',
  102: 'Product_2'}}

Sample value for df_test
{'Temperature_1': {Timestamp('2021-10-26 06:55:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:56:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:57:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:58:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:59:29'): 62.9905242919922,
  Timestamp('2021-10-26 08:25:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:26:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:27:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:28:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:29:29'): 65.0611953735352},
 'Temperature_2': {Timestamp('2021-10-26 06:55:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:56:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:57:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:58:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:59:29'): 66.8290863037109,
  Timestamp('2021-10-26 08:25:29'): 67.0449523925781,
  Timestamp('2021-10-26 08:26:29'): 67.0449523925781,
  Timestamp('2021-10-26 08:27:29'): 67.0449523925781,
  Timestamp('2021-10-26 08:28:29'): 66.0404281616211,
  Timestamp('2021-10-26 08:29:29'): 66.0404281616211}}

The output would be a new column that indicate which product is concerned regarding timestamp included or not in the interval :
{'Temperature_1': {Timestamp('2021-10-26 06:55:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:56:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:57:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:58:29'): 62.9905242919922,
  Timestamp('2021-10-26 06:59:29'): 62.9905242919922,
  Timestamp('2021-10-26 08:25:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:26:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:27:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:28:29'): 65.0611953735352,
  Timestamp('2021-10-26 08:29:29'): 65.0611953735352},
 'Temperature_2': {Timestamp('2021-10-26 06:55:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:56:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:57:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:58:29'): 66.8290863037109,
  Timestamp('2021-10-26 06:59:29'): 66.8290863037109,
  Timestamp('2021-10-26 08:25:29'): 67.0449523925781,
  Timestamp('2021-10-26 08:26:29'): 67.0449523925781,
  Timestamp('2021-10-26 08:27:29'): 67.0449523925781,
  Timestamp('2021-10-26 08:28:29'): 66.0404281616211,
  Timestamp('2021-10-26 08:29:29'): 66.0404281616211},
'Product': {Timestamp('2021-10-26 06:55:29'): 'Product_1',
  Timestamp('2021-10-26 06:56:29'): 'Product_1',
  Timestamp('2021-10-26 06:57:29'): 'Product_1',
  Timestamp('2021-10-26 06:58:29'): 'Product_1',
  Timestamp('2021-10-26 06:59:29'): 'Product_1',
  Timestamp('2021-10-26 08:25:29'): 'Product_2',
  Timestamp('2021-10-26 08:26:29'): 'Product_2',
  Timestamp('2021-10-26 08:27:29'): 'Product_2',
  Timestamp('2021-10-26 08:28:29'): 'Product_2',
  Timestamp('2021-10-26 08:29:29'): 'Product_2'}}

NEW SET OF DATA
data_test = {'Ordre': {53: 3147783, 54: 3147783, 55: 3147783, 56: 3147783, 57: 3147783},
 'Start': {53: Timestamp('2021-10-24 20:35:00'),
  54: Timestamp('2021-10-24 20:35:00'),
  55: Timestamp('2021-10-25 00:01:00'),
  56: Timestamp('2021-10-25 00:01:00'),
  57: Timestamp('2021-10-25 00:01:00')},
 'End': {53: Timestamp('2021-10-24 23:59:00'),
  54: Timestamp('2021-10-24 23:59:00'),
  55: Timestamp('2021-10-25 04:27:00'),
  56: Timestamp('2021-10-25 04:27:00'),
  57: Timestamp('2021-10-25 04:27:00')},
 'Product': {53: 'Product_1',
  54: 'Product_1',
  55: 'Product_1',
  56: 'Product_1',
  57: 'Product_1'}}

df_test = {'Temperature_1': {Timestamp('2021-10-24 23:55:00'): 48.0,
  Timestamp('2021-10-24 23:56:00'): 48.0,
  Timestamp('2021-10-24 23:57:00'): 48.0,
  Timestamp('2021-10-24 23:58:00'): 48.0,
  Timestamp('2021-10-24 23:59:00'): 48.0,
  Timestamp('2021-10-25 00:00:00'): 48.0,
  Timestamp('2021-10-25 00:01:00'): 48.0,
  Timestamp('2021-10-25 00:02:00'): 48.0},
 'Temperature_2': {Timestamp('2021-10-24 23:55:00'): 60.0,
  Timestamp('2021-10-24 23:56:00'): 60.0,
  Timestamp('2021-10-24 23:57:00'): 60.0,
  Timestamp('2021-10-24 23:58:00'): 60.0,
  Timestamp('2021-10-24 23:59:00'): 60.0,
  Timestamp('2021-10-25 00:00:00'): 59.0,
  Timestamp('2021-10-25 00:01:00'): 59.0,
  Timestamp('2021-10-25 00:02:00'): 59.0}}

Thank you for your help and advice

A: The intervals should be created on the data_test, not df_test. Also, your data_test has duplicates:
data_test = data_test.drop_duplicates()
data_test.index = pd.IntervalIndex.from_arrays(data_test['Start'],
                                               data_test['End'],
                                               closed='both')

product = (df_test
           .index
           .to_series()
           .apply(lambda df: data_test.iloc[data_test.index.get_loc(df),
                                            data_test.columns.get_loc('Product')])
          )

df_test.assign(Product = product)

Temperature_1  Temperature_2    Product
2021-10-26 06:55:29      62.990524      66.829086  Product_1
2021-10-26 06:56:29      62.990524      66.829086  Product_1
2021-10-26 06:57:29      62.990524      66.829086  Product_1
2021-10-26 06:58:29      62.990524      66.829086  Product_1
2021-10-26 06:59:29      62.990524      66.829086  Product_1
2021-10-26 08:25:29      65.061195      67.044952  Product_2
2021-10-26 08:26:29      65.061195      67.044952  Product_2
2021-10-26 08:27:29      65.061195      67.044952  Product_2
2021-10-26 08:28:29      65.061195      66.040428  Product_2
2021-10-26 08:29:29      65.061195      66.040428  Product_2

For the updated data, you are right that if a value is not within the intervals it will fail. There are alternatives to solve this:
One option is to use conditional_join from pyjanitor, which can help to abstract inequality joins:
# pip install pyjanitor
import pandas as pd
import janitor

data_test = pd.DataFrame(data_test)

df_test = pd.DataFrame(df_test)

df_test.index.name = 'Timestamp'

(df_test
  .reset_index()
  .conditional_join(
       data_test,
       ('Timestamp', 'Start', '>='),
       ('Timestamp', 'End', '<='), how = 'left')
  .loc[:, ['Timestamp', 'Temperature_1', 'Temperature_2', 'Product']]
  .set_index('Timestamp')
)
                     Temperature_1  Temperature_2    Product
Timestamp
2021-10-24 23:55:00           48.0           60.0  Product_1
2021-10-24 23:55:00           48.0           60.0  Product_1
2021-10-24 23:56:00           48.0           60.0  Product_1
2021-10-24 23:56:00           48.0           60.0  Product_1
2021-10-24 23:57:00           48.0           60.0  Product_1
2021-10-24 23:57:00           48.0           60.0  Product_1
2021-10-24 23:58:00           48.0           60.0  Product_1
2021-10-24 23:58:00           48.0           60.0  Product_1
2021-10-24 23:59:00           48.0           60.0  Product_1
2021-10-24 23:59:00           48.0           60.0  Product_1
2021-10-25 00:00:00           48.0           59.0        NaN
2021-10-25 00:01:00           48.0           59.0  Product_1
2021-10-25 00:01:00           48.0           59.0  Product_1
2021-10-25 00:01:00           48.0           59.0  Product_1
2021-10-25 00:02:00           48.0           59.0  Product_1
2021-10-25 00:02:00           48.0           59.0  Product_1
2021-10-25 00:02:00           48.0           59.0  Product_1

The other option involves IntervalIndex; however, instead of apply, we use a for loop (apply is sort of a for loop):
# start afresh

data_test = pd.DataFrame(data_test)

df_test = pd.DataFrame(df_test)

# build the intervals
intervals = pd.IntervalIndex.from_arrays(data_test['Start'],
                                         data_test['End'],
                                         closed='both')

data_test.index = intervals

values = {}

# create dictionary of values found in the intervals
for val in df_test.index:
    present = intervals.contains(val)
    if present.any(): # we found something!
        values[val] = intervals[present]

values = pd.Series(values).explode()

# reindex and create a temporary column
df_test.loc[values.index, 'intervals'] = values.array

# use the temporary column to merge
(df_test
  .merge(data_test.Product,
         left_on='intervals',
         right_index = True,
         how = 'left')
  .drop(columns='intervals')
)

                     Temperature_1  Temperature_2    Product
2021-10-24 23:55:00           48.0           60.0  Product_1
2021-10-24 23:55:00           48.0           60.0  Product_1
2021-10-24 23:56:00           48.0           60.0  Product_1
2021-10-24 23:56:00           48.0           60.0  Product_1
2021-10-24 23:57:00           48.0           60.0  Product_1
2021-10-24 23:57:00           48.0           60.0  Product_1
2021-10-24 23:58:00           48.0           60.0  Product_1
2021-10-24 23:58:00           48.0           60.0  Product_1
2021-10-24 23:59:00           48.0           60.0  Product_1
2021-10-24 23:59:00           48.0           60.0  Product_1
2021-10-25 00:00:00           48.0           59.0        NaN
2021-10-25 00:01:00           48.0           59.0  Product_1
2021-10-25 00:01:00           48.0           59.0  Product_1
2021-10-25 00:01:00           48.0           59.0  Product_1
2021-10-25 00:02:00           48.0           59.0  Product_1
2021-10-25 00:02:00           48.0           59.0  Product_1
2021-10-25 00:02:00           48.0           59.0  Product_1


text:
Q: Why won't a Boolean cast narrow type in short-circuit evaluation? I'm trying to narrow an optional argument in short-circuit evaluation.
Here's a Typescript playground with the below code: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABFApgZygCgA5zWmAIwBsBPAVTABMVgYwUqB+ALkQwCd6BzASkQDeAWABQiRAHoJiAO4ALFEghwQxKogAGufETKUadBlQ2IEyBYi7c5URHICG1djBqJCKROAP1GTUeI4UKBAOJAAhODhiFEccPAISCmpaHyp+ADJ0xG0EvWTDRgA6aLBuKDkAblEAXyA
function test(possiblyUndefined?: string) {
  // when could `possiblyUndefined` on the right hand side be undefined?
  return Boolean(possiblyUndefined) && possiblyUndefined.length;
}

This errors out with: 'possiblyUndefined' is possibly 'undefined'.
...But that can't be right. The left-hand side of the statement can only ever succeed when possiblyUndefined is not undefined, right?

A: Because the Boolean function will happily accept undefined, and TypeScript doesn't have it defined as a type predicate that guarantees its input isn't undefined (probably because that's not its purpose, even though it's true that Boolean will return false for undefined). If you look at the current definition of it, it's this (relevant portion highlighted):
interface BooleanConstructor {
    new(value?: any): Boolean;
    <T>(value?: T): boolean;             // <====
    readonly prototype: Boolean;
}

declare var Boolean: BooleanConstructor;

That's just a function that returns boolean, not a type predicate.¹
If you want to handle undefined, you can do so explicitly. I'd also use > 0 so your function always returns boolean, not false | number (though that's up to you, of course):
return typeof possiblyUndefined !== "undefined" && possiblyUndefined.length > 0;
// or
return possiblyUndefined !== undefined && possiblyUndefined.length > 0;

Although these days I think I'd probably go for optional chaining (?.) and nullish coalescing (??):
return possiblyUndefined?.length ?? 0 > 0;

Playground link for the above

¹ It's interesting to see from the link in Leland's own answer that there's at least talk of making it a predicate function. But it isn't one as of this writing. It's just a conversion function.

A: Answering my own question. This is a missing feature in Typescript.

Boolean() cannot be used to perform a null check

https://github.com/microsoft/TypeScript/issues/16655

redpajama_set_name: RedPajamaStackExchange


text:
Q: date validations with javascript I need sample javascript code to validate the date with mm-dd-yyyy format.
1) if user enters wrong date with respect to above date format.
2) Date range validations,start date and end date range validations.
Any help on this appreciated.
Regards,
Chaitu

A: Validating the format could be something like:
function isValidDateFormat(s) {
  return /^\d\d-\d\d-\d\d\d\d$/.test(s);
}

For date ranges, convert the string to a date object and compare it to date objects for the limits of the range.
Here's a date validation function - no need to check the format of the input, if it's wrong, the function returns false:
// Expects date in US-specific mm-dd-yyyy or
// mm/dd/yyyy format
function isValidDate(d) {
  var bits = d.split(/[-/]/);
  var date = new Date(bits[2] + '/'
                    + bits[0] + '/'
                    + bits[1]);
  return date && (date.getMonth()+1) == bits[0]
              && date.getDate() == bits[1];
}

So now you have how to validate the format, how to validate a date and how to convert a string to a date object. Should be pretty simple to do the comparison from here.

A: A detailed one, I used years back...

And a bit of html for demonstration:
<form method="get" onSubmit="return ValidateForm()">

Enter a Date (mm/dd/yyyy): <input type="text" name="txtDate" maxlength="10" size="15">

<input type="submit" value="Submit">

</form>


text:
Q: MySQL - Performance issue in simple SUM() I'm trying to do a simple sum in MYSQL 5.7 (installed on my notebook - I5, 8Gb ram) and am having a big performance issue.
If I do:
SELECT distinct `Text Field`
FROM Table1
group by `Text Field`;

The query runs in 7s and returns 72 rows
If I do:
SELECT sum(`Value Field`)
FROM Table1;

The query runs in less than 1s and returns 1 line with the total sum.
However, if I do:
select `Text Field`, sum(`Value Field`)
from Table1
group by `Text Field`;

The query runs for 1 hour before the connection times-out!
The table has 26 columns (but I'm only using those 2 fields in the query), has 1.5 million rows and 821mb.
I already played with some memory variables:
table_open_cache=2000
tmp_table_size=256M
innodb_buffer_pool_size=1000M
innodb_log_file_size=500M

and also tried to run the query as following:
select `Text Field`, sum(`Value Field`)
from (
        SELECT `Text Field`, `Value Field`
        FROM Table1
    ) as T1
group by `Text Field`;

All without any success.
EDIT
I also have one, auto-increase, Index column.

A: The fast queries don't do anything with a group of rows for multiple group keys. The first just scans the post-group key values. The second treats the entire table as one group and scans the post-group key values. (In both cases maybe the post-group keys are table keys, hence indexed?) But the third has to do something with every row of the table, including collect them together per post-group key and add them.
Learn to use UNIQUE NOT NULL (including PRIMARY KEY) and other indexes and constraints and EXPLAIN. Read about query implementation/execution/optimization/performance in general & for particular (versions of particular) DBMSs.


text:
Q: Generate a "blank" font using the metrics of another font This question is in relation to one of my previous questions: How to replace a large block of text by an empty block of the same size?
Is it possible to generate a "blank" font using the metrics of another font in LaTeX? Can this be done "on the fly", during the typesetting of the document?

A: Edit: different method.
Depending on what you want to do with it, the implementation could likely be improved, but how about the following:
\documentclass{article}
\usepackage{xcolor}
\usepackage{transparent}
\usepackage{etoolbox}

\newbool{trans}

\newcommand{\transon}{
    \booltrue{trans}
}
\newcommand{\transoff}{
    \boolfalse{trans}
}
\newcommand{\ttext}[1]{
    \ifbool{trans}
        {\texttransparent{0}{#1}}
        {#1}
}

\begin{document}

\transoff{}
\ttext{Here is some text.}

\transon{}
\ttext{Here is some text.}

\end{document}

A: @digital-Ink: am not sure this answers your question but the command
\special{color rgb X Y Z} changes the color of the `pen' until the document ends or you change the color again. Here X Y Z is the rgb color specification, so you could just change it to white, i.e.
\special{color rgb 1 1 1}

would change the font color to white but of course latex keeps going as though nothing happened.
\special{color rgb 0 0 0}

changes it back to normal.


text:
Q: ng-repeat and ui-if When I want to use ui-if (anguluarUi) with ng-repeat (and I think it would be most useful there) I Get an error:
Error: Multiple directives [uiIf, ngRepeat] asking for transclusion on: <!-- uiIf: oConnection.aOptions -->

Is there any way to combine those two?
Edit:
<ng-repeat><div ui-if>...

Is not possible (for now) unfortunately.
I know that I can combine ng-show and ng-repeat, but it's not the same.
I also don't want to put the ui-if outside of the repeat, as I want to use the values of the repeat for the condition.

A: I think that a filter should be used instead of ui-if.

A: ui-if was removed at least from latest version angular-ui but since angular 1.1.5 you have ng-if build-in.


text:
Q: AsyncTask: Not Writing data to file I'm fairly new to Android programming, I've been giving some code to solve a problem which I can't seem to figure out for quite a while now.
I've got a AsyncTask which is trying to save some data into a file placed on the internal storage of the device. The file is created but is populated with 0 bytes
public void exportFile(final Context mContext, boolean debug) {

    try {
        final String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/DroidP";
        File dir = new File(path);
        dir.mkdirs();

        final File file = new File(dir, "Droid_export.txt");

        if (file.exists()) {
            file.delete();
        }

        file.createNewFile();

        final FileWriter out = new FileWriter(file,true);

        final int totalLines = recordsIdList.size();
        new AsyncTask<Void, String, Void>() {
            ProgressDialog progressDialog;

            @Override
            protected Void doInBackground(Void... arg0) {
                try {

                    List<byte[]> mainBuffer = new ArrayList<byte[]>();

                    int i = 0;
                    int size = 0;

                    for (Integer r : recordsIdList) {
                        Log.i("test", db.getRecord(r).toExportSQL());

                        byte[] buffer = db.getRecord(r).toExportSQL().getBytes();
                        mainBuffer.add(buffer);
                        size += buffer.length;

                        publishProgress("Writing " + (i++) + " from "+ totalLines);
                    }

                    int pos = 0;
                    char[] outBuffer = new char[size];
                    for(byte[] chunk : mainBuffer) {
                        for(i=0;i<chunk.length;i++) {
                            outBuffer[pos] = (char)chunk[i];
                            pos++;
                        }
                    }

                    out.write(outBuffer);

                    out.flush();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
      }

            @Override
            protected void onProgressUpdate(String... progress) {
                progressDialog.setMessage(progress[0]);
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                progressDialog.dismiss();
            }

            @Override
            protected void onPreExecute() {
                progressDialog = ProgressDialog.show(mContext,
                        "Exporting file", "", true);
            }
        }.execute((Void) null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file.getAbsoluteFile()));
        sendBroadcast(intent);
    } catch (Exception e) {

    }
}

When I look at the logs, I'm able to see the data that I'm trying to save into the file, which is the correct one, but once the AsyncTask finishes a file is created with 0 bytes.Am I missing something? Remember, I'm fairly new to Android Programming.

A: I haven't tested for your error but you could simplify your problem a bit by skipping the byte to char conversion and move file handing into the async task as many has suggested.
Try something like this:
private Boolean isExporting = false;

public void exportFile(final Context mContext, boolean debug) {
    if (!isExporting) {
        isExporting = true;
        new AsyncTask<Void, String, Void>() {
            ProgressDialog progressDialog;

            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    // read data into byte array
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int i = 0;
                    for (Integer r : recordsIdList) {
                        byte[] buffer = db.getRecord(r).toExportSQL().getBytes();
                        Log.i("test", new String(buffer));
                        baos.write(buffer);
                        publishProgress("Writing " + (i++) + " from " + totalLines);
                    }
                    baos.close();
                    // write data to file
                    final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DroidP";
                    final File dir = new File(path);
                    dir.mkdirs();
                    final File file = new File(dir, "Droid_export.txt");
                    file.createNewFile();
                    final FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baos.toByteArray());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(String... progress) {
                progressDialog.setMessage(progress[0]);
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                isExporting = false;
                progressDialog.dismiss();
            }

            @Override
            protected void onPreExecute() {
                progressDialog = ProgressDialog.show(mContext,
                        "Exporting file", "", true);
            }
        }.execute();
    }
}


text:
Q: ggplot2 warnings : Warning message: Computation failed in `stat_density()`: attempt to apply non-function I am trying to use ggplot to plot 2 data sets of mine. This is my code below.
data <- read.table("test.txt",sep="\t",header = F)
y <- data.frame(v1=data$V7,v2=data$V8)
head(y)

         v1         v2
1 -0.305037 0.00223546
2 -0.207126 0.26586100
3  0.290341 0.49381600
4 -0.345713 0.21023300
5 -1.249040 0.54090400
6 -0.340126 0.60984800

y2<-head(y,100)
d2<-melt(y2)
ggplot(d2,aes(y2=value, fill=variable)) + geom_density(alpha=0.25)

I was taking help from this post for my data set
Overlay density plots
I am getting this warning and the graph is not being generated:
Warning message:
Computation failed in stat_density():
attempt to apply non-function
How can I make this work?
Thanks

A: This seems to generate what I assume you're looking for. The biggest thing is to change y2= to x= in the ggplot call.
(I just used y as the values you provided. I assume this should work for whatever y you have)
The y2 <- head(y,100) is only necessary if you're trying to create the density plots for only the first 100 values.
y <- data.frame(v1 = c(-.305, -.207, .290, -.346, -1.25, -.340),
                v2 = c(.002, .266, .464, .210, .541, .610))

library('reshape2')
d2 <- melt(y)

library('ggplot2')
ggplot(d2, aes(x = value, fill = variable)) + geom_density(alpha = .25)

A: In case anyone else sees this question and the accepted answer which relate to a particular case, the underlying problem that gives rise to the rather puzzling and misleading error message is something wrong with the aes(). I just got the same message when I just forgot to include aes().


text:
Q: ios UIPicker with two options. Want text field to load the value of the first option when the picker is opened I have a UIPickerView combined with a UITextField that allows users to select their gender when signing up for an account. The text field has a placeholder that says "gender" to indicate what that particular text field is for. The issue I am running into is that when the user clicks on the gender bar, the picker shows the first option as being selected (in my case, "male").
I have implemented the didSelectRow delegate that updates the text fields value when a picker row is selected; however, the loading of the picker view does not trigger a selection. meaning if a user wants to select male, they have to scroll to female, then back to male to trigger the selection. Is there a way that when the picker view loads I immediately am able to catch that event and load the first available selection from my picker view?
Is there a better option for showing 2 option selections? The UISegmentedControl feels a bit out of place with the rest of the UI on that page.
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

// The number of rows of data
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
    return self.genderData.count;
}

 // The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:    (NSInteger)component
{
    return self.genderData[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.genderField.text = self.genderData[row];
}


text:
Q: Divide $x=123456$ into three factors $x=uvw$ such that $uv^iw$ is divisible by 3 I have the problem of dividing the string 123456 into three factors uvw that such $uv^iw$ as a number is divisible by three, where $\left|uv\right|\le4$ and $\left| v\right|>0$, i.e. the factors u and v should together only be 4 digits long.
I found the answer but just by simply trying out different values. My knowledge in number theory is very limited, I basically just know that a number is divisible by 3 if it contains three in its prime factorization... And I just cannot explain why it is that if I e.g. divide 123456  such that u=12, v=34, w=56 it's the case that for all small values of i, it's the case that $uv^iw$ is divisible by 3: $uv^2w=121156656, uv^3w=123930456, uv^4w=12133633656$ are all divisible by 3, why is that the case?

A: Shouldn't $v^i$ be repetition of $v$, not a power of the number $v$?  That seems more likely since we are talking about strings.  In that case $u=12,v=34,w=56$ is not correct.  The classic divisibility rule says that a number is a multiple of $3$ if and only if the sum of the digits is.  So as long as the sum of the digits in your string is a multiple of $3$, the whole number is.  If the sum of the digits in $v$ is a multiple of $3$, repeating it will not change the status of the number.


text:
Q: Bind form array value in angular reactive form I have a update form in which i want to bind feilds of form array. There are 2 fields in form array. One of them is drop down while the other is text field. I want to make drop down value non editable while input tag value as editable.
here is my component.html
    <hello name="{{ name }}"></hello>
    <form [formGroup]="editForm" (ngSubmit)="onSubmit(editForm.value)">

    Employees

                    Employee Name

                        <select
                      (change)="onChangeEmp($event.target.value)"
                      type="number"
                      class="form-control"
                      formControlName="CoordinateId"
                    >
                      <option hidden value=""
                        >Please Select Employee
                      </option>

                      <option
                        *ngFor="
                          let emp of employeeArray;
                          let empIndex = index
                        "
                        type="number"

                        [ngValue]="
                          empControlElementOfArray(empIndex).get(
                            'CoordinateId'
                          ).value
                        "
                      >
                        {{ emp.CoordinateName }}
                      </option>

                    </select>

                    Age

                        <input

                      name="nnnn"
                      type="text"

                      onkeypress="return (event.charCode !=8 && event.charCode ==0 ||
                  (event.charCode >= 48 && event.charCode <= 57))"
                      formControlName="Age"
                      class="form-control"
                      placeholder="Please Enter Age"
                    />

                            <button
                      type="button"
                      *ngIf="
                        editForm.get('CoordinatesInfo')[
                          'controls'
                        ]
                      "
                      (click)="deleteRow(i)"
                      class="a-btns btn btn-success tab-btn"
                    >Delete

                    </button>

                    <button
                  type="button"
                  (click)="addNewRow()"
                  class="a-btns btn btn-success tab-btn"
                >
                  Add Emp

                </button>

   </form>

here is my component.ts file
   editForm: FormGroup;
   constructor(
   private fb: FormBuilder,
   private http: HttpClient,
   private router: Router,
   private route: ActivatedRoute
 ) {}

response = {
Id: 73,
EmpName: "Rajesh",
CoordinatesInfo: [
  { CoordinateId: 36, CoordinateName: "Nisha", Age: 25 },
  { CoordinateId: 37, CoordinateName: "nidhi", Age: 29 }
]
};

ngOnInit() {
this.editForm = this.fb.group({
  CoordinatesInfo: this.fb.array([])
});
this.empInfo();
}
empInfo() {
console.log(this.response);
this.response.CoordinatesInfo = this.response.CoordinatesInfo.map(el => {
  var o = Object.assign({}, el, { isdisabled: true });
  this.employeeArray.push(
    this.initPrefilledEmpRow(el.CoordinateId, el.Age)
  );
  console.log(this.employeeArray);
  return o;
});
}

initBlankEmpRow() {
return this.fb.group({
  CoordinateId: [""],
  Age: ["", [Validators.required]]
});
}

initPrefilledEmpRow(CoordinateId: number, Age: number) {
return new FormGroup({
  CoordinateId: new FormControl({
    value: CoordinateId,
    Validators: Validators.required,
    disabled: true
  }),
  Age: new FormControl({
    value: Age,
    Validators: Validators.required,
    disabled: true
  })
});
}

 get employeeArray(): FormArray {
const name = this.editForm.get("CoordinatesInfo") as FormArray;

return name;
 }

 empControlElementOfArray(index: number) {
const arrayElem = this.employeeArray.get(index.toString()) as FormGroup;
return arrayElem;
}

initItemRows() {
return this.fb.group({
  CoordinateId: [""],
  Age: ["", [Validators.required]]
 });
 }

addNewRow() {
this.employeeArray.push(this.initItemRows());
}
deleteRow(index: number) {
this.employeeArray.removeAt(index);
}

Here is my stackblitz link
https://stackblitz.com/edit/angular-nfmavt?file=src/app/app.component.ts
I don't know where i am missing. Am i doing something wrong?

A: You can use the property disabled to make the select disable. In your example:
                  <select
                      (change)="onChangeEmp($event.target.value)"
                      type="number"
                      class="form-control"
                      formControlName="CoordinateId"
                      [attr.disabled]="true"
                    >

You can change the "true" value for a variable and you can control the disable of this field.

A: You can disable the field when creating the form group.
Eg:
initItemRows() {
return this.fb.group({
  CoordinateId: { value: "", disabled: true },
  Age: ["", [Validators.required]]
 });
 }


text:
Q: Oracle insert from function I am converting SQL Server stored procedures to Oracle. In SQL Server you can insert into a table from a function call.
Here is the SQL Server:
INSERT INTO t_tmpl( rel_class_code, rel_side, template_id, template_name, template_desc )
SELECT rel_class_code, ls_rel_side, obj_id, name, description
FROM etmf_get_templates_for_rel( ps_rel_class_code, ls_rel_side, pi_called_by )

The error message I get when converting this to Oracle is "PL/SQL: ORA-00933: SQL command not properly ended".
Does anyone know what this statement should look like in Oracle?
Thanks!!!

A: If your function returns a pipelined result set you just need to put the function inside TABLE as follows:
INSERT INTO t_tmpl
   (rel_class_code, rel_side, template_id, template_name, template_desc)
   SELECT rel_class_code, ls_rel_side, obj_id, name, description
   FROM TABLE(
      etmf_get_templates_for_rel(ps_rel_class_code, ls_rel_side, pi_called_by)
      )


text:
Q: Reading a large *.txt file. Why didn't i get the output? Hello all I'm trying to read a large txt file, word by word, then print each word out then continue on with the loop until EOF but I got no output after running this code.  I check everything, file name was correct, the file also in the same folder with my c file. Could anyone please explain what is going on? Thank you. Here is the txt file, and the code:
.txt file
#include <stdio.h>
#include <string.h>

int main(void) {

    FILE *infile;
    char temp_1[25];
    setvbuf(stdout, NULL, _IONBF, 0);

    infile = fopen("LittleRegiment.txt", "r");

    if(infile != NULL) {
        while(fscanf(infile, "%s", temp_1) != EOF) {
            printf("%s ", temp_1);
        }
    } else {
        printf("Couldn't open the file.");
    }

    return 0;
}

A: Try printing the reason for the error.
} else {
    //printf("Couldn't open the file.");
    perror("open file");                 // prototype in <stdio.h>
}


text:
Q: Multiple ifs within list comprehension I've used a list comprehension which is supposed to store keys and values in itemDict variable considering the fact that some items if present in item['keys'] will not be included in itemDict. I've used multiple if conditions to make that possible.
This is what I've tried with:
itemDict = {item['keys']:item['value'] for item in soup.select('input[keys]') if '$cmdPrint' not in item['name'] and 'btnView' not in item['name'] and 'btnMyDoc' not in item['key']}

How can I rewrite those conditions to make it concise?

A: You could use a check function and use all builtin. Also reformat the comprehension for readability.
def check(item):
    return all(('$cmdPrint' not in item['name'],
           'btnView' not in item['name'],
           'btnMyDoc' not in item['key']))

itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if check(item)}

Or use it in the comprehension, but that's one long comprehension.
itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if all(('$cmdPrint' not in item['name'],
                    'btnView' not in item['name'],
                    'btnMyDoc' not in item['key']))}

Or just use a regular for loop:
itemDict = {}
for item in soup.select('input[keys]')
    if check(item):
        itemDict[item['keys']] = item['value']


text:
Q: is Treemap inside ConcurrentHashMap thread safe? I have a case of nested maps as follows:
private final static Map<String, TreeMap<Long,String>> outerConcurrentMap = new ConcurrentHashMap<>();

I know that ConcurrentHashMap is thread safe, but I want to know about the TreeMaps this CHM holding, are they also thread safe inside CHM ?
The operations I am doing are:

*

*If specific key is not found --> create new TreeMap and put against key.

*If key is found then get the TreeMap, and update it.

*Retrieve TreeMap from CHM using get(K).

*Retreive data from TreeMap using tailMap(K,boolean) method.

*clear() the CHM.

I want a thread-safe structure in this scenario. Is the above implementation thread-safe or not? If not then please suggest a solution.

A: Once you've done TreeMap<?, ?> tm = chm.get(key); you are not in thread safe territory any longer. In particular, if another thread updates the treemap (through the CHM or not) you may or may not see the change. Worse, the copy of the map that you have in tm may be corrupted...
One option would be to use a thread safe map, such as a ConcurrentSkipListMap.

A: Simple answer: no.
If your map is a ConcurrentHashMap, then all operations that affect the state of your hashmap are thread-safe. That does not at all mean that objects stored in that map become thread-safe.
How would that work; you create any kind of object, and by adding it to such a map, the object itself becomes thread-safe? And when you remove that object from the map, the "thread-unsafety" is restored?!

A: Assuming you're doing all of this in multiple threads, no, it's not thread-safe.
Ignore the fact that you've accessed the TreeMap via a ConcurrentHashMap - you end up with multiple threads accessing the TreeMap at the same time, including one or more of them writing to the map. That's not safe, because TreeMap isn't thread-safe for that situation:

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

A: Some your scenarios are thread-safe, some are not:
1. Yes this is thread safe though other threads cannot see newly created TreeMap until you put it to CHM. But this should be implemented carefully to avoid race conditions - you should make it sure that checking and insertion are performed atomically:
// create an empty treemap somewhere before
TreeMap<Long, String> emptyMap = new TreeMap<>();
...
// On access, use putIfAbsent method to make sure that if 2 threads
// try to get same key without associated value sumultaneously,
// the same empty map is returned
if (outerConcurrentMap.putIfAbsent(key, emptyMap) == null) {
    emptyMap = new TreeMap<>();
};
map = outerConcurrentMap.get(key);

2, 3, 4. No, you first need to lock this TreeMap by explicit lock or using synchronized. TreeMap is not synchronized by itself.
5. Yes, this is operation is performed on CHM, so it is thread-safe.
If you need fully thread-safe sorted map, use ConcurrentSkipListMap instead. It is slower than TreeMap but its internal structure doesn't need to lock full collection during access thus making it effective in concurrent environment.

A: The TreeMap itself should not be thread safe. Since only the methods of the ConcurrentHashMap are effected.
What you could do is following:
private final static Map<String, SortedMap <Long,String>> outerConcurrentMap= new ConcurrentHashMap<String, SortedMap <Long,String> >();

static {
    // Just an example
    SortedMap map = Collections.synchronizedSortedMap(new TreeMap(...));
    outerConcurrentMap.put("...",map);
}


text:
Q: why does eclipse complain "recursive method loop needs result type"? I am editing following code in eclipse but it complains that "recursive method loop needs result type", so what's the error? Thanks.
package week2

object exercise {
  def factorial(n: Int): Int = {
    def loop(acc: Int, n: Int) =
      if (n == 0) acc
      else loop(acc * n, n - 1)

    loop(1, n)
  }

  factorial(4)
}

Thanks for the answer. Yes, I missed something here. The correct is:
package week2

object exercise {
  def factorial(n: Int): Int = {
    def loop(acc: Int, n: Int): Int =
      if (n == 0) acc
      else loop(acc * n, n - 1)

    loop(1, n)
  }                                               //> factorial: (n: Int)Int

  factorial(4)                                    //> res0: Int = 24
}

A: As sepp2k indicated, it's restricted by compiler. Just wanted to add more info for clarification.
According to Scala's local type inference mechanism

return types of methods can often be omitted since they correspond to the type of the body, which gets inferred by the compiler

Consider non-recursive function
def f(n: Int) = n % 2 == 0

where compiler can infer a result type, since it knows that expression x % 2 == 0 will always produce type Boolean.
But when you deal with a recursive function, like
def f(n: Int) = if (n == 0) 1 else n * f(n-1)

Scala compiler won't infer the result type of if (x == 0) 1 else x * f(x-1) since that leads to an infinite loop. It can't even know that f(x-1) is an eligible operand for * operation, thus will give you an error Cannot resolve reference * with such signature.

A: The rules of the Scala language that any recursive method needs to be declared with a return type. loop is a recursive method and you didn't declare a return type for it (you only declared one for factorial, which doesn't necessarily need one). Therefore scalac (and by extension Eclipse) is telling you that the recursive method loop needs a return type.


text:
Q: Redshift Time Datatype I am trying to create and load a TIME column not unlike other databases to store, only the time.  i.e. 09:30:00, 14:23:16
According to this https://docs.aws.amazon.com/redshift/latest/dg/r_Datetime_types.html  Redshift has a TIME data type.
However trying to use it like the date and timestamp datatypes is proving challenging.
select version();
                                                          version
---------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.18228
(1 row)

-- TimeStamps ------------------------------------------------------------------------
drop table if exists t1;
psql:redshiftTime.sql:4: INFO:  Table "t1" does not exist and will be skipped
DROP TABLE
create table t1 (c1 timestamp);
CREATE TABLE
insert into t1 (select current_timestamp);
INSERT 0 1
insert into t1 values ('2020-03-01 07:30:57.123456');
INSERT 0 1
insert into t1 values ('2020-03-01 07:30:57');
INSERT 0 1

-- Dates -----------------------------------------------------------------------------
drop table if exists t1;
DROP TABLE
create table t1 (c1 date);
CREATE TABLE
insert into t1 (select current_date);
INSERT 0 1
insert into t1 values ('2020-03-01');
INSERT 0 1

-- Times -----------------------------------------------------------------------------
drop table if exists t1;
DROP TABLE
create table t1 (c1 time);   -- FAILS????
psql:redshiftTime.sql:19: ERROR:  Column "t1.c1" has unsupported type "time without time zone".
insert into t1 (select current_time);
psql:redshiftTime.sql:20: ERROR:  relation "t1" does not exist
insert into t1 values ('12:00:00');
psql:redshiftTime.sql:21: ERROR:  relation "t1" does not exist
-- CHAR Woraround ???? ----------------------------------------------------------------
drop table if exists t1;
psql:redshiftTime.sql:25: INFO:  Table "t1" does not exist and will be skipped
DROP TABLE
create table t1 (c1 CHAR(8));
CREATE TABLE
insert into t1 (select current_time);   -- FAILS  - expected due to mismatch data type
psql:redshiftTime.sql:27: INFO:  Function "text(time with time zone)" not supported.
psql:redshiftTime.sql:27: INFO:  Function "timetz(time with time zone,integer)" not supported.
psql:redshiftTime.sql:27: ERROR:  Specified types or functions (one per INFO message) not supported on Redshift tables.
insert into t1 values ('12:00:00'); -- OK
INSERT 0 1
SELECT CAST( current_time AS CHAR(8)); -- OK - automagic substring
  bpchar
----------
 08:42:24
(1 row)

insert into t1 (SELECT CAST( current_time AS CHAR(8))); -- FAILS
psql:redshiftTime.sql:31: INFO:  Function "text(time with time zone)" not supported.
psql:redshiftTime.sql:31: INFO:  Function "timetz(time with time zone,integer)" not supported.
psql:redshiftTime.sql:31: ERROR:  Specified types or functions (one per INFO message) not supported on Redshift tables.
SELECT CAST( current_time AS CHAR(18)); -- OK
       bpchar
--------------------
 08:42:25.411191+00
(1 row)

insert into t1 (SELECT substr(CAST( current_time AS CHAR(18)),1,8)); -- FAILS
psql:redshiftTime.sql:34: INFO:  Function "text(time with time zone)" not supported.
psql:redshiftTime.sql:34: INFO:  Function "timetz(time with time zone,integer)" not supported.
psql:redshiftTime.sql:34: ERROR:  Specified types or functions (one per INFO message) not supported on Redshift tables.

A: My testing matches your findings.
However, while I could not create a column of type TIME, I could cast to TIME:
SELECT NOW()::TIME

09:10:08

However, I was unable to cast a TIMESTAMP table column to TIME. Most strange!


text:
Q: How can we get a URL which is a parameter I am trying to get the URL which is a parameter but unfortunately i get a Forbidden error
Eg: http://project.com/http://google.com
If i put the above url, my parameter should be http://google.com but i am not getting that. I get a Forbidden Error.
The project i am working on is Codeigniter
Here is what i have done for routes
$route['(:any)'] = "mycontroller";

A: You should encode your parameters before using it on GET.
echo 'test';

In that way, there is no conflicts between google vars and yours.
See urlencode() manual for details.


text:
Q: How to forbid create Object via reflection? Prologue
I have a class :
public final class Session {

    private int userId;
    private String token;

    Session(int userId, String token) {
        this.userId = userId;
        this.token = token;
    }

    public String getToken() {
        return token;
    }

    public int getUserId() {
        return userId;
    }
}

As you see, we can create object via reflection.

*

*I know that i can forbid access to constructor via private or package-private modificators.

The goals

*

*Forbid creating of object even via reflection way to preserve security.

*Make access to fill object fields only package-private.

P.S. Maybe it can be complete via OOP/OOD way?

A: On plain Java, install a SecurityManager with a policy describing what you want.
While Android has a SecurityManager class, the docs say not to use it, and I don't think there's any way to do what you want, although I'm also not sure how it makes sense.


text:
Q: django: creating two models depends on each other trying to solve quite simple problem, but I'm a little lost.
class Person(models.Model):
    created_by = models.ForeignKey(User)

class User(models.Model):
    person = models.ForeignKey(Person)

User is user who use system, log in, create persons, etc.
Each Person has info who create it.
Each User should be just one Person also, but able to create unlimited Persons
So the question how to properly create User (on registration) and assign Person?
I can't save Person without user, also can't save User without Person.
I think use person.models.ForeignKey(Person, null=True) in User model is not good design, because User has to have Person.
Any suggestion?
Thank you

A: It looks like User should just inherit from the Person model, since every User is a Person. Incidentally this would also resolve your problem - creating User would create an associated Person automatically.
You should probably read about multi-table inheritance to fully understand how this would work.
Furthermore, the created_by field should have null=True specified, since the first Person wouldn't be created by anyone, so the first object need to have the Null value there.
class Person(models.Model):
    created_by = models.ForeignKey('User', null=True)

class User(Person):
    person = models.ForeignKey('Person')

Also, since you want the User model to by used as the AUTH_USER_MODEL you should read about requirements for such models.


text:
Q: we take safety measures, do we also 'take' control measures? Someone provided me with a PowerPoint presentation and instructed me to convert it into a word document with sentences rather than point form notes. Here is what the PowerPoint slide said:
"Control Measures
-Provide an easy exit
-Wear protective equipment"
The slide talks about what to do when you are working in a tight, enclosed and confied space. Basically, the slide says that when you are working in an enclosed and confined space then 'take' the following control measures: provide an easy exit (that is, make sure it is easy to get out of the enclosed area) and wear protective equipment while working in a confied space.
My question is, does it make sense if I say "When working in a confied and enclosed area, 'take' the following control measures: ensure that there is an easy exit provided to the individual who is working in the confined space, and ensure that the individual working is wearing protective equipment."
Do we 'take' control measures, just as how we take safety measures? If no, what is the correct way of saying what I said in the paragraph above?
Note: I do know that the 'control' measures stated above are really just safety measures, but I'm just wondering if we 'take' control measures like how we take safety measures.

A: There is no reason why the expression take measures (take action to achieve a particular purpose) cannot take a modifying adjective. Take (adj) measures should work with any adjective. (If a word modifies a noun, it is an adjective.) So Take control measures is okay.


text:
Q: How to find element in specific context using DOMXPath in php? I'm trying to parse a xml file with information about some users. Something like this
users.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <name>Alexander</name>
        <email>alexander@test.com</email>
    </user>
    <user>
        <name>Tyler</name>
        <email>tyler@test.com</email>
    </user>
</users>

I'm using DOMXpath to extract all users inside this xml, and all of this fields.
In xml file, I have 15 users and when I search all fields about one user in this code
$username = $xpath->query ( '//email', $users->item(0) );

I got 15 length, instead of 1. I mean query is searching in all xml instead of looking for the actual user.
What I'm doing wrong?
xml_query.php
$xml = new DOMDocument();
$xml->loadXML( $xml_content );
$xpath = new DOMXPath($xml);

$users = $xpath->query( '//user' );
var_dump( $users->item(0) );
$username = $xpath->query ( '//email', $users->item(0) );

var_dump( $username );

A: Because //email select all  elements in the document but you need to select elements within the current context. Remove // from query expression.
$username = $xpath->query ( 'email', $users->item(0) );

See result in demo

A: A slash (/) at the start of an location path makes it relative to the document node. The context node will be ignored. If it is followed by another slash, it uses the descendant axis. //email is short for /descendant::email. The default axis is child.
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <name>Alexander</name>
        <email>alexander@test.com</email>
    </user>
    <user>
        <name>Tyler</name>
        <email>tyler@test.com</email>
    </user>
</users>
XML;

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate('//user') as $user) {
  var_dump($xpath->evaluate('string(email)', $user));
}

Output:
string(18) "alexander@test.com"
string(14) "tyler@test.com"

DOMXpath::evaluate() can return node lists or scalars depending on the expression. It allows you to cast the nodes to string directly in the Xpath expression.
Xpath expression can contain conditions so to output the email by position you could do something like:
foreach ($xpath->evaluate('//user[2]') as $user) {
  var_dump($xpath->evaluate('string(email)', $user));
}

Output:
string(14) "tyler@test.com"


text:
Q: Blacklist (variable) not working discord.py I just made blacklist in my bot, and still I can use bot even though I blacklisted myself. This is my code:
BLACKLIST = ["my ID"]

@bot.command()
async def testblacklist(ctx):
  if ctx.author.id in BLACKLIST:
    await ctx.send("U r on blacklist!")
  else:
    await ctx.send("Test")

Can anyone help me with this? There aren't any errors in console and bot sends "Test"

A: That's because in BLACKLIST your id is a str and ctx.author.id is int. You have 2 options:

*

*replace:

if ctx.author.id in BLACKLIST:

with:
if str(ctx.author.id) in BLACKLIST:

*Put int as your id in BLACKLIST


text:
Q: how to query group by and distinct with a limit in MongoDB PHP codeigniter? Is such a operation possible?
sample record:
{
 _id: ObjectId("51d6be147483c58419000002"),
 user: "ashok",
 action: "login",
 time: 1373027860,
 details: {
               user_entries:   "blah..blah",
               url: "web.domain.com"
                 }
 }

Suppose, i want to group by url visited, for each user,
group by url where user = "ashok", limit 10.
I am using AlexBilbie library for MongoDB-Codeigniter (it doesnt have aggregation). so using plain php.
Still even if I could aggregate, how to distinct or limit it?
Any suggestion is welcome.

A: First of all using group_by and distinct together doesn't make any sense. Either you are using group_by or distinct.
If you want to do some kind of pagination for a grouped query you have to use map and reduce or the aggregation pipeline. In your case the aggregation would look like that.
db.users.aggregate(
  { '$match' => { 'user' => 'ashok' } },
  { '$group' => { '_id' => '$details.url' } },
  { '$skip'  => 0 },
  { '$limit' => 10 }
)

I am using this aggregation feature to display references at VersionEye. The aggregation feature allows to do grouping and paging on db level, that's why it's much faster then other ORM or pagination solutions.

A: In the below format you can give a limit:
$this->mongo_db->order_by(array('Student_Name'=>'asc'))->limit(20)->get('mycollection_name');


text:
Q: How to get Unauthenticated identity using Swift I have initialized the credentials provider per this AWS Developer Guide.  I'm not sure if it worked, and how to check.  I can't seem to find any documentation on how to use Cognito with Swift.  I'm running it as a unit test, and the test passes and the line print("identityId", identityId) outputs:
identityId <AWSTask: 0x17d5fde0; completed = NO; cancelled = NO; faulted = NO;>
However, during debug the property identityProvider.identityId is nil.
Here are my files:
// MyAuth.swift

import Foundation
import AWSCognito

class MyAuth {

    func getUnauthCognitoId()->Bool {
        let identityProvider = MyIdentityProvider()
        let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityProvider: identityProvider, unauthRoleArn: Constants.ARNUnauth.value, authRoleArn: Constants.ARNAuth.value)
        let defaultServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)
        AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration

        if let identityId = identityProvider.getIdentityId() {
            print("identityId", identityId)
            return true
        } else {
            return false
        }

    }

}

And
//  MyIdentityProvider.swift

import Foundation
import AWSCognito

class MyIdentityProvider: AWSAbstractCognitoIdentityProvider {
    var _token: String!
    var _logins: [ NSObject : AnyObject ]!

    // Header stuff you may not need but I use for auth with my server
    /*let acceptHeader = "application/vnd.exampleapp-api+json;version=1;"
    let authHeader = "Token token="
    let userDefaults = NSUserDefaults.standardUserDefaults()
    let authToken = self.userDefaults.valueForKey("authentication_token") as String*/

    // End point that my server gives amazon identityId and tokens to authorized users
    let url = "https://api.myapp.com/api/amazon_id/"

    func authenticatedWithProvider()->Bool {
        if let logins = _logins {
            return logins["ProviderName"] == nil
        }
        else {
            return false
        }
    }

    override var token: String {
        get {
            return _token
        }
    }

    override var logins: [ NSObject : AnyObject ]! {
        get {
            return _logins
        }
        set {
            _logins = newValue
        }
    }

    override func getIdentityId() -> AWSTask! {
        if self.identityId != nil {
            return AWSTask(result: self.identityId)
        }
        else if(!self.authenticatedWithProvider()) {
            return super.getIdentityId()
        }
        else{
            return AWSTask(result: nil).continueWithBlock({ (task) -> AnyObject! in
                if self.identityId == nil {
                    return self.refresh()
                }
                return AWSTask(result: self.identityId)
            })
        }
    }

    override func refresh() -> AWSTask! {
        let task = AWSTaskCompletionSource()
        if(!self.authenticatedWithProvider()) {
            return super.getIdentityId()
        }
        else {
            // TODO: Authenticate with developer
            return task.task
        }
        /*let request = AFHTTPRequestOperationManager()
        request.requestSerializer.setValue(self.acceptHeader, forHTTPHeaderField: "ACCEPT")
        request.requestSerializer.setValue(self.authHeader+authToken, forHTTPHeaderField: "AUTHORIZATION")
        request.GET(self.url, parameters: nil, success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
            // The following 3 lines are required as referenced here: http://stackoverflow.com/a/26741208/535363
            var tmp = NSMutableDictionary()
            tmp.setObject("temp", forKey: "ExampleApp")
            self.logins = tmp

            // Get the properties from my server response
            let properties: NSDictionary = response.objectForKey("properties") as NSDictionary
            let amazonId = properties.objectForKey("amazon_identity") as String
            let amazonToken = properties.objectForKey("token") as String

            // Set the identityId and token for the ExampleAppIdentityProvider
            self.identityId = amazonId
            self._token = amazonToken

            task.setResult(response)
            }, failure: { (request: AFHTTPRequestOperation!, error: NSError!) -> Void in
                task.setError(error)
        })*/
        return task.task
    }
}

And
import XCTest
@testable import My

class MyTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock {
            // Put the code you want to measure the time of here.
        }
    }

    func testGetUnauthCognitoId() {
        let myAuth = MyAuth()
        XCTAssertTrue(myAuth.getUnauthCognitoId())
    }

}

A: It turns out that if you create a default service configuration within the application:didFinishLaunchingWithOptions: application delegate method in your app delegate file as described here:
let credentialsProvider = AWSCognitoCredentialsProvider(
        regionType: AWSRegionType.USEast1, identityPoolId: cognitoIdentityPoolId)

let defaultServiceConfiguration = AWSServiceConfiguration(
        region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)

AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration

The SDK will use an unauthenticated identity whenever you try to use any of the AWS services, and you don't necessarily need to create a cognitoIdentity object.

A: getIdentityId returns an AWSTask. Since AWSTask is essentially BFTask with a different name, you can get the identityId using the continueWithBlock syntax shown on the BFTask page. Something like:
credentialProvider.getIdentityId().continueWithBlock {
    (task: AWSTask!) -> AWSTask in
    if task.error() {
        // failed to retrieve identityId.
    } else {
        print("identityId", task.result())
    }


text:
Q: How to change default stylesheet rules order in Internet Explorer Developer Tools One reason why I don't use Internet Explorer for web development is the way it supports CSS attribute manipulation: it lists the most general stylesheet attributes first. When there's a lot of the stylesheet rules you have to scroll down - which is most of the time.
Is there a way to change that order ? So it list the most specific style rules first just like Firefox in firebug and Chrome do ?

A: Try with IE tester. www.my-debugbar.com/wiki/IETester/HomePage.
You also need to install debug toolbar for IE tester http://www.debugbar.com/download.php.
This tool will give you what you need.


text:
Q: libgdx GWT. Create Texture from url I need help.
I need display jpg image from url.
Desktop version work fine
byte[] imgBytes
new Pixmap(imgBytes, 0, imgBytes.length)

But it is not work in GWT project.
I try this solution "Tainted canvases may not be loaded" Cross domain issue with WebGL textures
public void downloadPixmap(final String url, final DownloadPixmapResponse response) {
    final RootPanel root = RootPanel.get("embed-html");
    final Image img = new Image(url);
    img.getElement().setAttribute("crossOrigin", "anonymous");
    img.addLoadHandler(new LoadHandler() {

        @Override
        public void onLoad(LoadEvent event) {
            HtmlLauncher.application.getPreloader().images.put(url, ImageElement.as(img.getElement()));
            response.downloadComplete(new Pixmap(Gdx.files.internal(url)));
            root.remove(img);
        }
    });
    root.add(img);
}

interface DownloadPixmapResponse {
     void downloadComplete(Pixmap pixmap);
     void downloadFailed(Throwable e);
}

but it is work only in Chrome browser. It is not work in Mozilla Firefox.
Help me please

A: Problem was in url. Some url do not have header
Access-Control-Allow-Origin *
That is why images do not display. I fix this using nginx.
Here link to my settings, my problems  and ansvers
https://serverfault.com/questions/816080/nginx-proxy-pass-regexp-to-another-domain


text:
Q: $C_c^{\infty}(\mathbb R^n)$ is dense in $W^{k,p}(\mathbb R^n)$ As the title say, I want to prove that  $C_c^{\infty}(\mathbb R^n)$ is dense in $W^{k,p}(\mathbb R^n)$
i.e.  $\displaystyle{ W^{k,p} (\mathbb R^n) = W_0^{k,p}(\mathbb R^n)  \quad (\star)}$.
In a book I found that in order to prove it, we need the following claim:
Claim: Let $\displaystyle{\zeta \in C^{\infty} ([0, \infty)) }$ such that $\zeta (t)  =1 $ for $ t \leq 1 $ and $\displaystyle{ \zeta (t) =0 }$ for $ t \geq 2$. For $R>0$ and  $x \in \mathbb R^n$ define $\displaystyle{ \eta_R (x) = \zeta \left( \frac{|x|}{R} \right)}$. If $ \displaystyle{ u \in W^{k,p} ( \mathbb R^n) }$ with $1 \leq p < \infty $ then, $\displaystyle{ \eta_R u \to u }$ in $W^{k,p}(\mathbb R^n) $ as $ R \to \infty$.
If I prove the claim then the $(\star)$ follows using mollifiers. But unfortuently I have stuck, with the proof of the claim.
Any ideas?

A: It may help to consider first the case $n=1$ and $k=2$. The fact that $\eta_Ru\to u$ in $L^p$ follows from a monotone convergence argument. Indeed, since $\eta_R(x)=1$ if $|x|\leqslant R$,
$$\int_\mathbb R|\eta_R(x)u(x)-u(x)|^p\mathrm dx=\int_{\{|x|\gt R\}}|u(x)|^p\mathrm dx.$$
We can use the product rule for derivatives: we get $(\eta_R u)'=\eta_R u'+\eta'_Ru$. The first terms goes to $u'$ by a similar argument as before. For the second one, there is a term $\frac 1R$ which appears when we take the derivative. Since the derivative of $\eta$ is bounded, the light version of the claim follows.
For the general case, we have to consider Leibnitz rule. It's the same idea, altought it's more technical. We shall need that each derivative of $\eta$ is bounded.


text:
Q: java.lang.UnsatisfiedLinkError in java.lang.Runtime.loadLibrary from Market by Android version
Android 2.3.3 - 2.3.7 385 65.5%
Android 4.2 155 26.4%
Android 4.3 28 4.8%
Android 4.0.3 - 4.0.4 20 3.4%

*

*by device
Optimus L3 (e0) 118 20.1%
Xperia L (C2104) 93 15.8%
hsdroid 72 12.2%
java.lang.ExceptionInInitializerError
at com.android.XXX.MakeupApp.a(Unknown Source)
at com.android.XXX.al.run(Unknown Source)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.UnsatisfiedLinkError: Couldn't load arcsoft_hairsalon from loader   dalvik.system.PathClassLoader[dexPath=/data/app/com.android.XXX-     1.apk,libraryPath=/data/app-lib/com.android.XXX-1]: findLibrary returned null
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:535)
 at com.meiren.FlawlessFace.FlawlessFaceLib.<clinit>(Unknown Source)
 ... 3 more
I don't known why some devices and android version can occurs some problems!
But I test some devices(included armV6 or armV7) ,not appera this problem.

A: I got same issue, and looking hard for solution. I found one, in chromium, but its not looking well. Anyway, i hope it helps you.
try {
        System.loadLibrary("YourLib");
    } catch (UnsatisfiedLinkError e) {

        System.load("YourLibPath");
    }

A: It seems that you are using a library (arcsoft_hairsalon?) that can't be found during runtime.
We had this kind of problems before (using a haptics library in our project) that we could solve including the ".so" library not only into the libs/ folder but also into libs/armeabi/ and libs/armeabi-v7a/
Currently we are facing this issue only with the Xperia L. As soon as I find the solution I'll let you know.
I hope this helps!
EDIT
Have you tried this solution? https://stackoverflow.com/a/17131418/1658749 Maybe it works for you. With this solution you would be creating a bundled jar file containing the .so files. Maybe that helps (not in my case but....)


text:
Q: Jest: Testing a nested promise I'm new to jest, and having trouble determining how to test results nested inside promises. Specifically:
myMethod: function (e) {
  let self = this
  self.resetErrors()

  Parser.parseFile(this.form.uploadFile).then(res => {
    const hasErrors = self.validFile(res)
    if (!hasErrors) {
      self.processFile(res)
    }
  })
}

I'd like to test to ensure that, assuming hasErrors is false,  self.processFile fires. Here's my current (failing) best effort:
describe("if the provided data is valid", () => {
  it('runs processFile', () => {
    const mockProcessFile = jest.fn()
    mockParser = jest.fn(() => {
      new Promise((resolve, reject) => {
        return ValidMockData
      }).then((loanData) => {
        expect(mockProcessFile).toBeCalled()
      })
    })

    CsvParser.parseFile = mockParser

    wrapper.vm.validFile = jest.fn(true)
    wrapper.vm.processFile = mockProcessFile
    wrapper.vm.store().resolve((data) => {
      expect(mockProcessFile).toBeCalled()
    })
  })
})

At present I'm getting a Cannot read property 'then' of undefined error - which makes sense, but I'm not sure how exactly I'm supposed to crack into expectations inside of a then() call. Any thoughts appreciated

A: You need to store the Promise you create in the test so you can use await to let the test finishing after it was resolved:
describe("if the provided data is valid", async() => {
  it('runs processFile', () => {
    const mockProcessFile = jest.fn()
    const p = Promise.resolve(ValidMockData)
    CsvParser.parseFile = jest.fn(() => p)

    wrapper.vm.validFile = jest.fn(true)
    wrapper.vm.processFile = mockProcessFile
    wrapper.vm.store()

    await p

    expect(mockProcessFile).toBeCalled()
    expect(mockProcessFile).toBeCalled()

  })
})


text:
Q: In how many ways can $3$ ladies and $3$ gentlemen be seated around a round table so that any two and only two of the ladies sit together?
Q) In how many ways can $3$ ladies and $3$ gentlemen be seated around a round table so that any two and only two of the ladies sit together?

Answer given- $72$
My answer - $108$
My Approach-
Number of required ways= total number of ways of seating two women adjacent - number Of ways of seating $3$ women adjacent.
$3C2 \cdot 2 \cdot 4!-3C3 \cdot 3! \cdot 3! =144-36=108$
Where am I going wrong?

A: HINT:
Try thinking about this as follows
Two woman will sit next to eachother:
$$
WW
$$
this can be done in $\binom{3}{2}\cdot 2$ different ways.
Next to them on both sides we will need men
$$
MWWM
$$
this can again be done in $\binom{3}{2}\cdot 2$ different ways.
Can you figure the rest out?

A: Method 1:  We subtract the number of arrangements in which no two women sit together and in which all three women sit together from the total number of arrangements of six people at a round table.
Suppose Alexander is one of the men.  Seat him.  Since only the relative order of the people matters, it does not matter where Alexander sits.  The other five people can be seated in $5!$ orders as we proceed clockwise around the table from Andrew.
If none of the women sit together, the men and women must alternate.  Again, we seat Alexander first.  Seating him determine which seats will be occupied by the men and which will be occupied by the women.  The other two men can be seated in $2!$ ways as we proceed clockwise around the table from Alexander.  The three women can be seated in $3!$ ways as we proceed clockwise around the table from Alexander.  Thus, there are $2!3!$ seating arrangements in which no two women sit together.
For arrangements in which all three women sit together, we again seat Alexander first.  We have three objects to arrange relative to Alexander, the other two men and the block of three women.  The objects can be arranged in $3!$ ways as we proceed clockwise around the table relative to Alexander.  The women within the block can be arranged in $3!$ orders.  Hence, there are $3!3!$ ways the men and women can be seated if all the women sit together.
Thus, there are $5! - 2!3! - 3!3!$ admissible arrangements.
Method 2:  We correct your count.
We seat Alexander first.  We have four objects to arrange relative to Alexander, the block of two women and the other three people.  Choose which two of the three women form the block, which can be done in $\binom{3}{2}$ ways.  The four objects can be arranged in $4!$ ways as we proceed clockwise around the table from Alexander. The two women in the block can be arranged in $2!$ ways.  Hence, there are $\binom{3}{2}4!2!$ ways in which at least two women sit together, as you correctly calculated.
However, we have counted each arrangement in which all three women sit together twice, once for the first two women we encounter as we proceed clockwise around the table from Alexander and once when we encounter the last two women as we proceed clockwise around the table from Andrew.  Since we want the number of arrangements in which exactly two women sit together, we do not want to count these arrangements at all.  Therefore, we must subtract twice the number of arrangements in which all three women sit together.
As shown above and as you correctly calculated, there are $3!3!$ arrangements in which all three women sit together.  Hence, there are
$$\binom{3}{2}4!2! - 2 \cdot 3!3!$$
admissible seating arrangements.
Method 3:  We do a direct count.
Seat Alexander.  We then ask the women to wait while we seat the other two men.  Relative to Alexander, they can be seated in $2!$ ways as we proceed clockwise around the circle relative to Alexander.  This creates three spaces, one to the left of each man, in which the women can be seated.  Choose which two of the three women sit together, which can be done in $\binom{3}{2}$ ways.  Choose in which of the three spaces these women sit, which can be done in $\binom{3}{1}$ ways.  Arrange the two women in that space, which can be done in $2!$ ways.  Choose in which of the two remaining spaces between two men the other woman sits, which can be done in $\binom{2}{1}$.  Therefore, there are
$$2!\binom{3}{2}\binom{3}{1}2!\binom{2}{1}$$
admissible seating arrangements.


text:
Q: How to "Allow service to interact with desktop" for a web service? I'm trying to run some applications through a web service that I wrote. I've given necessary user permissions, but I still cannot see any user interface of the started applications, even though I know that they are running because they are listed in Task Manager.
When I looked into this issue I came up with one solution which is: enabling the "Allow service to interact with desktop" checkbox. But when I looked for my service in Services I could not find it running there. I don't even know what my service's name is: could anyone help me with this?
Does my web service turn into a windows service while it is running?
If it doesn't how can I find it?

A: Your web service is not a "Service" which will appear in Services - those are Windows Services... very different concept.
You can't have a web service "interacting with the desktop" on the server unless the service host process has access to the interactive user's Window Station. This is impossible with an ASP.NET web service, which is hosted by IIS and will be running in a separate session with a non-interactive Window Station.
If you instead implement the web service using WCF, hosting it in an application run by a logged in interactive user, you might get round the security obstacles which prevent the started applications showing a visible UI.
However, I don't know what you mean by "a system controlled over a web site": that sounds like the kind of thing which needs IIS and shouldn't be run by an interactive user - so you may run into other problems. If you explain in more detail what you are trying to do there are probably better solution architectures we could suggest.


text:
Q: How did the term 'buff' originate? I was interested in learning that the term 'nerf' originated from Nerf gun toys. The opposite of nerf is buff, but I have found no information on the origin of it.
In the video game community, how did the term 'buff' originate?

A: Here's anarchy online Nov 2001 with "I watched MA get buffed.. then nerfed".
Before "Buff" was the opposite of "Nerf", "Buff" was the opposite of "Debuff".  I learned of the word buff in everquest(1999).  Primarily the word was used to describe spells that one character would cast to enhance another.  Examples are, the shaman run speed buff (SoW) or the enchanter mana regen buff (Clarity).
There are certainly older references than this - reaching into MUDs, MOOs and penAndPaper games.
Since the word was in use as a temporary improvement mechanic in games, it is sensible that it was later picked up to describe dev changes which are considered improvements.

A: The English Stack Exchange does a good job explaining the history of this word.
The word "buff" also means to polish something and make it more attractive.  Keeping that in mind, when you buff a character in a video game, you're "polishing" them up, get it?

A: I am not sure of the exact origins of the word "buff" as it applys to gaming. However, I can say when and where I personally heard "buff" and "nerf" used in a gaming context. I first heard about "nerf" when reading an Ultima Online forum post in the late 90s, regarding a balancing change effecting some weapons. The forum poster stated they might as well be fighting with Nerf bats.
I first heard the word "buff" while playing Everquest. There was a low level spell which would increase the strength stat. When the spell was applied, there was an icon of a big, bulging bicep on your screen. Some players said "I will buff you up" or some reference like that while casting it in the first weeks since the game's release. I am not sure why, but I just went with it. Soon the term was applied to everything which caused a stat increase, or benefit. Soon after, I heard debuff when refering to spells which lowered something's fighting stats.


text:
Q: tmux force kill session (non graceful) I'm running number of java services in linux via tmux sessions
each service has its own session.
To kill a service i use this
tmux kill-session -t $servicename

Some services (java) go nuts when attempting to kill them gracefully.
I believe this sends a signal that allows application to shut down gracefully.
Is there a way to send a similar command via tmux or to tmux such that application  is terminated ungracefully?


text:
Q: Billing Cycle Date Range Code:
DECLARE @CurrentDate DATE = '2018-01-02' ;  -- Can be any date. This is just a date I used as an anchor point.
DECLARE @BillingDayOfMonth INT = 31 ;       -- The day of the billing every month (can be between 1st and 31st of the month).

;WITH [TT1] ( [N] ) AS
    (
        SELECT  1
        UNION ALL
        SELECT  1
    )
    , [TT2] ( [N] ) AS
    (
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
    )
    , [TT] ( [N] ) AS
    (
        SELECT      ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL ) )
        FROM        [TT1] [T1]
        CROSS JOIN  [TT2] [T2]
    )
SELECT  [N]
FROM    [TT] ; -- This gives me the count of 12 cycles (can vary).

Goal:
To return current and X number of previous billing cycle dates (12 cycles total in the above example).
If the BillingDayOfMonth doesn't exists in a month (i.e. 29th to 31st depending on the month), choose the last day of the month as the BillingDayOfMonth. So if BillingDayOfMonth = 31st, this day doesn't exist in Nov. So The Cycle will start @11/30 instead of 11/31. The above code is incomplete and need your help figuring out an efficient solution. Thank you
Desired Output:
CycleStartDate  CycleEndDate
2017-12-31      2018-01-30      -- The most current cycle
2017-11-30      2017-12-30
2017-10-31      2017-11-29
2017-09-30      2017-10-30
2017-08-31      2017-09-29
2017-07-31      2017-08-30
2017-06-30      2017-07-30
2017-05-31      2017-06-29
2017-04-30      2017-05-30      -- Notice the EndDate
2017-03-31      2017-04-29      -- Notice the EndDate
2017-02-28      2017-03-30      -- Notice the StartDate
2017-01-31      2017-02-27      -- Notice the EndDate

A: So based on your numbers table approach and your rules, you can use a query like below.
I tested this for  @BillingDayOfMonth values like 25, 28, 30 and found results reasonably true.
See live demo
DECLARE @CurrentDate DATE = '2018-01-02' ;  -- Can be any date. This is just a date I used as an anchor point.
DECLARE @BillingDayOfMonth INT = 31 ;       -- The day of the billing every month (can be between 1st and 31st of the month).
DECLARE @StartDate DATE
SET @StartDate=   CASE WHEN
                       DAY(EOMONTH(@CurrentDate)) < @BillingDayOfMonth
                       THEN
                       EOMONTH(@CurrentDate)
                       ELSE
                       DATEFROMPARTS(YEAR(@CurrentDate),MONTH(@CurrentDate),@BillingDayOfMonth)
                   END

;WITH [TT1] ( [N] ) AS
    (
        SELECT  1
        UNION ALL
        SELECT  1
    )
    , [TT2] ( [N] ) AS
    (
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
        UNION ALL
        SELECT  1
    )
    , [TT] ( [N] ) AS
    (
        SELECT
        ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL ) )

        FROM        [TT1] [T1]
        CROSS JOIN  [TT2] [T2]
    )

SELECT  CycleStartDate  =
                    DATEADD(M,-N,@StartDate)
        ,
        CycleEndDate    =
                    DATEADD(D,-1,DATEADD(M,1-N,@StartDate))

FROM    [TT] ;


text:
Q: How to use matplotlib to draw multiple cylinders in one drawing? enter image description here
I saw such a formal presentation of results in a paper.
I tried to use matplotlib to achieve the same effect, but failed. This is my code.
x1 = [
        [350, 100, 80, 1000],
        [200, 600, 150, 800],
        [600, 150, 100, 500],
        [450, 800, 75, 1000],
        [680, 400, 120, 500],
        [850, 600, 70, 750],
        [150, 250, 80, 1000],
        [750, 800, 100, 1000]
]

threats = np.asarray(x1)

def create3DEnvironment(threats):
    fig = plt.figure()

    ax = fig.add_subplot(projection='3d')

    counts = len(threats)

    us = np.linspace(0, 2 * np.pi, 20)
    for i in range(0, counts):
        x = threats[i, 0]
        y = threats[i, 1]
        r = threats[i, 2]
        h = threats[i, 3]

        zs = np.linspace(0, h, 30)
        us, zs = np.meshgrid(us, zs)
        xs = r * np.cos(us) + x
        ys = r * np.sin(us) + y
        ax.plot_surface(xs, ys, zs, cmap='Blues', alpha=0.8)
    plt.show()

The error message is as follows
numpy.core._exceptions._ArrayMemoryError: Unable to allocate 14.8 MiB for an array with shape (3, 648002) and data type float64

I'm not sure what's going on.
Could someone please provide me with any ways or information?
I much appreciate your time and help.


text:
Q: Find the variables that contribute the most into group variances I have two groups with different numbers of observations. Here is the toy example:
obs1_1 <- c(1,0,13,5,0,2,6,7,0,2)
obs2_1 <- c(0,0,13,0,0,2,1,0,4,3)
obs3_1 <- c(2,1,10,5,8,4,6,5,1,2)
obs4_1 <- c(1,0,13,4,0,2,6,7,0,2)
obs5_1 <- c(0,1,13,0,4,4,1,0,4,3)

group1 <- data.frame(obs1_1, obs2_1, obs3_1, obs4_1, obs5_1)
rownames(group1) <- c("var1", "var2", "var3", "var4", "var5", "var6", "var7", "var8", "var9", "var10")

obs1_2 <- c(11,1,11,5,0,2,6,7,0,2)
obs2_2 <- c(11,1,11,0,0,1,1,0,4,1)
obs3_2 <- c(11,1,10,1,8,1,1,5,1,2)
obs4_2 <- c(11,1,13,4,0,2,6,0,0,2)
obs5_2 <- c(10,0,13,0,3,0,1,0,4,3)
obs6_2 <- c(10,1,13,2,0,4,1,3,4,3)

group2 <- data.frame(obs1_2, obs2_2, obs3_2, obs4_2, obs5_2, obs6_2)
rownames(group2) <- c("var1", "var3", "var4", "var5", "var7", "var8", "var11", "var12", "var13", "var14")

All the values are continuous and I don't think they are normally distributed. Also, not all the variables present in both groups.
I am thinking to use Wilcoxon sum rank test to analyze differences between the groups. But I am confused how to do it in R as I have too many variables.
How to find the variables that contribute the most into group variances? In this toy example, variables var1, var3, and var4 have the biggest difference between group. So, I guess, they should be the ones that contribute to the groups variance. Plus those that present in just one group.

A: You can merge both data frames and do a loop like this:
library(dplyr)

# Transposing the dataframes

g1 <- as.data.frame(t(group1))
g2 <- as.data.frame(t(group2))

# Melting to have a variable  and value columns

g1 <- reshape2::melt(g1, measure = colnames(g1))
g1$group <- "g1"

g2 <- reshape2::melt(g2, measure = colnames(g2))
g2$group <- "g2"

# Binding both groups

df <- rbind(g1, g2)

# Creating an empty list for output

wsr <- list()

for (i in unique(df$variable)) {
  d <- df %>% filter(variable == i)
  wsr[[i]] <- ifelse(length(unique(d$group)) == 2,
                      wilcox.test(value~group, data = d),
                     NA)

}

# If you just need the p.value

wsr_p <- data.frame(matrix(nrow = 0, ncol = 2))

for (i in unique(df$variable)) {
  d <- filter(df, variable == i)
  s <- ifelse(length(unique(d$group)) == 2,
                     wilcox.test(value~group, data = d)[["p.value"]],
                     NA)
  wsr_p <- rbind(wsr_p, data.frame(variable = i, p = s))

}

wsr_p

variable           p
1      var1 0.006349039
2      var2          NA
3      var3 0.004390260
4      var4 0.007135044
5      var5 0.847768887
6      var6          NA
7      var7 0.156039402
8      var8 0.516063755
9      var9          NA
10    var10          NA
11    var11          NA
12    var12          NA
13    var13          NA
14    var14          NA


text:
Q: Why android 7 local storage is smaller than the android version before? I tried to test the size of local storage on android 7, why the limit is very small only 2.49 M, much different with android 6 has a larger that is 4.98 M? Please, I need answer for this backwardness?
Reference: http://dev-test.nemikor.com/web-storage/support-test/

Update: 2017-06-24


text:
Q: Definition of connection 1-forms - when we write $A(X^\#)=X$, is $A(X^\#)$ meant to be constant? Let $A$ be a connection $1$-form on a principal $G$-bundle and $X\in\mathfrak{g}$.
By the definition of connection $1$-forms, $A(X^\#)=X$. However, $A(X^\#)\in C^\infty(P,\mathfrak{g})$, so the equation doesn't make sense. Is $A(X^\#)$ assumed to be constant? That is, $$A(X^\#)_p=X$$ for all $p\in P$?


text:
Q: Serial port comms only working in one direction I am working with a SOM mounted on a carrier board running Ubuntu 14.04 with the generic 3.13 kernel.
While testing out the peripherals, I hit a problem with serial communication.
Basically, I can transmit data from the custom platform to an external Linux machine, but I can not properly receive data from the external Linux machine to the custom platform.
Through my research I have messed with all sorts of BIOS settings, baud rates, hardware flow control, parity, etc. Nothing has worked. Most info I have found online just says "Make sure your baud rates and other settings match", and they do. It is not my first time working with Linux serial ports. But it is my first time encountering a problem like this.
Does anyone have any suggestions, recommendations, or has anyone ever seen an issue like this before?
More info: We are running a quad-core Intel Atom micro with a custom serial breakout interface. The serial port is at /dev/ttyS0.
EDIT (clarification):
If I set up a session in Picocom or Minicom, I can send characters from our custom platform (running Ubuntu 14.04) to another Linux PC (also running Ubuntu 14.04). However, if I try to send characters from the Linux PC to our custom board, I sometimes get nothing, and other times get unrecognized characters (they show up as bubbles with question marks in them).
I can also simply echo a string to /dev/ttyS0 on the custom platform and receive it on the Linux PC. I just can't get it to work the other way around.


text:
Q: Как из Range выбрать максимальное значение? Проблемка скорее всего легкая но застрял....помогите кто чем может. Логической цепочкой- ссылкой-куском кода :)
Задача:
Есть масив данных вытащеных из SAP - куча инфы\цена\дата

Нужны самые последние цены для продукта
1) нашел сходство что самая свежая цена имеет самую высокую цифру в конце;
2) вытащил из \кучи инфы\последнюю цифру;
3) сделал Range котор опр максимальное значение и понял что в тупике(;
4) как перейти на следующий Range? - на скрине зеленый;
5) чтобы в результате к колонке К была цена - на скрине синим;
6) в колонке J могут быть пустые ячейки (когда макрос хочет взять последнее значение -показывается ошибка на которой он просто выполняет цикл дальше).
Куда копать дальше?
\Ссылка на код: введите сюда описание ссылки

Sub ss()
Dim str, str2 As String
Dim lowmin As Integer
Dim w, lngRow As Long
Dim vValue As Variant
Dim rngCol As Range

lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lastrow
str = Cells(i, 1)

'copy paste last number from 1column to column 10

lowmin = InStr(12, str, "_", vbBinaryCompare)
On Error Resume Next
Cells(i, 10) = Mid(str, lowmin, 3)

str2 = Cells(i, 10)
   str2 = Replace(str2, "_", "")
Cells(i, 10) = str2

Next i
For i = 1 To lastrow

If Cells(i, 10) = blank Then

Cells(i, 10).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.End(xlUp)).Select
i = i + 1
vValue = Application.WorksheetFunction.Max(Selection) 'Determines max valuein range
If Application.WorksheetFunction.CountIf(Selection, vValue) > 0 Then
lngRow = Application.WorksheetFunction.Match(vValue, Selection, 0) 'Determines in case the max
Cells(lngRow, 5).Copy
Cells(lngRow, 11).PasteSpecial
End If
Else
End If
Next i

A: Sub LastPrice()
    Dim aData(), aRes()
    Dim lRw As Long, i As Long

    With ActiveSheet ' можно укзать любой лист'
        lRw = .Cells(.Rows.Count, 1).End(xlUp).Row ' последняя строка с данными в столбце А'
        aData = .Range("A1:F" & lRw).Value ' данные в массив'
        ReDim aRes(1 To lRw, 1 To 2) ' размерность массива результата'

        aRes(1, 1) = Val(Split(aData(1, 1) & "_", "_")(2)) ' извлекаем число в строке 1'

        For i = 2 To lRw
            aRes(i, 1) = Val(Split(aData(i, 1) & "_", "_")(2)) ' извлекаем число'

            If aRes(i - 1, 1) + 1 > aRes(i, 1) Then
                If aRes(i - 1, 1) > 0 Then aRes(i - 1, 2) = aData(i - 1, 5) ' запись цены'
            End If
        Next i

        If aRes(i - 1, 1) > 0 Then aRes(i - 1, 2) = aData(i - 1, 5) ' цена в последней строке'
        .Range("J1:K" & lRw).Value = aRes ' выгрузка результата'
    End With
End Sub

Макрос ориентируется на третий фрагмент текста в столбце A (a_b_число)


text:
Q: IIS URL re-write I have an intranet hosted on an IIS server (Windows Server 2016) which I want to run over https.  On our internal web server I have set up a Host (A) record:
Host - intranet
FQDN - intranet.mydomain.co.uk
IP address - xxx.xxx.xxx.xxx
I have applied a certificate to the IIS server and set up the bindings and it loads fine.  However previously people could access the intranet through an Alias (CNAME) record - i.e. http://intranet
and I am worried that they will grumble about the longer URL.
Is there a way of setting something up so if you type in https://intranet then what you are seeing is https://intranet.mydomain.co.uk and not get any certificate errors.  I am wondering if I can do something with DNS, URL masking or URL re-write.
All suggestions welcome!

A: I was able to solve this in the end by installing URL Rewrite on IIS then adding a rule:

*

*Requested URL - matches the pattern

*Using - regular expressions

*Pattern - .*

*Ignore case - ticked

*Conditions - {HTTP_HOST} | Matches the Pattern | intranet

*Action type - redirect

*Redirect URL - https://intranet.mydomain.co.uk/{R:0}

*Append query string - ticked

*Redirect type - permanent (301)