text:
Q: Change/Override Trinket (attiny85) USB identification name, device name The AdaFruit 'Trinket' library identifies itself as "Trinket HID Combo" when using as USB Keyboard. Is it possible to change this name to more useful name (with some code, constant etc)?
I'm using Arduino 1.0.4 IDE. Take a look in the source of this library but cannot find this name hard coded.
Any ideas to override this?

A: You have to change the Trinket library.
Search for USB_CFG_DEVICE_NAME in usbconfig.h
#define USB_CFG_DEVICE_NAME 'T', 'r', 'i', 'n', 'k', 'e', 't', ' ', 'H', 'I', 'D', ' ', 'C', 'o', 'm', 'b', 'o',

Here is the reference to the adafruit library: Adafruit-Trinket-USB


text:
Q: Detox tests are breaking This is regarding detox e2e tests.
I am running my tests, each under an it('xx', async => { await...});
The tests are scripted in such a way that 1st test would log in, 2nd test would do something on homepage, 3 rd test would navigate from homepage to other pages and so on.
The issue here is, as soon as my first test executes, the app is getting logged out and all the consecutive tests are failing.
But when I include all steps(right from login to the desired functionality) in every test, the suite is working properly.
I would like to know why is this happening. Is there any connection with async function?

A: One of the gotchas for using Detox is that the sample test specification uses a beforeEach and there is a tendency to copy verbatim examples that we are given, some times missing out things that either need to be removed or should be added.
In this particular case in the beforeEach there is the call await device.reloadReactNative(); this command reloads the device as if you had pressed CMD+R (on iOS) or RR (on Android). This means that items that have been saved to state are lost and the application is pretty much returned to its initial state.
Check your code for the offending line, you can see it in example provided below. If you remove this line then it will stop reloading React Native on your device before each test.
example.spec.js
https://github.com/wix/Detox/blob/master/examples/demo-react-native/e2e/example.spec.js
describe('Example', () => {
  beforeEach(async () => {
    await device.reloadReactNative(); // <- this is the problem
  });

  it('should have welcome screen', async () => {
    await expect(element(by.id('welcome'))).toBeVisible();
  });

  it('should show hello screen after tap', async () => {
    await element(by.id('hello_button')).tap();
    await expect(element(by.text('Hello!!!'))).toBeVisible();
  });

  it('should show world screen after tap', async () => {
    await element(by.id('world_button')).tap();
    await expect(element(by.text('World!!!'))).toBeVisible();
  });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I use the terraform totem in Reprisal? In Reprisal, I like to quickly clean up my newly conquered islands with the terraform totem.
Unfortunately, when I tried to exert my will on the landscape in a recent game, I found I was flatly denied.
You can see the crossed out cursor totem here:

I know that a certain amount of mana is necessary to use the totem, but the screenshot also shows that I definitely had enough mana for any terraform actions.
What is preventing me from using the terraform totem?


text:
Q: Should the "flag-weights" tag be renamed to the "helpful-flags"? As Waffles wrote @ https://meta.stackexchange.com/a/119714/143601:

We now only show the number of helpful flags on your profile
  page (visible only to you) ... this number only ever increases.
Flag weight on the other hand, is gone ... it is dead.

Should we rename the existing flag-weight tag to the helpful-flags? And/or create a synonym? Or just leave it as is (for historical purposes, for example)?

Just in case… No personal interest here as I'd rather prefer flag-weight -> helpful-flags rename, than Taxonomist badge for the latter.

A: No. They're different mechanisms and much of the discussion about flag weight won't apply to a simple helpful flag counter.
Retag what makes sense and close/delete/comment/etc. on the rest.


text:
Q: highlighting lines based on array I have a body of text with several lines.  Each line is wrapped in a span with an incremented value at the end to determine which line is what (for example, line-1, line-2, line-3 and so forth).

    what is love

    oh baby, don't hurt me

    Don't hurt me no more

    Oh, baby don't hurt me

    Don't hurt me no more

    What is love

    Yeah

Now I have an array that says lines 1 and 2 are grouped together and lines 5-6 are grouped together.  Which means when the mouse hovers over line-1 then turn the background a different color on line-1 and line-2 (as per the array) as well as if line-5 is mouseovered then do the background thing on line-5 and line-6.
It's simply doing it on a span by span basis, but I'm not sure how to approach the array part of it.  Should I use something like in_array?  I know it's a PHP function, but Google tells me people have built similar functions for JS.
$("span[id^='line-']").live('mouseover', function(e) {
  e.preventDefault();
  var line_id = $(this).attr('id').substring(6);

  $(this).addClass("highlight1");

  return false;
});

$("span[id^='line-']").live('mouseleave', function(e) {
  e.preventDefault();
  var line_id = $(this).attr('id').substring(6);

  $(this).removeClass("highlight1");

  return false;
});

A: If you can group the elements in the HTML:

    what is love

    oh baby, don't hurt me

  Don't hurt me no more

  Oh, baby don't hurt me

    Don't hurt me no more

    What is love

  Yeah

Then you don't need any script at all, just some CSS:
#textbody > span:hover { background: yellow; }

Demo: http://jsfiddle.net/Guffa/Rfwye/

A: var groups = [{
    group: [1,2],
    color: "#000"},
{
    group: [3,7],
    color: "#0ff"},
{
    group: [4,6],
    color: "#ff0"},
{
    group: [5],
    color: "#ff0000"}];

$(groups).each(function(index, item) {
    $(item.group).each(function(i, span) {
        $("#line-" + span).addClass("group" + index).data("bgcolor", item.color);
    });
});

$("#textbody span").mouseover(function(){
   $("." + $(this).attr("class")).css("background-color", $(this).data("bgcolor"));
});

$("#textbody span").mouseout(function(){
   $("." + $(this).attr("class")).css("background", "transparent");
});

demo : http://jsfiddle.net/y8UrW/

A: You can add a class to the container and use CSS to highlight lines based on the hovered over line.
$('#textbody').addClass('over-' + $(this).id());

and then use CSS to group them
#textbody span[id^='line-']:hover, /* Always highlight the hovered line */
.over-line-1 > #line-2, .over-line-2 > #line-1 /* Higlight the partner line */
{ background: yellow }

will group lines 1 and 2.

A: I've come to a somewhat lengthy solution that maintains your current structure. Seems to work well, though it might be a little overkill for your case... Anyway, take a look: http://jsfiddle.net/Ap6JP/
var groups = [
  [1, 2],
  [5, 6]
]

var lineIdFor = function($span) {
  return parseInt($span.attr("id").match(/\d+/)[0]);
};

var groupFor = function(lineId) {
  var group;
  $.each(groups, function() {
    if(this.indexOf(lineId) >= 0) {
      group = this;
    }
  });

  return group || [lineId];
};

var spansInGroup = function(group) {
  var $spans = new $();

  $.each(group, function() {
    $spans = $spans.add($("#line-" + this));
  });

  return $spans;
};

var groupForSpan = function($span) {
  var lineId = lineIdFor($span);
  var group  = groupFor(lineId);
  return spansInGroup(group);
};

$("#textbody").on("mouseover", "span", function() {
  var $group = groupForSpan($(this));
  $group.addClass("highlight1");
});

$("#textbody").on("mouseout", "span", function() {
  var $group = groupForSpan($(this));
  $group.removeClass("highlight1");
});


text:
Q: Cannot use dot notation or bracket notation to get into an array I cannot seem to get into an array that I'm needing to get into, in my console it appears as [] but you can expand it and it has more inside of it which I need access to.
I've tried using dot notation and bracket notation to get into the array but with no luck
This is part of my code:
console.log(gameData);
    _.each(gameData['1'], (games) => {
      console.log(games);
}

This is the array as it first appears in the console:
[]

This is the array expanded in the console:
0: "Games fetched successfully"
1: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
length: 2

I cannot access the array with gameData[1] which is what I need. Can you think of a reason why this is happening? I'm probably doing something simple wrong.

A: Assuming that gameData is an Array, you can access its items using this:
_.each(gameData, game => console.log(game));

You also don't really need _ here. You can simply use the forEach method on it:
gameData.forEach(game => console.log(game));

And yeah, since this is an Array which are 0 based, you can access it's elements using
gameData[index]

where index would be an integer(0, 1, 2) etc.
Here, give this a try:

const gameData = [{
    id: 1,
    name: 'Game 1'
  },
  {
    id: 2,
    name: 'Game 2'
  },
  {
    id: 3,
    name: 'Game 3'
  },
  {
    id: 4,
    name: 'Game 4'
  },
  {
    id: 5,
    name: 'Game 5'
  },
];

gameData.forEach(game => console.log(game));

console.log('Got the game at the 0th index as: ', gameData[0]);


text:
Q: How Do You Edit Pages Using The Client Side Object Model? Im using the C#  CSOM object for Sharepoint 2013. I want to edit the homepage of a site so i can add some custom content to it. I want to be able to add some custom text and some web parts in the future if i ever need them. So far i have the following code
        using (ClientContext context = new ClientContext("http://sharepointserver/site1"))
        {
            var pagesList = context.Web.Lists.GetByTitle("Site Pages");
            context.Load(pagesList);
            context.ExecuteQuery();
            var rootcontents = pagesList.RootFolder.Files;
            context.Load(rootcontents);
            context.ExecuteQuery();
            var homepage = rootcontents[1];
        }

I had expected that i could go homepage.content = "abc"; there is no option to do this with the homepage object. I have the correct page that i want in this homepage object but i cant figure out how to add custom content to the page using this objects.


text:
Q: Python pandas .loc multiple conditions and modify part of date I have a DataFrame with (among others) two date columns formatted like this:
cap['DateCollecte'] = pd.to_datetime(cap['Date de collecte']+' '+cap['Heure de collecte'],format='%d/%m/%Y %H:%M:%S',errors='coerce')
cap['DatePose'] = pd.to_datetime(cap['Date de pose']+' '+cap['Heure de pose'],format='%d/%m/%Y %H:%M:%S',errors='coerce')

I know that some of them have an error: the year of DatePose is 2010 and the year of DateCollecte is 2011. The year of DatePose should be 2011 too.
The idea of what I'd like to do is more or less :
cap.loc[(cap.DateCollecte.dt.year == 2011) & (cap.DatePose.dt.year == 2010), cap.DatePose.dt.year] = 2011

I think the tricky part is that I just want to change the year part of the date. Is there a way to do this?
In the worst case, since it only concerns 3 rows with different dates (but same year problem) I could do it by hand.

A: You can use your mask and add a DateOffset, example:
In [43]:
df=pd.DataFrame({'a':pd.date_range(dt.datetime(2011,1,1), dt.datetime(2012,1,1), freq='M'), 'b':pd.date_range(dt.datetime(2010,6,1), dt.datetime(2011,6,1), freq='M')})
df

Out[43]:
            a          b
0  2011-01-31 2010-06-30
1  2011-02-28 2010-07-31
2  2011-03-31 2010-08-31
3  2011-04-30 2010-09-30
4  2011-05-31 2010-10-31
5  2011-06-30 2010-11-30
6  2011-07-31 2010-12-31
7  2011-08-31 2011-01-31
8  2011-09-30 2011-02-28
9  2011-10-31 2011-03-31
10 2011-11-30 2011-04-30
11 2011-12-31 2011-05-31

In [65]:
df.loc[(df['a'].dt.year == 2011) & (df['b'].dt.year == 2010), 'b'] = df['b'] + pd.DateOffset(years=1)
df

Out[65]:
            a          b
0  2011-01-31 2011-06-30
1  2011-02-28 2011-07-31
2  2011-03-31 2011-08-31
3  2011-04-30 2011-09-30
4  2011-05-31 2011-10-31
5  2011-06-30 2011-11-30
6  2011-07-31 2011-12-31
7  2011-08-31 2011-01-31
8  2011-09-30 2011-02-28
9  2011-10-31 2011-03-31
10 2011-11-30 2011-04-30
11 2011-12-31 2011-05-31

In the general case you can use apply to dynamically apply the difference:
In [69]:
df['b'] = df.apply(lambda x: x['b'] + pd.DateOffset(years=x['a'].year-x['b'].year), axis=1)
df

Out[69]:
            a          b
0  2011-01-31 2011-06-30
1  2011-02-28 2011-07-31
2  2011-03-31 2011-08-31
3  2011-04-30 2011-09-30
4  2011-05-31 2011-10-31
5  2011-06-30 2011-11-30
6  2011-07-31 2011-12-31
7  2011-08-31 2011-01-31
8  2011-09-30 2011-02-28
9  2011-10-31 2011-03-31
10 2011-11-30 2011-04-30
11 2011-12-31 2011-05-31


text:
Q: Exercise 1-18 in K&R The C Programming Language This exercise is driving me crazy. Sorry if my programming problems seem petty, but I'm a beginner so please bear with me.
The exercise asks for the following:
Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.
Can anybody tell me why my code doesn't work? I haven't yet tackled the issue of entirely blank lines, but I can't find any reason why my code won't remove trailing blanks and tabs. Here it is:
#include <stdio.h>

#define MAXLINE 1000

int better_line_length(char line[], int lim);
void copy(char to[], char from[]);

int main(void)
{
    int len;
    char s[MAXLINE];
    char better_s[MAXLINE];

    while ((len = better_line_length(s, MAXLINE)) > 0) {
        copy(better_s, s);
        printf("%s\n", better_s);
    }

    return 0;
}

int better_line_length(char s[], int lim)
{
    int c, i, last_letter;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
        s[i] = c;
        if (c != ' ' && c != '\t')
            last_letter = i;
    }

    s[last_letter+1] = '\0';

    return last_letter+1;
}

void copy(char to[], char from[])
{
    int i = 0;

    while ((to[i] = from[i]) != '\0')
        ++i;
}

For example, I expect the code to work as follows: If my input is like this (where '▯' indicates a space):
abcdefg▯▯▯▯▯▯▯▯▯▯▯▯

I expect the output to be
abcdefg

Notice that there are no spaces after the expected output.
But instead, the output I get is an infinite printing of the first character of the input.
UPDATE: My code works as expected when input is taken from the keyboard, but I still get the repeating of one character when input is taken from another file. My mind is blown.

A: The problem is this part of your code:
while ((len = better_line_length(s, MAXLINE)) > 0) {
    copy(better_s, s);
    printf("%s\n", better_s);
}

It iterates infinitely as the result of (len = better_line_length(s, MAXLINE)) will always be greater than 0 (for strings with at least 1 character).
You do not need a while loop. Instead, do it like this:
len = better_line_length(s, MAXLINE);
copy(better_s, s);
printf("%s|\n", better_s);

(also note that you don't use len anywhere)


text:
Q: ParamValidationExt error with WelsInitEncoderExt failed while setting up OpenH264 encoder Scenario:
I am using OpenH264 with my App to encode into a video_file.mp4.
Environment:
Platform : MacOs Sierra
Compiler : Clang++
The code:
Following is the crux of the code I have:
void EncodeVideoFile() {

  ISVCEncoder     * encoder_;
  std:string      video_file_name = "/Path/to/some/folder/video_file.mp4";
  EncodeFileParam * pEncFileParam;
  SEncParamExt    * pEnxParamExt;

  float frameRate = 1000;
  EUsageType usageType = EUsageType::CAMERA_VIDEO_REAL_TIME;
  bool denoise = false;
  bool lossless = true;
  bool enable_ltr = false;
  int layers = 1;
  bool cabac = false;
  int sliceMode = 1;

  pEncFileParam = new EncodeFileParam;

  pEncFileParam->eUsageType = EUsageType::CAMERA_VIDEO_REAL_TIME;
  pEncFileParam->pkcFileName = video_file_name.c_str();
  pEncFileParam->iWidth = frame_width;
  pEncFileParam->iHeight = frame_height;
  pEncFileParam->fFrameRate = frameRate;
  pEncFileParam->iLayerNum = layers;
  pEncFileParam->bDenoise = denoise;
  pEncFileParam->bLossless = lossless;
  pEncFileParam->bEnableLtr = enable_ltr;
  pEncFileParam->bCabac = cabac;

  int rv = WelsCreateSVCEncoder (&encoder_);

  pEnxParamExt = new SEncParamExt;

  pEnxParamExt->iUsageType                = pEncFileParam->eUsageType;
  pEnxParamExt->iPicWidth                 = pEncFileParam->iWidth;
  pEnxParamExt->iPicHeight                = pEncFileParam->iHeight;
  pEnxParamExt->fMaxFrameRate             = pEncFileParam->fFrameRate;
  pEnxParamExt->iSpatialLayerNum          = pEncFileParam->iLayerNum;

  pEnxParamExt->bEnableDenoise            = pEncFileParam->bDenoise;
  pEnxParamExt->bIsLosslessLink           = pEncFileParam->bLossless;
  pEnxParamExt->bEnableLongTermReference  = pEncFileParam->bEnableLtr;
  pEnxParamExt->iEntropyCodingModeFlag    = pEncFileParam->bCabac ? 1 : 0;

  for (int i = 0; i < pEnxParamExt->iSpatialLayerNum; i++) {
      pEnxParamExt->sSpatialLayers[i].sSliceArgument.uiSliceMode = pEncFileParam->eSliceMode;
  }

  encoder_->InitializeExt(pEnxParamExt);

  int videoFormat = videoFormatI420;
  encoder_->SetOption (ENCODER_OPTION_DATAFORMAT, &videoFormat);

  int frameSize = frame_width * frame_height * 3 / 2;
  int total_num = 500;
  BufferedData buf;
  buf.SetLength (frameSize);

  // check the buffer before proceeding
  if (buf.Length() != (size_t)frameSize) {
      CloseEncoder();
      return;
  }

  SFrameBSInfo info;
  memset (&info, 0, sizeof (SFrameBSInfo));
  SSourcePicture pic;
  memset (&pic, 0, sizeof (SSourcePicture));
  pic.iPicWidth = frame_width;
  pic.iPicHeight = frame_height;
  pic.iColorFormat = videoFormatI420;
  pic.iStride[0] = pic.iPicWidth;
  pic.iStride[1] = pic.iStride[2] = pic.iPicWidth >> 1;
  pic.pData[0] = buf.data();
  pic.pData[1] = pic.pData[0] + frame_width * frame_height;
  pic.pData[2] = pic.pData[1] + (frame_width * frame_height >> 2);

  for(int num = 0; num < total_num; num++) {
     // try to encode the frame
     rv = encoder_->EncodeFrame (&pic, &info);
  }

  if (encoder_) {
      encoder_->Uninitialize();
      WelsDestroySVCEncoder (encoder_);
  }
}

Above code is something I pulled up from official usage examples of OpenH264 where BufferedData.h is a class I reused from OpenH264 utils
Issue:
But, I am getting the following error:
[OpenH264] this = 0x0x1038bc8c0, Error:ParamValidationExt(), width > 0, height > 0, width * height <= 9437184, invalid 0 x 0 in dependency layer settings!
[OpenH264] this = 0x0x1038bc8c0, Error:WelsInitEncoderExt(), ParamValidationExt failed return 2.
[OpenH264] this = 0x0x1038bc8c0, Error:CWelsH264SVCEncoder::Initialize(), WelsInitEncoderExt failed.

Above does not crash the application but it goes through a blank run without creating the video_file.mp4 with the dummy data that I am trying to write into it.
Question:
There seems to be something wrong with the set up config I applying to pEnxParamExtwhich goes into encoder_->InitializeExt.
What am I doing wrong with the set up of the encoder?
Note:
I am not trying to hook up to any camera device. I am just trying to create a .mp4 video out of some dummy image data.

A: If you want to get complete and working OpenH264 Encoder Initialization procedure you can click... here.
According to your problem scenario, you are trying to create a video file(.mp4/.avi) from some dummy images. This task can be accomplished using two different libraries: i) Library for Codec, ii) Library for Container.
i) Library for Codec: It's so much easy to use a OpenH264 to compress data. One thing I must mention is that, OpenH264 always works with raw frames e.g. yuv420 data. So, if you want to compress your image data, you have to convert these image data into yuv420 color format. To get OpenH264 click... here
ii) Library for Container: After getting the encoded data you have to use another library to create the container with extension .mp4, .avi, .flv etc. There exists a lot of libraries in github to do that staff like FFmpeg, OpenCV, Bento4, MP4Maker, mp4parser etc. Before using these libraries please check in detail about the license issues. If you use FFmpeg, you will not need to use OpenH264 becuse FFmpeg itself works along with several codecs. You will also find lot more working examples as so many developers are working with video data out there.
Hope it helps. :)


text:
Q: MySQL query WHERE IN + ORDER BY, which EXPLAIN is better and how to avoid filesort? This is my table definition, without any special index for now:
CREATE TABLE `filter` (
  `field_name` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `category_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `position` smallint(6) NOT NULL,
  `options` longtext COLLATE utf8_unicode_ci COMMENT '(DC2Type:json_array)',
  PRIMARY KEY (`field_name`,`category_id`),
  KEY `IDX_702C956612469DE2` (`category_id`),
  CONSTRAINT `FK_702C956612469DE2`
      FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Sample data:
+------------+-----------------------+-------------+----------+
| field_name |        options        | category_id | position |
+------------+-----------------------+-------------+----------+
| color      | {"label": "Color"}    |        1895 |        1 |
| material   | {"label": "Material"} |        1895 |        2 |
| color      | {"label": "Color"}    |        1896 |        1 |
| color      | {"label": "Color"}    |        1897 |        1 |
+------------+-----------------------+-------------+----------+

Most of the time I do a query with WHERE IN and ORDER BY position and selecting only field_name and options:
EXPLAIN SELECT
  field_name
  options
FROM
  filter
WHERE
  category_id IN ('1895', '1896', '1897')
ORDER BY
  position ASC

This gives me Using index condition; Using filesort, quite bad uh?
{
   "query_block":{
      "select_id":1,
      "ordering_operation":{
         "using_filesort":true,
         "table":{
            "table_name":"filter",
            "access_type":"range",
            "possible_keys":[
               "IDX_702C956612469DE2"
            ],
            "key":"IDX_702C956612469DE2",
            "used_key_parts":[
               "category_id"
            ],
            "key_length":"98",
            "rows":5,
            "filtered":100,
            "index_condition":"(`filter`.`category_id` in ('1895','1896','1897'))"
         }
      }
   }
}

With an index on category_id, position Using where; Using index; Using filesort:
{
   "query_block":{
      "select_id":1,
      "ordering_operation":{
         "using_filesort":true,
         "table":{
            "table_name":"filter",
            "access_type":"range",
            "possible_keys":[
               "IDX_702C956612469DE2",
               "IDX_CATEGORY_POSITION"
            ],
            "key":"IDX_CATEGORY_POSITION",
            "used_key_parts":[
               "category_id"
            ],
            "key_length":"98",
            "rows":5,
            "filtered":100,
            "using_index":true,
            "attached_condition":"(`filter`.`category_id` in ('1895','1896','1897'))"
         }
      }
   }
}

So which explain is better? I would say the first because of using index condition (there is no "where" part). Is there any way to avoid the filesort?

A: Given the structure of multicolumn B-tree index it is not viable to do a sort on position when using IN on category_id. But as the test data suggest the position is not "global" but seems to have a meaning only for given category_id. So as I suggested in comments, it is instead possible to ORDER BY (category_id, position) - that can use two-column index on those columns to get it without filesort. http://sqlfiddle.com/#!9/aabaa/7
Because of the longtext column it is not possible to turn this into an index-only scan (text columns can be only indexed on prefix, not on entire value, as index key length is limited).
Using varchar fields as primary key has some drawbacks, but it is not "wrong" by itself so just a little suggestion - would it make sense in your desing to use some integer ids instead?


text:
Q: is there a way to open a file in webpack browser extension application When compiling my browser extension project I have this error :
Module not found: Error: Can't resolve 'fs' in 'C:\Users\admin\project\node_modules\pdf-table-extractor'

I'm using webpack and npm.
pdf-table-extractor is an npm library that extracts pdf data in Json format.
This library require the fs library to open the pdf file path.
It seems that this library is somehow blocked by webpack.
Can any one help with this ?
Adding
 node: {
        fs: 'empty'
    }
to the "webpack.config.js" file solve the compiling error but the extension  is failing in the browser.
Many thanks in advance.


text:
Q: Does an RST packet get sent to the application regardless of its sequence number? When an application is receiving data from a socket, it will receive the data in the correct order in which it was sent. TCP will know how to re-order the data based on the sequence number included in each packet's header.
But what about an RST packet, for example: if the other side sent some data and then sent an RST packet (by ungracefully closing the connection), and the RST packet was received before the data, what will happen in this case?
Will TCP wait for the data to be received and then give the application the data followed by the RST packet, or will TCP give the application the RST packet immediately before receiving the data?

A: It doesn't make any difference. Receipt of the RST will cause the entire contents of the socket receive buffer to be thrown away in either case.


text:
Q: center a table in tkinter I am tkintering with tkinter :) and trying to center the "StackQuestion" table.
I do not know what is the option to center horizontally, and or vertically the table inside of the receiving container.
The first class, Class StackQuestion defines how the general windows works and how to switch from container to container. The second, define the table and its content.
I have tried adding different colours to the different containers in order to check which container is active and thereof to try to center everything that is inside the later, without much success.
edit : in order not to have lots of code here I have deleted all the other classes and duplicate "Test" in "for F in (Test, Test):" in order for the code to run on your computer.

#utf8
#python3
import tkinter as tk
from tkinter import *
from tkinter import ttk

class StackQuestion(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        container = ttk.Frame(self)

        container.grid()

        #windows resize management
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (Test, Test):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=1, column=1, sticky='nsew')

        self.show_frame(Test)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class Test(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text = 'StackQuestion')
        label.grid(row=0, column=0, columnspan=2)

        questions = ['Question 1', 'Question 2' , 'Question 3']
        row_number = 1
        column_number = 0

        Tree = ttk.Treeview(self, show ='headings')
        Tree['columns'] = ('Author', 'Subject', 'Date', 'Question')
        Tree.heading('Author', text = 'Author')
        Tree.heading('Subject', text = 'Subject')
        Tree.heading('Date', text = 'Date')
        Tree.heading('Question', text = 'Question')

        for value in questions :
            Tree.insert('', 'end', value, text = value)
            Tree.set(value, 'Author', value)

        Tree.grid()

app = StackQuestion()
app.geometry('1080x700')
app.configure(background='grey')
app.mainloop()

A: I'm not an expert python programmer, in fact I'm still a newbie and I'm tkintering too in order to learn. So I've found this "noob-fix" following the hint by toti08
You can change
 container.grid()

with:
container.pack(pady=50)

This will center it horizzontally and give the table a bit of padding top so you can also center it vertically or at least give it a little margin on the border.
Hope this helps until someone more experienced comes along with a solution to your problem :)


text:
Q: Splitting and reording in an orthonormal basis Suppose I have a Hilbert space $H$ with countable orthonormal basis $\{e_n \}_{n\in\mathbb{Z}_{\geq 0}}$. Every orthonormal basis is an example of an unconditional Schauder basis, meaning if I write $x\in H$ as
$$
x=\sum_{n\geq 0} c_n e_n, \quad |c_n|<\infty
$$
then I can rearrange the terms in the sum in any way I like and the series will still converge to $x$.
Now, suppose I split the coefficients $c_n$ into finite sums of another finite set of coefficients, that is for each $n$ I write
$$
c_n=\sum_{m=0}^{K_n}b_{nm}, \quad |b_{nm}|<\infty,\quad K_n<\infty
$$
Question: Can I still reorder the resulting series in any way I like? To give an example of what I mean, suppose $K_0=1$, $K_j=0$, $j>1$. So I have
$$
x=(b_{00}+b_{01})e_0 +\sum_{n\geq 1}c_1 e_1
$$
Can I then move $b_{01} e_0$ to any position I like and write
$$
x=b_{00} e_0 +c_1 e_1 + \dots + b_{01} e_0 + \dots\quad
$$
or is it crucial that I keep all $e_n$ together?

A: Any vector in $H$ is uniquely defined by the coordinate projections $\langle e_n,x\rangle$. Since each $K_n$ is finite one can reorder the basis vectors in any desired way and this will not affect the coordinate values.


text:
Q: TableView cell request Focus I'm new in JavaFX and have the following issue:
I have a tableview inside a BorderPane. I want it to focus on the last row/1st column when it's loaded. I have tried the following:

*

*requestfocus()

*scrollTo()

*focusModel.focus()

*selectionModel.select()

What happens is that the cell I want is indeed blue (as if it was selected) but the first cell has a blue border. So, when I try to use the arrow keys, the selected cell moves to the first row.
BTW, I'm using TornadoFX.
Any ideas?
Thanks in advance!
class CashflowTab : View() {
    override val root: HBox by fxml()
    private val mController : CashflowController by inject()
    private val mainView : MainView by inject()

    // Get the buttons
    private val buttonCashflow : Button by fxid("btnCashflow")

    init {
        // Setup the buttons
        buttonCashflow.action {
            setupCashflowTable()
        }
    }

    /** Displays the TableView for the Cashflow */
    private fun setupCashflowTable() {
        var initialFocus = true
        // List of entries for the category ComboBox
        val categoryList = mController.getCashFlowCategoryList()

        // Create the table
        val cashTable = tableview<CashEntry>(mController.getCashEntryList()) {
            isEditable = true
            column(Constants.COL_COUNT, CashEntry::countProperty)
            column(Constants.COL_DATE, CashEntry::dateProperty).makeEditable(LocaleDateConverter())
            column(Constants.COL_INCOME, CashEntry::incomeProperty).makeEditable(CurrencyConverter())
            column(Constants.COL_EXPENSES, CashEntry::expensesProperty).makeEditable(CurrencyConverter())
            column(Constants.COL_PROFIT, CashEntry::profitProperty).converter(CurrencyConverter())
            column(Constants.COL_TOTAL_PROFIT, CashEntry::totalProfitProperty).converter(CurrencyConverter())
            column(Constants.COL_COMMENTS, CashEntry::commentsProperty).makeEditable()
            column(Constants.COL_CATEGORY, CashEntry::categoryProperty).useComboBox(categoryList)

            // Scroll to and focus on the last cell on startup
            if (initialFocus) {
                val lastRow = mController.getCashEntryList().size - 1
                requestFocus()
                scrollTo(lastRow)
                focusModel.focus(lastRow)
                selectionModel.select(lastRow)
                initialFocus = false
            }

            onEditCommit {entry ->
                // Update the list
                mController.updateCashEntryList(entry)

                // Move to the next cell
                requestFocus()
                focusModel.focusRightCell()
                @Suppress("UNCHECKED_CAST")
                selectionModel.select(focusModel.focusedCell.row, focusModel.focusedCell.tableColumn as TableColumn<CashEntry, *>)
            }
            enableCellEditing()

            // Enable edit on key typed
            addEventHandler(KeyEvent.KEY_PRESSED) {keyEvent ->
                if (keyEvent.code.isDigitKey || keyEvent.code.isLetterKey) {
                    if (editingCell == null) {
                        val currentSelectedCell = selectedCell
                        if (currentSelectedCell != null && currentSelectedCell.tableColumn.isEditable) {
                            edit(currentSelectedCell.row, currentSelectedCell.tableColumn)
                        }
                    }
                }
            }
        }

        // Add the table to the view
        mainView.root.center = cashTable
        cashTable.tableMenuButtonVisibleProperty()

        // Ensure no other node can get focus
        cashTable.focusedProperty().onChange {
            val focusOwner = currentStage?.scene?.focusOwnerProperty()?.value

            // Check if the focus owner is the table or a cell
            if (focusOwner !is TableView<*> && focusOwner !is TextField) {
                cashTable.requestFocus()
            }
        }
    }
}

A: You should use
Platform.runLater(() -> {
    requestFocus();
    scrollTo(lastRow);
    ...
});

to update the GUI.


text:
Q: SQL - Combine multiple column and apply ILIKE I am using PostgreSql and I have user table with firstName and lastName column.
Please check below table as a example
----------------------------------------------------
id | firstname | lastName
----------------------------------------------------
1  | Keval     | Gangani
----------------------------------------------------
2  | New       | User
----------------------------------------------------

My pg query is SELECT * FROM users WHERE ("firstname" ILIKE %Keval Gangani% OR "lastName" ILIKE %Keval Gangani%) but this return zero results.
I know there is no records with %Keval Gangani%
I want to combine firstName and lastName and then i want to apply ILIKE query.

A: SELECT * FROM users WHERE concat(firstname,' ',lastName) ILIKE '%Keval Gangani%'
Thanks to @Philippe


text:
Q: Deploying go1.11 on App Engine Standard Build failure: Your app is not on your GOPATH I have attempted to deploy my Go app to App Engine. I have the following build errors:
Starting Step #1 - "builder"
Step #1 - "builder": Pulling image: gcr.io/gae-runtimes/go111_app_builder:go111_1_11_2_20181111_RC00
Step #1 - "builder": go111_1_11_2_20181111_RC00: Pulling from gae-runtimes/go111_app_builder
Step #1 - "builder": Digest: sha256:51fb36bfa16e7013356867c3a3972986084df93e56258fc258579a5799f0436e
Step #1 - "builder": Status: Downloaded newer image for gcr.io/gae-runtimes/go111_app_builder:go111_1_11_2_20181111_RC00
Step #1 - "builder": 2018/11/24 18:13:29 Your app is not on your GOPATH, this build may fail.
Step #1 - "builder": 2018/11/24 18:13:29 Building from Go source in /tmp/staging477638319/srv, with main package at ./...
Step #1 - "builder": 2018/11/24 18:13:29 Building /tmp/staging477638319/srv, saving to /tmp/staging477638319/usr/local/bin/start
Step #1 - "builder": 2018/11/24 18:13:30 Wrote build output to /builder/outputs/output
Step #1 - "builder": 2018/11/24 18:13:30 Failed to build app: Your app is not on your GOPATH, please move it there and try again.
Step #1 - "builder": building app with command '[go build -o /tmp/staging477638319/usr/local/bin/start ./...]', env '[PATH=/go/bin:/usr/local/go/bin:/builder/google-cloud-sdk/bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOSTNAME=d253e517b16c HOME=/builder/home BUILDER_OUTPUT=/builder/outputs DEBIAN_FRONTEND=noninteractive GOROOT=/usr/local/go/ GOPATH=/go GOPATH=/tmp/staging477638319/srv/gopath]': err=exit status 1, out=srv/main.go:7:2: cannot find package "cloud.google.com/go/firestore" in any of:
Step #1 - "builder": /usr/local/go/src/cloud.google.com/go/firestore (from $GOROOT)
Step #1 - "builder": /tmp/staging477638319/srv/gopath/src/cloud.google.com/go/firestore (from $GOPATH)
Step #1 - "builder": srv/main.go:8:2: cannot find package "github.com/gin-gonic/gin" in any of:
Step #1 - "builder": /usr/local/go/src/github.com/gin-gonic/gin (from $GOROOT)
Step #1 - "builder": /tmp/staging477638319/srv/gopath/src/github.com/gin-gonic/gin (from $GOPATH)
Step #1 - "builder": srv/main.go:9:2: cannot find package "google.golang.org/api/option" in any of:
Step #1 - "builder": /usr/local/go/src/google.golang.org/api/option (from $GOROOT)
Step #1 - "builder": /tmp/staging477638319/srv/gopath/src/google.golang.org/api/option (from $GOPATH)
Finished Step #1 - "builder"
ERROR
ERROR: build step 1 "gcr.io/gae-runtimes/go111_app_builder:go111_1_11_2_20181111_RC00" failed: exit status 1

My app.yaml file looks like:
runtime: go111
handlers:
- url: /api/user
  script: auto

- url: /favicon.ico
  static_files: build/favicon.ico
  upload: build/favicon.ico

- url: /
  static_files: build/index.html
  upload: build/index.html

- url: /
  static_dir: build

My main.go file at the root looks like:
package main

import (
    "context"
    "net/http"

    "cloud.google.com/go/firestore"
    "github.com/gin-gonic/gin"
    "google.golang.org/api/option"
)

const firestoreAccountFile = "firebase.json"
const firestoreProjectID = "golang-gae-firestore-template"

type formData struct {
    Name  string `json:"name" binding:"required"`
    Email string `json:"email" binding:"required"`
}

func main() {
    // Gin init
    r := gin.Default()
    // Serve from static build directory
    r.StaticFS("/", http.Dir("./build"))
    // routes
    r.POST("/api/user", userHandler)
    // run application on port 8080
    r.Run(":8080")
}

func writeLogIfError(c *gin.Context, err error) {
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    }
}

func getNewFirestoreClient(ctx context.Context) (*firestore.Client, error) {
    return firestore.NewClient(ctx, firestoreProjectID, option.WithServiceAccountFile(firestoreAccountFile))
}

func userHandler(c *gin.Context) {
    ctx := context.Background()

    client, err := getNewFirestoreClient(ctx)
    writeLogIfError(c, err)
    defer client.Close()
    // Get form data
    var form formData
    c.BindJSON(&form)

    // [START add user to firestore]
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
        "name":  form.Name,
        "email": form.Email,
    })
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    // [END add user to firestore]
    c.JSON(http.StatusOK, gin.H{"status": "user added to db"})
}

I cannot build successfully without getting these build errors. I've attempted to follow the documentation for Go on App Engine exactly and am confused if I am to structure my application any different than suggested. Any thoughts on how to resolve this GOPATH error?

A: Update: I was unable to successfully deploy with GOPATH, and instead successfully was able to deploy with go.mod after I included the env variable: export GO111MODULE=on for the modules to work. Documentation here: https://github.com/golang/go/wiki/Modules.

A: The way it worked for me was to put my app into GOPATH/src/ folder - to reside there along third party dependencies.
https://cloud.google.com/appengine/docs/standard/go111/specifying-dependencies
says:

If your app is in a directory on your GOPATH environment variable, App Engine analyzes, copies, and uploads your imports from GOPATH

-which was confusing, i.e. I first tried to put my app into GOPATH folder and it didn't work.
So given your GOPATH folder is C:\go your project should be structured like that:
- C
  - go
     - pkg
     - src
         - cloud.google.com
         - github.com
         - google.golang.org
         - your-app


text:
Q: Order List count 2 and 3 with respect to modulus 4 I have a list which I need to sort into an order provided it contains ALL of the numbers in its sequence:
Manually just setting them does not seem like the way to go about it.
I know how to order lists to be ascending or descending but having the modulus 4 is sending my head funny.
Modulus of 4 is due to this being linked to node neighbours on a grid
I do not know what order they are put into the list initially as it is random and changes every time - Procedural generation of grid connections
I do not want a new list, I just want to simply re-arrange the current one.
List Count of 3:
0, 1, 2
1, 2, 3
2, 3, 0
3, 0, 1
if (acceptedIndicies.Contains(0) && acceptedIndicies.Contains(1) && acceptedIndicies.Contains(2)) // Top-Right-Down
{
      // Order List in the sequence
      acceptedIndicies[0] = 0;
      acceptedIndicies[1] = 1;
      acceptedIndicies[2] = 2;
}
else if (acceptedIndicies.Contains(1) && acceptedIndicies.Contains(2) && acceptedIndicies.Contains(3)) // Right-Down-Left
{
      // Order List in the sequence
      acceptedIndicies[0] = 1;
      acceptedIndicies[1] = 2;
      acceptedIndicies[2] = 3;
}
else if (acceptedIndicies.Contains(2) && acceptedIndicies.Contains(3) && acceptedIndicies.Contains(0)) // Down-Left-Top
{
      // Order List in the sequence
      acceptedIndicies[0] = 2;
      acceptedIndicies[1] = 3;
      acceptedIndicies[2] = 0;
}
else if (acceptedIndicies.Contains(3) && acceptedIndicies.Contains(0) && acceptedIndicies.Contains(1)) // Left-Top-Right
{
      // Order List in the sequence
      acceptedIndicies[0] = 3;
      acceptedIndicies[1] = 0;
      acceptedIndicies[2] = 1;
}

List Count of 2:
0, 1
1, 2
2, 3
3, 0
if (acceptedIndicies.Contains(0) && acceptedIndicies.Contains(1))
{
      // Order List in the sequence
      acceptedIndicies[0] = 0;
      acceptedIndicies[1] = 1;
}
else if (acceptedIndicies.Contains(1) && acceptedIndicies.Contains(2))
{
      // Order List in the sequence
      acceptedIndicies[0] = 1;
      acceptedIndicies[1] = 2;
}
else if (acceptedIndicies.Contains(2) && acceptedIndicies.Contains(3))
{
      // Order List in the sequence
      acceptedIndicies[0] = 2;
      acceptedIndicies[1] = 3;
}
else if (acceptedIndicies.Contains(3) && acceptedIndicies.Contains(0))
{
      // Order List in the sequence
      acceptedIndicies[0] = 3;
      acceptedIndicies[1] = 0;
}

A: You can do the following:

*

*Build a valid modulus sequence. That's easy:
 var modulusSequence = Enumerable.Range(0, modulus);

*Now you need a way of generating all valid modulus sequences of a given modulus and length. Thats easy too, just shift left or right a total of modulus times a valid sequence we happen to know taking the first n elements of every new shifted sequence:
private static IEnumerable<int> ShiftLeft(IEnumerable<int> sequence)
{
    if (!sequence.Any())
        yield break;

    foreach (var i in sequence.Skip(1))
    {
        yield return i;
    }

    yield return sequence.First();
}

private static IEnumerable<IEnumerable<int>> getAllModulusSequences(int modulus, int length)
{
    var sequence = Enumerable.Range(0, modulus);

    for (var i = 0; i < modulus; i++)
    {
        yield return sequence.Take(length);
        sequence = ShiftLeft(sequence);
    }
}

*And now you simply have to check if the given sequence contains all elements of a valid sequence (note that doing it the way around is not correct because you could get false positives if the given sequence has repeating items). If it does, return the valid sequence.
I do note that I'm not ordering your list, I'm returning a new one or null if the sequence is not valid.
public static IList<int> GetOrderedSequence(IList<int> sequence, int modulus)
{
    if (modulus < sequence.Count)
        throw new ArgumentOutOfRangeException(nameof(sequence), "Sequence can not contain more elements than specified modulus.");

    foreach (var validSequence in getAllModulusSequences(modulus, sequence.Count))
    {
        if (validSequence.All(item => sequence.Contains(item)))
            return validSequence.ToList();
    }

    return null;
}

Is this faster / more efficient than your approach? Probably not. Is it prettier? I think so but its debatable. Is it more flexible? Oh yes!
If you are absolutely sure you are only going to need to check 2 and 3 long sequences with modulus 4 then you could keep your code. If not, implement a general purpose solution like the one I've shown you.


text:
Q: NUnit console run all categories (where: cat = ' ') I have a suite of NUnit tests and I am using Jenkins and MSBuild to run them. I have a number of test categories and sometimes I want to run just one category and other times all of them. Category parameter is provided from Jenkins.
I have a problem when I want to run all categories. If category is not provided I get this condition where: cat== and build fails.
If category is provided everything is fine.
Is there a way to tell nunit console to run all tests categories? Something like where: cat==*.

A: The NUnit console option --where takes an argument written in Test Selection Language. (TSL) Like any other computer language, it has it's own syntax and you get errors if you don't follow it. The expression cat== is not legal TSL. It's just as if you wrote if (cat==) in a C# program.
If you don't want to do any category selection, then you should simply not use cat== in your where clause. If you don't want to do any selection at all but just to run all tests, then you shouldn't be using --where on the command-line.
If Jenkins is actually creating the command-line for you, then you have to figure out how to tell it to not use the --where option. I don't use Jenkins, but I would bet that there docs tell you how to do it. Most CI systems I have used do it by simply not filling anything in the space where you enter categories.


text:
Q: Atributo skinSimple do Primefaces 5.0 não aparece Estou tentando usar o componente fileUpload do primefaces e para o que quero, não está aparecendo o atributo "skinSimple", como vi demonstrando no showcase. Até tento colocar o atributo sem o autocompletar mas quando termino de digitar a IDE retorna um erro dizendo que o atributo não existe para o componente.
Alguém tem ideia do que pode ser?


text:
Q: convert function type in Golang // Each type have Error() string method.
// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
//  type error interface {
//   Error() string
//  }

func (f binFunc) Error() string {
    return "binFunc error"
}

func func_type_convert() {
    var err error
    err = binFunc(add)
    fmt.Println(err)
    fmt.Println(i)
}

I have two questions about the code above:

*

*I don't know why the Error method executed, when add function was converted into binFunc type?

*Why the add function converted result was able to assign to an err error interface variable?

A: error is an interface:
type error interface {
    Error() string
}

This means that any type which has a method: Error() string fulfills the interface and can be assigned to a variable of type error.
binFunc has such a method:
func (f binFunc) Error() string {
    return "binFunc error"
}

New developers in Go sometimes find this confusing because they don't realize it's possible to attach methods to more than just structs. In this case binFunc is defined liked this:
type binFunc func(int, int) int

So the way this works is you are allowed to convert any function which has the same signature: (from the spec)

A function type denotes the set of all functions with the same parameter and result types.

So if you create a function add:
func add(x, y int) int {
    return x + y
}

You are allowed to convert this into a binFunc:
binFunc(add)

And because of the Error method on binFunc we defined above, we are then able to assign this new binFunc to a variable of type error:
var err error
var bf binFunc = binFunc(add)
err = bf

fmt.Println's behavior is to call .Error() on errors for you:

*If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

So to answer your questions:

*

*The Error method is executed because fmt.Println looks for arguments of type error, invokes .Error() and prints the resulting string.

*You are allowed to assign binFuncs to err because binFunc has an Error method. You cannot assign add directly to err because it does not have an Error method. But you are allowed to convert add to a binFunc because they have the same function signature, and by doing so you can then assign it to the err variable.

A: go spec dependencies:
type casting or conversion -> assignability -> type identity

*

*explicit type casting or conversion
binFunc and func(int, int) int have same underlying representation.
binFunc(add)

note, type casting can happen between 2 types that have the same underlying representation. However, their type can be totally different.
type MyInt int

func main() {
    var b MyInt = 3
    a := int(b)
    fmt.Println(a, b)
}

*variable assignment

check type identity
based on type identity rule, binFunc is identical to func(int, int) int. So you can do type casting as below:

A named type is always different from any other type. Otherwise, two types are identical if their underlying type literals are structurally equivalent; that is, they have the same literal structure and corresponding components have identical types.

func(int, int) int

is type literal, and it's unnamed.
type binFunc func(int, int) int

is a named type.

Predeclared types, defined types, and type parameters are called named types. An alias denotes a named type if the type given in the alias declaration is a named type.

named type is different from others. but here, binFunc is compared with the un-named type: their underlying type literals are structurally equivalent, both func(int, int) int.
var bfunc binFunc = add

check assignability
variable of named type can be assigned with a value of unnamed type providing their underlying type is identical.
You may call this an implicit type conversion here, but it's not accurate. At least golang doesn't call this type conversion because the underlying type/representation is the same.
inspired by this answer
extra words
type assertion only requires type identity. Therefore, the rule is simpler than type assignability.


text:
Q: Unexpected behaviour of Excel/VBA aggregate functions on large 1D arrays In VBA, conveniently, programmers can access Excel functions via the Application.WorksheetFunction object.  To save the programmer defining everything as spreadsheet-esque 2D arrays, the aggregate functions like WorksheetFunction.Average() will accept 1D arrays as well.
However, I've just spent the past few hours trying to pin down a unit test failure in a complex bit of statistical code, and I've found that the behaviour of the aggregate functions on 1D arrays changes once you go past an array length of 65536 (i.e. the max value of an Integer in VBA).  In particular, the following code constructs the series 1,2,3,4,5,... and then takes the average, which should equal (n+1)/2:
Dim arr1D() As Double, arr2D() As Double, kk As Long

Debug.Print "Arr length", "True mean", "Excel mean (1D)", "Excel mean (2D)"
For kk = 65535 To 65538
    ReDim arr1D(1 To kk), arr2D(1 To kk, 1 To 1)
    For ii = 1 To kk
        arr1D(ii) = ii
        arr2D(ii, 1) = ii
    Next ii ' both arrays now contain 1, 2, 3, ...
    Debug.Print kk, (kk + 1) / 2, WorksheetFunction.Average(arr1D), WorksheetFunction.Average(arr2D)
Next kk

It produces this output - note the difference depending on whether the array is 1D or 2D:
Arr length  True mean  Excel mean (1D)  Excel mean (2D)
 65535       32768      32768            32768
 65536       32768.5    32768.5          32768.5
 65537       32769      1                32769
 65538       32769.5    1.5              32769.5

Similar weird behaviour is seen with other aggregate functions - for example StDev_S similarly rolls over at 65538 items, and outright crashes at 65537.  In the words of my generation: nani the f***?
Excel version is: Microsoft® Excel® for Microsoft 365 MSO (Version 2205 Build 16.0.15225.20028) 32-bit.  A possible related question is here.  An obvious workaround is to implement my own aggregate functions - which is what I'm currently doing - but that doesn't answer the question of why the above code is doing what it does.


text:
Q: Conditional formatting, select only visible cells I have written code to select specific sheets and on button click email the data of all selected sheets. Now in one sheet there is conditional formatting applied on the dropdown list.
So the requirement is when dropdown option 1 is chosen, then below two cells are not visible. Secondly when dropdown option 2 is selected then all cells are visible.
With my code everything gets selected.
I tried this code :
overallrange = ActiveSheet.Range("C1:D50").SpecialCells(xlCellTypeVisible).Select

Can someone advice better ways to do this....

A: You're headed the right way, see my sniplet below:
Sub ert()

Dim rng As Range
For Each rng In ActiveSheet.Range("C1:D50").SpecialCells(xlCellTypeVisible)
    rng.Select
    With Selection
        .FormatConditions.Add Type:=xlExpression, Formula1:="=TRUE" 'replace with your formula
        .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
        .FormatConditions(1).StopIfTrue = False
        .FormatConditions(1).Interior.Color = 49407 'give it a touch of orange
    End With
Next

End Sub

P.S. Noone tell him, gotta love the 1st of April. Will come back tomorrow.
Edit, back with more heat: let me highlight the .Select method emulates you selecting a range then the Selection. refers to the range selected. The Select in your code wastes resource and can cause errors (e.g. something cannot be selected so the macro halts, a selectionchange event triggers etc.) and looks lousy. For the above reasons (esp. lousiness) you don't select, you just define the range and then run the script for given range. This way you can save seconds of runtime while looking cool. The snipplet below is the cool variation of your sub-sub.
Sub ert()
    With ActiveSheet.Range("C1:D50").SpecialCells(xlCellTypeVisible)
        .FormatConditions.Add Type:=xlExpression, Formula1:="=TRUE" 'replace with your formula
        .FormatConditions(.FormatConditions.Count).SetFirstPriority
        .FormatConditions(1).StopIfTrue = False
        .FormatConditions(1).Interior.Color = 49407 'give it a touch of orange
    End With
End Sub


text:
Q: On change event won't fire select list I can't seem to get jQuery to fire and on change event for the county_id select list. I have tried multiple code snippets and none will fire the on change. Any ideas?
HTML:
<select id="county_id" name="county_id">
    <option value=""></option>
    <option value="1">Somewhere</option>
    <option value="2">Somewhere else</option>
</select>

<select id="vice_county_id" name="vice_county_id"></select>

JS:
$(function(ready) {
    $("#county_id").change(
            function() {
                $("#vice_county_id").html("");
                var co_id = $("#county_id > option[@selected]").attr("value");
                if (co_id != 0) {
                    $.getJSON('./vice_county_web_service.php?co_id=' + co_id,
                            function(data) {
                                $.each(data, function() {
                                    $("#vice_county_id").append(
                                            $("<option></option>").val(
                                                    this['value']).html(
                                                    this['name']));
                                });
                            });
                }
            });

});

A: just enough to get value of select box
var co_id = $("#county_id").val();

You should use  on()
$('#county_id').on('change', function() {
  //....
  var co_id = $("#county_id").val();
});

A: try:
$(document).ready(function(){
    $("#county_id").change(function() {
        $("#vice_county_id").html("");
        var co_id = $(this).val();
        if(county_id != 0) {
            $.getJSON('./vice_county_web_service.php?co_id=' + co_id,function(data) {
                $.each(data, function() {
                    $("#vice_county_id").append($("<option></option>").val(this['value']).html(this['name']));
                });
            });
        }
    });
})

A: Change `var co_id = $("#county_id > option[@selected]").attr("value");' to 'var co_id = $("#county_id > option:selected").attr("value");'
http://jsfiddle.net/XvRsV/

A: The event is firing, but this line of code is failing:
var co_id = $("#county_id > option[@selected]").attr("value");

...because that's an invalid selector. In your browser's JavaScript console, you should be seeing Syntax error, unrecognized expression: [@selected].
jQuery will happily get you the value, just use val:
var co_id = $("#county_id").val();

Live example | source

A: Your code is working fine means the change event is getting handled by the code properly Please refer this link
$(function(ready){
            $("#county_id").change(function() {
                $("#vice_county_id").html("test");
                var co_id= $("#county_id").attr("value");
                alert('Value : ' +co_id);
            if(co_id != 0) {
                $.getJSON('./vice_county_web_service.php?co_id=' + co_id,function(data) {
                    $.each(data, function() {
                        $("#vice_county_id").append($("<option></option>").val(this['value']).html(this['name']));
                    });
                });
            }
        });

    });

Change this line only,
var co_id= $("#county_id").attr("value");
Just check if your ajax call is working or not

A:  <select id="county_id" name="county_id" onchange="ChangeCountry();">

function ChangeCountry()
{
   var _countryId = $('#county_id').val();
}


text:
Q: Vector to matrix function in NumPy without accessing elements of vector I would like to create a NumPy function that computes the Jacobian of a function at a certain point - with the Jacobian hard coded into the function.
Say I have a vector containing two arbitrary scalars X = np.array([[x],[y]]), and a function f(X) = np.array([[2xy],[3xy]]).
This function has Jacobian J = np.array([[2y, 2x],[3y, 3x]])
How can I write a function that takes in the array X and returns the Jacobian? Of course, I could do this using array indices (e.g. x = X[0,0]), but am wondering if there is a way to do this directly without accessing the individual elements of X.
I am looking for something that works like this:
def foo(x,y):
    return np.array([[2*y, 2*x],[3*y, 3*x]])

X = np.array([[3],[7]])
J = foo(X)

Given that this is possible on 1-dimensional arrays, e.g. the following works:
def foo(x):
    return np.array([x,x,x])

X = np.array([1,2,3,4])
J = foo(X)

A: You want the jacobian, which is the differential of the function. Is that correct? I'm afraid numpy is not the right tool for that.
Numpy works with fixed numbers not with variables. That is given some number you can calculate the value of a function. The differential is a different function, that has a special relationship to the original function but is not the same. You cannot just calculate the differential but must deduce it from the functional form of the original function using differentiating rules. Numpy cannot do that.
As far as I know you have three options:

*

*use a numeric library to calculate the differential at a specific point. However you only will get the jacobian at a specific point (x,y) and no formula for it.

*take a look at a pythen CAS library like e.g. sympy. There you can define expressions in terms of variables and compute the differential with respect to that variables.

*Use a library that perform automatic differentiation. Maschine learning toolkits like pytorch or tensorflow have excellent support for automatic differentiation and good integration of numpy arrays. They essentially calculate the differential, by knowing the differential for all basic operation like multiplication or addition. For composed functions, the chain rule is applied and the difderential can be calculated for arbitray complex functions.


text:
Q: Proving the integral of $f(x)g(x)$ on [a,b] is equal to an expression Given a continuous function g and an increasing function f on $[a,b]$, I'm trying to prove that
$\int_{a}^{b}f(x)g(x) dx = f(a)\int_{a}^{c} g(x)dx + f(b)\int_{c}^{b}g(x)dx$ for some c in $[a,b]$.
I tried to proceed by looking at the function $u(x)=f(a)\int_{a}^{x}g(t)dt+f(b)\int_{x}^{b}g(t)dt$, which is obviously continuous. I already know that $u(x)$ can achieve its maximum and minimum on $[a,b]$. If somehow I can prove that $\int_{a}^{b}f(x)g(x) dx$ is in $[{min}_{x\in [a,b]}(u(x)),{max}_{x\in [a,b]}(u(x))]$ then the proof can be easily done, but I really have no clue on how to prove this step. Any thoughts on that?

A: Hint: use that $f$ is an increasing function to find $\min_{x\in[a,b]}u(x)$ and $\max_{x\in[a,b]}u(x)$.


text:
Q: Why the order of options of dropdown box get changed? I have following MAP which is populating my dropdown list; however, it changes the order of the options.
public static final Map SIZE = new TreeMap(){
        {
            put("-1"," ");
            put("100","100m2");
            put("200","200m2");
            put("300","300m2");
            put("400","400m2");
            put("500","500m2");
            put("600","600m2");
            put("700","700m2");
            put("800","800m2");
            put("900","900m2");
            put("1000","1000m2");
        }
        ;
    };

 <s:select name="size"  label="Size" list="@com.example.Lists@SIZE"/>

Options in dropbox
 100m2
 1000m2
 200m2
 300m2
 ....

A: TreeMap is sorted based on the natural order of the keys. Try changing your keys to integer:
public static final Map SIZE = new TreeMap(){
        {
            put(-1," ");
            put(100,"100m2");
            put(200,"200m2");
            put(300,"300m2");
            put(400,"400m2");
            put(500,"500m2");
            put(600,"600m2");
            put(700,"700m2");
            put(800,"800m2");
            put(900,"900m2");
            put(1000,"1000m2");
        }
        ;
    };

 <s:select name="size"  label="Size" list="@com.example.Lists@SIZE"/>


text:
Q: About software licenses Good afternoon, I have a doubt about software licenses, Example if I create a script owner in the editor, eg Notepad + +, Netbeans. He will be an owner or I'll have to make available the source code for free? Because they are licensed under the GPL? Or this license is valid for only the source-code editor, and not to code created with this editor?I would be very grateful for the help.

A: No, your software is not a derived work from the editor or IDE.
It could be something else if you are using parts of the editor in your program - this is the reason the license of gcc and similar tools include an exception for this.

A: No.  In general, the license applies to the editor and the source for the editor.  Consult your attourney.


text:
Q: How to reset a broken TTY? My Slackware TTY can be broken easily by running:
cat some_binary_file

After the command, the entire TTY will no longer display readable characters but still responds to keyboard events.
Even if I logout and login again, the TTY is still broken and does not show readable characters anymore. I must restart the machine to restore normal TTY operation.
Is there a solution without restarting entire machine?

A: Usually, running reset resets the terminal. Some key bindings from .inputrc might be lost, though.

A: Run echo ^v^o, that is echo and then Ctrl-v and then Ctrl-o, Enter. You will not see the Ctrl-v. It will display as echo ^O. Ctrl-v sets it into verbose mode, passing through control characters, and the Ctrl-o will reset the terminal.

A: You can try the ANSI reset command:
printf "\033c"

A: My terminal didnt display any characters I typed. None of the other tricks worked. This one works:
stty sane

Worked for me. I sometimes have a terminal in an unresponsive state, but none of the other suggestions could give me the output back again. The other suggestions I tried, but didn't work:
echo ^v^o
reset
printf "\033c"

Source: https://unix.stackexchange.com/a/79686/53236

A: There are actually a few potential problems, and it might have to do with your environment. First off, as @Jesper answered, you want to do stty sane. However, you might not even be able to set up the environment correctly with that.
This is due to the difference between /bin/bash and /bin/sh. Upon opening your tty, run /bin/bash and then try stty sane. This should fix everything. Finally, I recommend adding such a thing to .bashrc
Another option would be to install a sane tty software.

A:     import subprocess
    def clear():
    if name == 'nt':
            _ = system('cls')
    else:
            _ = system('clear')
            subprocess.run(["reset"])

This works for me, my shell is /bin/bash, my enviroment is Windows 11, SWL and Python 3.8


text:
Q: get distinct values from file via python everyone!
I have one file containing one column with only numbers (Paramkey.txt) and i need to read the file and get distinct values and write them in another .txt file. Can someone help with the code? So far the code looks like this
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
outfile.write(set(infile)
else:
pass
infile.close()
outfile.close()

And i get Syntax error, something with the else statement.

A:   So i managed to finish the program and it's working:

    infile=open("Paramkey.txt", "r")
    outfile=open("distkey.txt", "w")
    for line in infile:
    output=set(line.strip() for line in infile)
    print >> outfile, "distincts:", output
    infile.close()
    outfile.close()

and i just want to add i used the "print >>" instead of "print()" statement, because my python is version 2.7.x not 3.x


text:
Q: Is there a 'standard' read/write lock implementation for ruby? Does anyone know of an existing ruby implementation of a read/write lock - http://en.wikipedia.org/wiki/Readers-writer_lock?
Preferably this would be in a popular library or some other implementation that's been used by enough people that it's fairly bulletproof at this point.

A: There isn't a standard one to my knowledge, but they aren't terribly hard to write.  Failing that, this guy has already written one.  It looks right and he's provided tests.

A: The link in Jonas' blog is now broken, but I have built and tested another implementation, and anybody who wants to use it is welcome to:
https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb

A: Within concurrent-ruby gem you find Concurrent::ReadWriteLock and Concurrent::ReentrantReadWriteLock.
lock = Concurrent::ReadWriteLock.new
lock.with_read_lock  { data.retrieve }
lock.with_write_lock { data.modify! }


text:
Q: Why when we list all the elements of a list for every list in a list of lists we need a specific order in the for in clauses? I am talking about the order of the for in clauses.
This order works:
[print(element) for element_list in list_of_lists for element in element_list]
and this doesn't:
[print(element) for element in element_list for element_list in list_of_lists]
I personally find the second more readable.

A: Reason is quite simple. I guess we agree on lists being an ordered collection, so no issues there. Why the order? It's very simple to remember if you think it like this:
(elt for subl in lists for elt in subl)
is the same as
for subl in lists:
    for elt in subl:
        yield elt

So, all you need to do to change latter to former is to "unfold" nested for loop by removing colons, already right-indented block then slides to the right and the yield expression is put to the front.
If that is hard to start with, I recommend writing comprehensions so that you first write the loop parts, omit colons and newlines, and put the returned part there last. That is,
1.
for subl in lists
    for elt in subl

2.
[for subl in lists for elt in subl] , note "sliding" to right end
3.
[elt for subl in lists for elt in subl]  Finished!


text:
Q: HTML table with Php for each loop Hi, I want to display two columns "test case" and "Test command" in the web.
I am getting "test case" and "test command" values from XML.
But I am facing alignment problem be of some text, case names are lengthy hence I used the table format, but this is not displaying as expected in foreach loop.
 <?php
    echo "
";
    echo "
";
    echo "  test cases 	";
    echo "  test command 	";
    echo "
";

    echo "
";
    foreach ($listfiles as $filename) {

        $element=$objDOM->getElementsByTagName('netfn')->item(0)->nodeValue ;
        $testcase_Command=$objDOM->getElementsByTagName('Command')->item(0)->nodeValue ;
        $tcname = substr(strstr(basename($fname),'.',true),3);
        echo "<input type='checkbox' name='Testcases[]' title= >$tcname" ; // prints test case name
        //echo "           $testcase_Command"; // this works but space problem, so adding coloumn below
        echo "$testcase_Command	"; // print in the column
        echo "
";
    }
    echo "
";
    echo "
";
?>

I think logic is wrong, please correct me.

A: I fixed it sorry for my mistake ..
If any one need this might help
foreach(){
    echo "
";
    echo "<input id='Checkbox1' type='checkbox' name='Testcases[]' value='hii' title= >$tcname" ;
    echo "	";
    echo "$testcase_Command";
    echo "
";
}


text:
Q: Crystal Reports Dynamically Grouping by Date I'm relatively new to Crystal Reports and it seems like this should be easy, but I haven't been able to figure it out after a lot of googling.  I'm working on a report in Crystal Reports XI that will show total hours logged by support staff for a date range and show sub totals by week, month, or both depending on the user input.  My report is currently arranged as follows:
Group 1 Header - Support Staff Member
  Group 2 Header - Ticket Closed Date with section printed monthly
    Group 3 Header - Ticket Closed Date with section printed weekly
      Group 4 Header - Ticket Category
      Group 4 Footer - Sum of time logged in each category for the week
    Group 3 Footer - Sum of time logged in all categories for the week
  Group 2 Footer - Sum of time logged in all categories for the month
Group 1 Footer - Sum of all time logged

My original idea was just to suppress the header and footer for groups 2 and 3 when they weren't needed, but if I manually do that it still prints the records by week and month.  Is there a way to not have the grouping at all unless the parameter says to show those totals?  Or if that isn't an option, how would I use the parameter to change whether the group prints records weekly or monthly?
Thank you

A: Best option would be create a string parameter 'option' with values weekly and monthly.
Now create a formula grouping.
If ?parameter='weekly'
Then //your weekly code here

Else if ?parameter='monthly'
Then //your monthly code

Now use this formula in grouping instead of multiple groups.
Now when user selects option your grouping will change dynamically.
Hope this helps


text:
Q: creating Web service from Outlook 2010 to Domino8.5.2 database I am new to web services. From Outlook, i want to create Domino document without Lotus Client installation. How to implement web service? Please any one know answer to this problem means help me?

A: Let me be your Google-Bot. These links should get you started:

*

*Lotus Notes/Domino 7 Web Services

*Practical Web services in IBM Lotus Domino 7: Writing complex Web services

A: You can also look into using Domino 8.5.3, the Extension Library and its Domino Data Service which can offer a REST API to the databases on the server.
For more details and information on how to install, administer and implement, please see:
http://www-10.lotus.com/ldd/ddwiki.nsf/xpViewCategories.xsp?lookupName=Domino%20Data%20Service


text:
Q: Second order active low pass filter values I want to use a second order active low pass filter to cut off frequencies over 33kHz . The input is 1.3 Volts peak to peak sine wave of 32 Khz and I want to make it 30kHz of 1Vpp . The formulas for calculating the values on the components of S.O.A.L.P. are for different SOALP than mine . Can someone provide me with the formulas that I need to calculate the values of my schematic or better provide the values and explain
Edit: the op amp is provided 20V in the [+] wire and is grounded on the [-] wire
Edit 2: the formulas I found for other SOALP are on this link
http://www.electronics-tutorials.ws/filter/second-order-filters.html

A: There are better steps to design a filter of this type;
Define specs then choose the type of knee response..  Low Q like Bessel give flat group delay or rate of change of phase shift.  Higher Q with steeper  edge like Chebychev compromise group delay but steeper edge and some ripple in passband. Others include Butterworth, etc.
Filter specs

*

*Choose Type & order (2, 4, 6, 8 ...) (low cost and much better performance)
or choose characteristics  ( better)

*

*Pass band gain

*Pass Band bandwidth -3dB f

*Pass Band Ripple

*Reject Band __ dB at f

*then use www.ti.com active filter tool to design AC part , then do more to correct DC bias part.

*it only takes minutes to create an email login, validate, then use the tool http://www.ti.com/design-tools/signal-chain-design/webench-filters.html

*Ensure DC bias is in valid CM range by adding biasing, e.g. Vcc/2 instead of Gnd.

*Scale R up and C down to minimize current

*Check input bias current offset voltage and balance both input R equiv with suitable R's. on (+) input.


text:
Q: CSS dropdown not working on iOS Safari? I have this navigation setup below with the CSS below that. I'm having issues with this navigation working within iOS Safari and I can't figure out why. It currently works perfectly fine in IE, Firefox and Chrome. The navigation looks fine on iOS but I can't get the dropdown to work in iOS at all.
Markup:

Home

Nav One

Link 1

Link 2

Link 3

Nav Two

Link 1

Link 2

Link 3

Link 4

Link 5

CSS:
nav {
    display: flex;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    align-items: center;
    margin: 40px 0 0;
    font-size: 12px;
}

.dropdown {
    text-transform: uppercase;
    font-family: "Montserrat",sans-serif;
    display: block;
    cursor: pointer;
    transition: color 0.3s ease-in-out;
    color: #423D39;
}

.dropdown:hover {
    color: #e16086;
}

.drop-nav {
    background: #D3AE95;
}

nav a {
    text-decoration: none;
    text-transform: uppercase;
    display: block;
    color: #423D39;
    font-family: 'Montserrat', sans-serif;
    transition: all 0.6s ease-in-out;
}

nav a:hover {
    color: #e16086;
}

nav ul li ul li {
    width: 160px;
    padding: 10px;
    font-size: 12px;
}

nav ul {
    display: flex;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    list-style: none;
    margin: 0;
}

nav ul ul {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
}

nav ul li:hover > ul {
    display: block;
    border: 1px solid rgba(255,255,255,0.4);
}

nav li {
    position: relative;
    margin: 0;
    padding: 0 7px;
}

Thanks.

A: It doesn't work because :hover effects can't directly be used on touch-devices.
A possible solution is to add a click event listener to the links, by adding this javascript (it uses jQuery, so make sure you include the jQuery library):
$(function() {
   $('nav > ul > li').on('click', function(){
       //
   });
});

This solution is, however, not very elegant and is not really user-friendly, because you can't close the subnav using this method. I'd recommend writing some custom javascript to make sure the navigation works with all user cases (e.g. tapping outside the navigation to close etc.)


text:
Q: Abort trap with SWIG for C++ and Lua I've been recently working for the first time with SWIG in order to create new Lua modules from C++. I'm working under Mac OS (El Capitan). Let me explain what I do step by step:
1) Create .cpp file
int myAddition(int x, int y)
{
  return (x+y);
}

int mySubtraction(int x, int y)
{
  return (x-y);
}

2) Create the interface file (.i):
%module test
%{
   extern int myAddition(int x, int y);
   extern int mySubtraction(int x, int y);
%}
 extern int myAddition(int x, int y);
 extern int mySubtraction(int x, int y);

3) Create the wrapper and a shared library with the following commands:
 swig -c++ -lua test.i
 g++ -I/usr/local/include -c test_wrap.cxx -o test_wrap.o
 g++ -c test.cpp -o test.o
 g++ -bundle -L/usr/local/lib/ -llua test_wrap.o test.o -o test.so

4) I create a .lua file to test the new module:
require("test")
print(test.myAddition(10,40))
print(test.mySubtraction(20,40))

The output of the script is the following:
50.0
-20.0
lua(21360,0x7fff7b739000) malloc: * error for object 0x10d86b998: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
Abort trap: 6
If I change the script into the following:
require("test")
print(test.myAddition(10,40))
print(test.mySubtraction(20,40))
os.exit()

, everything seems to be fine:
[Output] 50.0 -20.0
Do you spot any problem, or is it really necessary to call os.exit() once the script is done?
EDIT: Lua version is 5.3.2. The output of g++ -Wl --verbose -bundle -I/usr/local/include/ -L/usr/local/lib/ -llua test_wrap.o test.o -o test.so
is the following:
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin15.3.0
Thread model: posix
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -bundle -macosx_version_min 10.11.0 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -o test.so -L/usr/local/lib/ -llua test_wrap.o test.o -lc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.2/lib/darwin/libclang_rt.osx.a


text:
Q: How to handle Django Singals emitted by multiple models using a common function I would like to write a common function to handle the post_save signal emitted by Django for multiple models.
models.py
Class FirstModel(models.Model):
    pass

Class AnotherModel(models.Model):
    pass

Class YetAnotherModel(models.Model):
    pass

For some models (FirstModel, AnotherModel) in my models.py I need to write a function which can do some common action post save.
AFAIK, I can write two handler functions to receive the emitted signals and do the common action.
signals.py
@receiver(post_save, sender=FirstModel)
def first_model_post_save_handler(sender, **kwargs):
    pass

@receiver(post_save, sender=AnotherModel)
def another_model_post_save_handler(sender, **kwargs):
    pass

However I am interested in knowing any better solution to make it like a configuration.
configuration.py
MODELS_TO_BE_POST_SAVE_HANDLED = ['FirstModel', 'AnotherModel']

singals.py
@receiver(post_save, sender=MODELS_TO_BE_POST_SAVE_HANDLED)
def first_model_post_save_handler(sender, **kwargs):
    pass

Thanks in advance :)

A: You can use post_save.connect() instead of @receiver(post_save...).
Either as
post_save.connect(model_post_save_handler, sender=FirstModel)
post_save.connect(model_post_save_handler, sender=SecondModel)

or as
for model in MODELS_TO_BE_POST_SAVE_HANDLED:
    post_save.connect(model_post_save_handler, sender=model)

Also take a look at the signals documentation, it's worth reading.


text:
Q: chances of choosing 1 woman in a group consisting of 3 women and 13 men My discrete math class consists of 16 people total: 3 woman and 13 men.  If my professor handed out 16 envelopes, with one having a golden ticket in it, what are the chances that a woman gets the golden ticket?
I was trying to do something with C(16,1)*3 ... but for some reason that doesn't seem right.  It might be, and I might be second guessing myself.  As a woman, I want to know what the chances are of one of us girls winning.

A: HINT: The chances wouldn't change if there were just the envelope with the golden ticket, and your professor picked the recipient at random: each student is equally likely to get it in either version of the experiment.


text:
Q: How to click on the second element in capybara with css I have a set of following code inside table:

I am using capybara and I want to click on the second element.
I tried using:
page.all(:xpath, "//i[@class='fa fa-pen']")[1].trigger('click') -->resulted in clicking all elements

and
page.all(:xpath, "//i[@class='fa fa-pen']")[1].click -->resulted in ClickFailed error.

I would like to know if there is anyway I can click the second element without using 'within'.
Following is the HTML

A: Try something like find(:xpath, "//i[@class='fa fa-pen'][2]").click
and see if that works for you, a similar solution worked for me.


text:
Q: Colocar uma classe do Bootstrap dentro de um formulário gerado com CodeIgniter Alguém sabe me dizer como chamo as classes do Bootstrap dentro de um formulário que gerei usando o CodeIgniter? Pelo que pesquisei usa-se um array associativo, mas não estou conseguindo. Por exemplo, no label quero colocar class='sr-only' e nos input class="form-control input-lg".
echo form_open('crud/create');
echo validation_errors('<p>','</p>');
            echo form_label('Nome Completo');
            echo form_input(array('name'=>'nome'), '','autofocus');
            echo form_label('Email');
            echo form_input(array('name'=>'email'));
            echo form_label('Login');
            echo form_input(array('name'=>'login'));
            echo form_label('Senha');
            echo form_input(array('name'=>'senha'));
            echo form_label('Repita a senha');
            echo form_input(array('name'=>'senha2'));
            echo form_submit(array('name'=>'cadastrar');
echo form_close();

A: Consegui resolver.
echo form_label('Nome Completo','',array('class'=>'sr-only'));

A: De acordo com a documentação do CI você deve criar um array com os atributos que quer adicionar da seguinte maneira:
$atributos = array (
'class' => 'sua class',
'style' => 'color: #fff;' );
// E assim por diante

E depois adicionar a variavel atributos dentro do seu form_label ou seja
echo form_label('Nome Completo', $atributos);

você pode ver mais detalhes na documentação do CI


text:
Q: Can we import any file to our application from icloud? I know users can upload documents to icloud from their applications. I want to access these documents from my application. Is it possible to access any documents in icloud from our application?

A: According to the official doc: "To locate documents in iCloud storage, your app must search using an NSMetadataQuery object". But I suspect you can't simply access the documents of other apps freely.


text:
Q: JavaScript setTimeout not work on IE Preloader work 3sec, and the show the site content. But in IE and on MackBook preloader work infinitely... How can i fix that?

A: IE set timeout does not work like other browsers.
param in Internet explorer specifies whether the code in myFunction is JScript, JavaScript or VBscript See also: MSDN. It does not behave like other browsers.
Following will work:
function myFunction(){
    var $preloader = $('#page-preloader'),
    $spinner = $preloader.find('.spinner');
    $spinner.fadeOut();
    $preloader.delay(350).fadeOut('slow');
});

setTimeout( (function(param) {
    return function() {
        myFunction(param);
    };
})(param) , 3000);

For more information check out:
setTimeout Internet Explorer


text:
Q: Do I have to create a surrogate key if I want to save space? Let's say I have a very large table with owners of cars like so:
OWNERSHIP
owner    | car
---------------
steven   | audi
bernahrd | vw
dieter   | vw
eike     | vw
robert   | audi
... one hundred million rows ...

If I refactor it to this:
OWNERSHIP
owner    | car <-foreign key TYPE.car_type
---------------
steven   | audi
bernahrd | vw
dieter   | vw
eike     | vw
robert   | audi
...

TYPE
car_type      |
---------------
audi
vw

Do I win anything spacewise or speedwise or do I need to create an INTEGER surrogate key on car_type for that?

A: The integer is going to take up 4 bytes, which is one more byte than "vw" will. As it happens, PostgreSQL enums take up 4 bytes too, so you won't gain anything storage-wise by switching to this representation (except for the difficulties it imposes on changing the enum itself). Querying will be as fast either way, because with a table that size you're going to be consulting the index anyway. Database performance, especially when tables get large, is essentially a matter of I/O, not CPU performance. I'm not convinced that an index on integers is going to be smaller or faster than an index on short strings, especially when you have a huge number of rows referencing a very small set of possible values. It's certainly not going to be the bottleneck in your applications.
Even if we assume that you were able to recover 4 bytes by using an artificial key, how much storage are you going to save? 4 bytes times 100 million rows would be about 400 MB ideally. Are you so pressed for storage that you need to eek out a small amount like that, on your honkin' database server? And this is assuming you refactor it into its own table and use a proper foreign key.
The right way to answer this, of course, is not to argue from first principles at all. Take your 100 million row table and work it both ways. Then examine the size yourself, like so:
SELECT pg_size_pretty(pg_total_relation_size('ownership')));
SELECT pg_size_pretty(pg_total_relation_size('ownership2')));

Do your test queries, with EXPLAIN ANALYZE like so:
EXPLAIN ANALYZE SELECT * FROM ownership WHERE car = 'audi';
EXPLAIN ANALYZE SELECT * FROM ownership2 WHERE car_id = 1;

Pay more attention to the actual time taken than the cost, but do look at the cost. Do this on the same database server as your production, if possible; if not, a similar machine with the same PostgreSQL configuration. Then you'll have hard numbers to tell you what you're paying for and what you're getting. My suspicion is that you'll find the space usage to be slightly worse with the artificial key and the performance to be equivalent.
If that's what you find, do the relational thing and use the natural key, and stop worrying so much about optimizing the physical storage. Space is the cheapest commodity you have.

A: Using two tables and string foreign key would of course use more space than using one. How much more depends on how many types of cars you have.
You should use integer car_id:

*

*Using integer keys would save space if significant percentage of car names would repeat.

*More so if you'd need to index car column, as integer index is much smaller than string index.

*Also comparing integers is faster than comparing strings, so searching by car should also be faster.

*Smaller table means that bigger part if it would fit in cache, so accessing it should also be faster.


text:
Q: How to fix 2D Array that prints as one column so this is what my code actually looks like, i was trying to make a simple 2d 10 by 10 array  with just zeros at first.  The zeros print in one column with breaks where a new column should be starting
   int[][] board = new int[10][10];

   for(int x=0; x<10; x++)
   {
       for(int y=0; y<10; y++)
       {
           board[x][y]=0;
       }
   }

   for(int x=0; x<10; x++)
   {
       for(int y=0; y<10; y++)
       {
           System.out.println(board[x][y] +"");
   }
       System.out.println("");
   }

it prints like this...
       0
       0
       0
       0
       0
       0
       0
       0
       0
       0

       0
       0
       0
       0
       0
       0
       0
       0
       0
       0

etc.
I've tried other formats, they usually come out the same.
I want it to look something like...
       0000000000
       0000000000
       0000000000

etc.

A: Using println, notice the ln suffix, indicates it adds a \n (new line) or \r (carriage return) or something similar causing a new line.
You will need to use a similar but seperate print function to print without the new line, like print.
So replace
System.out.println(board[x][y] +"");

with
System.out.print(board[x][y] +"");

This will print the positions in rows. But you will need to add a carriage return between each row. Which you already did with this line:
System.out.println("");

A: Why not use a StringBuilder and build line by line, then print.
for (int x = 0; x < 10; x++) {
   StringBuilder sb = new StringBuilder();

   for (int y = 0; y < 10; y++) {
      sb.append(" " + board[x][y]);
   }

   System.out.println(sb.toString());
}

A: for(int x=0; x<10; x++)
{
   for(int y=0; y<10; y++)
   {
       System.out.println(board[x][y] +"");
}
   System.out.println("");
}

should be
for(int x=0; x<10; x++)
{
   for(int y=0; y<10; y++)
   {
       System.out.print(board[x][y] +" ");
}
   System.out.println("");
}

bye

A: In your code you used println which will give output per line. Use print instead. Also I have removed +""
 for(int i=0;i<10;i++){
    for(int j=0; j<10;j++){
        System.out.print(board[i][j]);
    }
    System.out.println("");
 }


text:
Q: Is it not possible to store my local websites in my Dropbox folder? I have a bunch of web sites that I develop, and I run an Apache server locally to do debugging and design. The web sites use Apache, PHP, and MySQL. To be clear, my Apache server is not serving these sites to the internet, I just access them locally.
I develop on two machines. One desktop, and one laptop. Both are running Linux Mint, and I try to keep the settings consistent between them. This means I have to duplicate the Apache and PHP configurations. I keep the directory structures the same. I have to make sure to copy the MySQL databases from one machine to the other if I make changes.
Which is not ideal. It's prone to human error, especially with keeping the MySQL databases synched. Sometimes I work on one on one machine, forget to export and import the databases, and then after I've done work on the other machine, I have two versions and I can't easily merge them. Also, it's a hassle for making backups.
What does work is that I store all my HTML, CSS, and Javascript in a folder in my Dropbox directory. So any changes I make to those files are automatically syncronized. It also means I have a backup in the cloud. Should the need arise, to restore these files if I ever move to a new machine, I just have to install Dropbox and all the files are recovered.
The most I have to do if setting up on a new computer is create a symlink to my Dropbox directory where my HTML files are stored:
sudo ln -s  /home/dave/Dropbox/Websites /var/www/Websites

Is there a way I can do this with my Apache settings and MySQL databases as well? Where I can keep them synchronized across both machines in my Dropbox folder, and have a miminum of set up if I go to a new machine?

A: For apache you can easily put the sites-available in dropbox and then symlink the sites you want to enable to to the sites-enabled folder in /etc/apache2/sites-enabled/[name]
as for mysql it's a little tricky, cause the access is protected with apparmor,
you can copy /var/lib/mysql to dropbox and edit the data path in /etc/mysql/my.cnf, but to make it work you need to edit the app armor config check this link for details
I think that's all you need.

A: Rather than try and keep these files in Dropbox directly I would suggest using a tool such as rsync and a crontab entry to keep the different files backed up to your Dropbox folder.
Something like this:
rsync -avz /etc/apache2 /etc/mysql $HOME/Dropbox/mybackup/

A command like this can be expanded to include more files and directories as necessary. Additionally the command can be run from a crontab entry every few minutes/seconds.
On the other system you use rsync to "deploy" the files from your Dropbox to their real locations in /etc, /var, etc.


text:
Q: Laravel Policy not injecting current user I'm trying to bind a policy for a user that checks if he has a record in another table and a flag set to true. However, the policy I'm using doesn't inject the current user.
AuthServiceProvider.php
/**
 * The policy mappings for the application.
 *
 * @var array
 */
protected $policies = [
    \App\Http\Models\User::class => \App\Policies\UserPolicy::class,
];

App\Policies\UserPolicy
<?php

namespace App\Policies;

use App\Http\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    public function view(User $user)
    {
        return true;
        // currently just debug value
    }
}

In the laravel docs it's stated as:

All policies are resolved via the Laravel service container, meaning you may type-hint any needed dependencies in the policy's constructor and they will be automatically injected.

When using auth()->user()->can('view') - in a controller that depends on the records of the table I'll check - always returns false, no matter what. The only way to get it working is by calling
auth()->user()->can('view', auth()->user()) or $this->authorize('view', auth()->user())
What am I missing to get the first method to work?
EDIT: It doesn't matter if I typehint the user in the method itself or in the constructor as it seems to be ignored.


text:
Q: Possibly Incorrect Reopen review audit I just failed this audit:
https://stackoverflow.com/review/reopen/3259718
It was marked closed as "unclear what you're asking". That's not so; the question is perfectly clear. However, it is asking for answerers to "find a ... specific off site resource". Thus the question should be closed.
Is my reasoning wrong? Alternatively, are we supposed to reopen and then reclose questions using the correct reason? (Robert Harvey's answer here suggests that doing so is discouraged.)

A: You're misquoting that off-topic reason. It reads:

Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

Note that the word "specific" doesn't appear anywhere - indeed, a big problem with the questions this reason was created to address is that they're not specific, thus opening the door to lazy recommendations and spam. Indeed, the advice linked to is all about being more specific as to the problem being solved.
The question used in this audit isn't asking for folks to recommend their favorite Font Awesome reference - it's just looking for the canonical docs for a specific version of the software, and includes specific details as to where that documentation used to be found and how it's failing now. It seems quite specific.
While that might seem like an odd question to ask, it's more common than you might realize: some companies are, sadly, crap at maintaining stable links to stuff like this.
As such, there's only really one possible answer - thus eliminating the problems of subjectiveness and spam-attraction inherent in "recommendation" questions.


text:
Q: Button unclickable the second time I got a problem with my jQuery code, when I press the 'edit' button, and then the 'cancel' button, if I then press 'edit' again, it won't work.
HTML

<button class="edit" id="2">edit</button>

jQuery
$('.edit').click(function(){
        var id = $(this).attr('id');
        var post = $('div#'+id);
        var title = $('div#'+id+'>h1').html();
        var content = $('div#'+id+'>p').html();
        var edit = '<input type="text" class="title" id="'+id+'" value="title">
';
        var edit2 = '<textarea class="content" id="'+id+'" rows="10" cols="100">content</textarea>';
        $(this).remove();
        post.append(edit);
        post.append(edit2);
        post.append('
<button id="'+id+'" class="save">save</button><button id="'+id+'" class="cancel">cancel</button>');
        $('.cancel').click(function(){
            $('div#'+id+'>input').empty().remove();
            $('div#'+id+'>textarea').empty().remove();
            $(this).empty().remove();
            $('.save').empty().remove();
            $('div#'+id+'>br').remove();
            post.append('<button class="edit" id="'+id+'">Edit</button>');
        });
        /*$('.save').click(function(){
            var newTitle = $('input#'+id+'.title').val();
            var newContent = $('textarea#'+id+'.content').val();
            console.log(newTitle);
            console.log(newContent);
            console.log(id);
            $.post('/editPost', {id: id, title: newTitle, content: newContent}, function(){
                location.reload();
            });
        });*/
    });

jsfidde: http://jsfiddle.net/pHCT8/2/

A: Firstly you CANNOT use same ID on two elements, this will surely render browser and JS errors.
(Also if youre not using HTML5 DOCTYPE then you shouldn't have ID's starting with a number)
Then use jQuery on() syntax as a live handler:
$('#2').on('click','.edit', function(){

Note that the starting $('#2') is the outer limit of where you want the click listener to work. If you need it wide then use $('body').on('click','.edit', function(){ this will listen to all .edit clicks inside the whole body tag
Reason is that your click event handler only work upon elements loaded with the DOM, but your ajax edit function will create elements that wasn't in the DOM when loaded (dynamically created).

A: Rather than actually getting rid of the button, why not just .hide on click, then .show when you click cancel?
http://jsfiddle.net/pHCT8/5/
The changed portions are:
$(this).hide(); rather than $(this).remove;
$('.edit').show(); rather than post.append('<button class="edit" id="'+id+'">Edit</button>');

A: Instead of destroying and recreating the button(in which case you lose the event handlers) you can hide/show it
var self = $(this).hide();
...
$('.cancel').click(function(){
    ...
    self.show();

http://jsfiddle.net/mowglisanu/pHCT8/4/