text:
Q: Log4j filter in Grails Log4j DSL configuration Is there a way to specify a log4j filter in Grails log4j DSL configuration? I need to define something like this in my Grails log4j config:
<filter class="org.apache.log4j.filter.ExpressionFilter">
    <param name="expression" value="EXCEPTION ~= com.company.BackendNotAvailableException" />
    <param name="acceptOnMatch" value="false"/>
</filter>

I use Grails 1.3.7.

A: I have worked around this issue by adding a short init code to Bootstrap.groovy
Logger.rootLogger.allAppenders.each { appender ->
    ExpressionFilter filter = new ExpressionFilter()
    filter.expression = "EXCEPTION ~= org.springframework.security.authentication.*"
    filter.acceptOnMatch = false
    filter.activateOptions()
    appender.addFilter(filter)
}

A: Just an update, stumbled into this issue and found another solution (hope to serve this as a reference):
in Config.groovy,
Filter expFilter = new org.apache.log4j.filter.ExpressionFilter()
expFilter.setExpression('EXCEPTION ~= com.company.BackendNotAvailableException')
expFilter.setAcceptOnMatch(false)

log4j = {
    appenders {
        appender new DailyRollingFileAppender(
            ...
            // This is where we set the filter:
            headFilter: expFilter
            ...
        )
}

A: Thank you for your pointer. I did the same thing without an ExpressionFilter, so that I wouldn't have to load the additional Log4j Extras module, using a quick Groovy closure coercion:
import org.apache.log4j.Logger
import org.apache.log4j.spi.Filter

Logger.rootLogger.allAppenders*.addFilter({ event ->
    event.loggerName == "some.logger.name" && event.message =~ /text to ignore/
    ? Filter.DENY : Filter.NEUTRAL
} as Filter)

In my case I wanted to filter some spurious messages generated by Hibernate on startup, so I put that code in Config.groovy, because Bootstrap would be executed too late.


text:
Q: Angularjs limit to directive I'm trying to make a filter be used as a directive in Angularjs 1.4
What I want to make is to limit string using limitTo filter but as a directive not (|) filter.
I made this but it's not working
charlimit.js directive
function controller($scope) {
    $scope.length = 15;
}

angular.module('xApp')
  .directive('charlimit', function () {
    return {
      restrict: 'A',
      scope: {
        limitTo: '@',
      },
      controller: ["$scope", controller]
    };
});

index.html

Do you have any thoughts?
Thanks.

A:

var app = angular.module("xApp", []);

app.directive('charLimit', function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      var limitLength = parseInt(attrs.charLimit);
      scope.limittext = scope.limittext.substring(0, limitLength);
      return scope.limittext;
    }
  }
});

app.controller("IndexController", function($scope) {
$scope.limittext = 'Sample text';
});

{{limittext}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeORM using SoftTDelete @BeforeRemove Why is the @BeforeRemove trigger only executed with the manager.remove() method and it permanently deletes the record from the database table?
Why is this @BeforeRemove trigger not executed by manager.softRemove() for example?
It makes no sense to fill a deleted_at column and then delete the record using manage.remove()!
@BeforeRemove()
  delete() {
    this.deleted_by = 'MyName'
}

// Run only with manage.remove
async remove(request: Request, _response: Response, next: NextFunction) {
  let userToRemove: any = await this.userRepository.findOne(request.params.id);

  return await this.userRepository.softRemove(userToRemove);
}

// softRemove does not run @BeforeRemove /:

A: https://github.com/typeorm/typeorm/releases/tag/0.2.42
Resolved in the release 0.2.42
https://github.com/typeorm/typeorm/pull/8403


text:
Q: Find and update all the keys value in a nested JSON Arrays and Objects using Javascript I have below nested JSON data of Arrays and Objects
I need to update the all the keys value in string from english to spanish in javascript or NodeJS or AngularJS
    {
      "firstrootkey" : [ //Array of 6 objects
      {  //1st object
        "key1" : "valueinstring",
        "key2" : randomnumbers
      },..... ],
      "secondrootkey" : { //having 7 objects
        "One" : [ { //each object having array of n objects
          "name" : "valueinstring",
          "id" : randomnumbers
        }, ......],
        "two two" : [ { // array of m objects
          "keya" : "valueinstring",
          "keyb" : randomnumbers
        },.......],
      .
      .
      .

      },
      "third root key" : { //having n objects
        "sdfdsfsfs" : [ { //each object having array of n objects
          "keyc" : "valueinstring",
          "keyhuh" : 858556
          "hgjhgj" : 6789
        },.... ],
        .
        .
        .
        .
        .
        }
    }

I tried to somany methods but none of them working...
one of the approach
   for (var rootKey in jsonEnglish) {
    var rootValue = jsonEnglish[rootKey];
      if (rootValue.isArray) { // function iterate Array objects
        //loop each array
          // if every array is object -- function iterate object
            // find value in object
              //if value not array and object
                 // then pass value to translator
                  //and update the value with translated value
              //else if its object
                  //

Give some directions to approach

A: Ok, start by validating your JSON here http://jsonlint.com/
Then in javascript you can access json and use it with XMLHttpRequest()
var xmlhttp = new XMLHttpRequest();
        var url = "yourdata.json";

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var json_array = JSON.parse(xmlhttp.responseText);
                parseJson(json_array);
        }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    json_data += "
Variable Access through array structure: " + json_array.firstrootkey[0].key1+ "
";
    json_data += "
Access Array inside array item: " + json_array.secondrootkey[0].one[0].name + "
";

    document.getElementById("display_json").innerHTML = json_data;

Also, there is a syntax error on line 7. Also, to test your code you a need a working web server. I prefer appserv.
Here is some JSON that is right and verified on JSONlint.com
{
    "firstrootkey": [{
    "firstName": "Shane",
    "lastName": "Burton",
    "id": [
        1, 2, 3, 4, 5, 6, 7, 8
    ],
    "credits": "24"
}],
"secondrootkey": [{
    "One": [{
        "firstName": "Shane",
        "lastName": "Burton",
        "id": [
            1, 2, 3, 4, 5, 6, 7, 8
        ],
        "credits": "24"
    }]
}]
}

Second JSON OBJECT Each set of brackets represents one row in your database/list
Since you're using a foreach loop I would make it one object for simplicity sake.
{
"foreachloopobject": [{
    "firstrootkey": [{
        "firstName": "Shane",
        "lastName": "Burton",
        "id": [
            1, 2, 3, 4, 5, 6, 7, 8
        ],
        "credits": "24"
    }],
    "secondrootkey": [{
        "One": [{
            "firstName": "Shane",
            "lastName": "Burton",
            "id": [
                1, 2, 3, 4, 5, 6, 7, 8
            ],
            "credits": "24"
        }]
    }],
    "firstrootkey": [{
        "firstName": "Shane",
        "lastName": "Burton",
        "id": [
            1, 2, 3, 4, 5, 6, 7, 8
        ],
        "credits": "24"
    }],
    "secondrootkey": [{
        "One": [{
            "firstName": "Shane",
            "lastName": "Burton",
            "id": [
                1, 2, 3, 4, 5, 6, 7, 8
            ],
            "credits": "24"
        }]
    }]
}]
}


text:
Q: How to get a centred rolling mean? I want to compute the rolling mean of data taken on successive days. If I just use dataframe.rolling(7) the mean is from the previous week.  Instead I would like day to be at the centre of the window the mean is computed over not right at the end.  Is there an easy/fast way to get such a centred rolling mean of a pandas Series?

A: df.rolling(7, center=True).mean()

The rolling mean can be centered by setting the center argument to True.
Example plot

A: df.shift(-4).rolling(7).mean()

Should do the trick.


text:
Q: MySQL REGEXP Match / or End of Field I've got a load of paths in a MySQL Database (5.7.17-0ubuntu0.16.04.2) and the user chooses a selection of paths, I want to select all those paths and those below, but I've hit an issue.
Say the user wants "/root/K" I need to do a select for:
a. /root/K%
b. /root/K

How can I get the REGEXP to match the end of a field or a / ?
I've tried the following:
original query:
where path REGEXP ('/root/K/|/root/J/J/')  # this works but doesn't show the items in that path, only ones below

where path REGEXP '/root/K[/\z]' # does the same as above
where path REGEXP '/root/K(?=/|$)'   # Get error 1139, repetition-operator invalid

I've also tried: Regex to match _ or end of string but that gives error 1139
Any other suggestions?

A: There is no support for lookarounds, not \z anchor in MySQL regex. You may use a normal capturing group:
WHERE path REGEXP '/root/K(/|$)'

It will match

*

*/root/K - literal char sequence

*(/|$) - either / or end of entry.


text:
Q: SwiftUI Xcode 11 beta 7 @Binding for collections is breaking preview This was working until beta 7. It seems that when I want to pass one element in a collection as a binding to another view, the preview gets broken
I followed the release notes where it says @Binding no longer conforms to collection protocol comments are at the bottom
I have Catalina and xcode in beta 7
Parent:
struct SimpleStructure {
    var label: String
}

struct ContentView: View {
    @State private var myVariables = [SimpleStructure(label: "hello")]

    var body: some View {
        ChildView(myVariables: $myVariables)
    }
}

Child
struct ChildView: View {
    @Binding var myVariables: [SimpleStructure]
    var body: some View {
        List(myVariables.indexed(), id: \.1.label) {(index, variable) in
            GrandChildView(myVariable: self.$myVariables[index])
        }
    }
}

GrandChild
struct GrandChildView: View {
    @Binding var myVariable:SimpleStructure
    var body: some View {
        Text(myVariable.label)
    }
}

UPDATE:
Still an issue with Beta 8

A: The release notes have a typo. You need to change:
var endIndex: Index { base.startIndex }

with
var endIndex: Index { base.endIndex }

A: Dunno, is this one solved for you? If not, maybe this helps:
struct ChildView: View {
    @Binding var myVariables: [SimpleStructure]

    var body: some View {
        List(myVariables.indices) { index in
            GrandChildView(myVariable: self.$myVariables[index])
        }
    }
}

If solved, either mark the correct answer, or provide a solution here by yourself in case you may have found one in the meantime.

A: The issue was fixed in SwiftUI Beta 10


text:
Q: Find previous cell address (to the left) in active row with different value than active cell value I,ve tried to find a VBA solution for finding the previous cell (located on the same row) with different value than the selected cell has. So if the selected cell is for example [N6] (as in my picture) then my search range should be ("A6:N6") from which I need to find the last cell with a different cell value (which would be cell [L6] in my picture because it's the previous cell with a different value than cell [N6]. The search should start from the end (N6,M6,L6...) backwards until the first match is found (first different cell value). When the first match is found then select it. I have hundreds of columns, so my picture is just to show the principle. I execute my vba code with Private Sub Worksheet_SelectionChange(ByVal Target As Range) so when the user selects a cell with the mouse. I get the desired cell with {=ADDRESS(6;MATCH(2;1/(A6:O6<>"D")))} but I would need a VBA solution for my problem. My current VBA solution takes me to cell [I6] instead of [L6] and I can't figure out how to edit my code to find the correct cell ([L6] in my example picture).
Dim rngSel As String, rngStart As String
Dim rngActiveStart As Range
rngSel = ActiveCell.Address(0, 0)
rngStart = Cells(ActiveCell.Row, 1).Address(0, 0)
Set rngActiveStart = Range(rngStart & ":" & rngSel)

Dim c
    For Each c In rngActiveStart.Cells
        If c <> Target.Value And c.Offset(0, 1) = Target.Value Then
                c.Select
                MsgBox "Previous different cell: " & c.Address(0, 0)
            Exit For
        End If
    Next

A: Using selection_Change
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim r As Long, col As Long, x
    Dim v As String

    r = Target.Row
    v = Target.Value
    Application.EnableEvents = False

    For x = Target.Column To 1 Step -1

        With Me
            If .Cells(r, x) <> v Then
                .Cells(r, x).Select
                Exit For
            End If
        End With

    Next x

    Application.EnableEvents = True

End Sub

A: You need a For i = max To min Step -1 loop to loop backwards/left:
Public Sub MoveLeftUntilChange()

    Dim SelRange As Range 'remember the selected range 'N6
    Set SelRange = Selection

    Dim iCol As Long
    For iCol = SelRange.Column To 1 Step -1 'move columns leftwards
        With SelRange.Parent.Cells(SelRange.Row, iCol) 'this is the current row/column to test againts the remembered range N6
            If .Value <> SelRange.Value Then 'if change found select and exit
                .Select
                Exit For
            End If
        End With
    Next iCol

End Sub


text:
Q: Odoo 14 in Docker: Database connection failure: could not connect to server: Connection refused I'm running Odoo 14 in a Docker container, linked to another container with PostgreSQL. I've had this setup for a month now, but yesterday I noticed that the Odoo container kept restarting every minute. According to the log:
Database connection failure: could not connect to server: Connection refused

Is the server running on host "172.17.0.3" and accepting

TCP/IP connections on port 5432?

As far as I can tell, the server is indeed running on that IP address and port - I'm using Docker's bridge network. Besides, it's not like I've made any changes to the environment since Odoo was first set up.
Both containers are running on a Synology NAS and were set up using the Synology Docker GUI. Below are the seetings for the Odoo container (odoo-app) and the PostgreSQL container (odoo-postgres):

Can anyone help me understand what's wrong and how to sort it out?
Thanks!

A: I suspect that, because I had opted for the "latest" Postgres container, a recent update might have knocked things out of balance.
I've just successfully restored the initial setup with Odoo 14 and PostgreSQL 13.


text:
Q: SMB Port 139 not enabled on Mac OS 10.15 Catalina I'm trying to share a folder on my local network in order to use a scanner that can upload files over SMB protocol towards a Mac Catalina 10.15.
My Mac is on my local network with IP address 192.168.1.54
The scanner is an old scanner, it can't use the 445 port, but it works perfectly with Windows 10 on port 139.
I've tried:
sudo lsof -iTCP -sTCP:LISTEN -n -P | grep :139

It returns nothing, so I think that the 139 port is not listening.
I've tried to open a Windows VM on the Mac, and:
telnet 192.168.1.54 445

it connects, but:
telnet 192.168.1.54 139

don't work.
I've tried also the suggestion reported here What causes some Network Drives using SMB no longer connect to macOS Catalina?, but even adding the file /etc/nsmb.conf the port 139 is still not working.
I also made a system reboot, but nothing has changed.
Any idea?
Thanks


text:
Q: Warnings with the hapi library I am presenting many warnings when installing things in my project because of this:
warning @hapi/hapi > @hapi/joi@17.1.1: joi is leaving the @hapi organization and moving back to 'joi'
(https://github.com/sideway/joi/issues/2411)
warning @hapi/hapi > @hapi/catbox > @hapi/joi@17.1.1: joi is leaving the @hapi organization and
moving back to 'joi' (https://github.com/sideway/joi/issues/2411)
warning @hapi/hapi > @hapi/joi > @hapi/formula@2.0.0: This version has been deprecated and is no
longer supported or maintained
warning @hapi/hapi > @hapi/heavy > @hapi/joi@17.1.1: joi is leaving the @hapi organization and moving
back to 'joi' (https://github.com/sideway/joi/issues/2411)
warning @hapi/hapi > @hapi/shot > @hapi/joi@17.1.1: joi is leaving the @hapi organization and moving
back to 'joi' (https://github.com/sideway/joi/issues/2411)
warning @hapi/hapi > @hapi/statehood > @hapi/joi@17.1.1: joi is leaving the @hapi organization and
moving back to 'joi' (https://github.com/sideway/joi/issues/2411)
warning @hapi/hapi > @hapi/podium > @hapi/joi@17.1.1: joi is leaving the @hapi organization and
moving back to 'joi' (https://github.com/sideway/joi/issues/2411)
warning @hapi/hapi > @hapi/teamwork@4.0.0: This version has been deprecated and is no longer
supported or maintained
warning @hapi/hapi > @hapi/podium > @hapi/teamwork@4.0.0: This version has been deprecated and is no
longer supported or maintained

Check other similar questions in SO and it didn't work for me, this is package.json (I already modified Joi)
I have modified the package-lock.json, I have made the ncu -u to check outdated dependencies, I install them and it doesn't work either
 "dependencies": {
"@capacitor-community/fcm": "^1.0.8",
"@capacitor/android": "^2.4.0",
"@capacitor/cli": "^2.4.0",
"@capacitor/core": "^2.4.0",
"@capacitor/ios": "^2.4.0",
"@hapi/formula": "^3.0.0",
"@hapi/hapi": "^19.2.0",
"@hapi/teamwork": "^5.1.0",
"@hapi/topo": "^5.0.0",
"@ionic/core": "^5.3.1",
"@ionic/pwa-elements": "^3.0.1",
"@ionic/react": "^5.3.1",
"@ionic/react-router": "^5.3.1",
"@sentry/browser": "^5.20.1",
"@testing-library/dom": "^7.21.5",
"@testing-library/jest-dom": "^5.11.1",
"@testing-library/react": "^10.4.7",
"@testing-library/user-event": "^12.0.15",
"@types/history": "^4.7.7",
"@types/jest": "^26.0.7",
"@types/jsonwebtoken": "^8.5.0",
"@types/lodash": "^4.14.158",
"@types/node": "^14.0.26",
"@types/pouchdb": "^6.4.0",
"@types/react": "^16.9.43",
"@types/react-dom": "^16.9.8",
"@types/react-router": "^5.1.8",
"@types/react-router-dom": "^5.1.5",
"@types/react-tracking": "^7.0.4",
"@typescript-eslint/eslint-plugin": "^3.7.1",
"@typescript-eslint/parser": "^3.7.1",
"axios": "^0.19.2",
"caniuse-lite": "^1.0.30001107",
"chokidar": "^3.4.1",
"eslint": "^7.5.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"firebase": "^7.17.1",
"immer": "7.0.7",
"ionicons": "^5.1.2",
"joi": "^17.1.1",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.19",
"moment": "^2.27.0",
"node-sass": "^4.14.1",
"npm-check-updates": "^7.0.2",
"pouchdb": "^7.2.2",
"prettier": "^2.0.5",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-app-rewire-workbox": "^2.0.1",
"react-app-rewired": "^2.1.6",
"react-dom": "^16.13.1",
"react-redux": "^7.2.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
"react-tracking": "^7.3.0",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"source-map-resolve": "^0.6.0",
"typescript": "3.9.7",
"unstated-typescript": "2.1.7",
"urix": "^0.1.0",
"webpack": "^4.44.0",
"workbox-build": "^5.1.3",
"workbox-webpack-plugin": "^5.1.3"
},
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
  ">0.2%",
  "not dead",
  "not op_mini all"
],
"development": [
  "last 1 chrome version",
  "last 1 firefox version",
  "last 1 safari version"
]
},
"optionalDependencies": {
"fsevents": "^2.1.3"
}
}

A: As stated here link, Joi modules are moved over some other place and as for now you are required to change your package.json file and require statements. If that doesn't work try reversing back to old way of using Joi and see if that works. It did in my case
Or try uninstalling @hapi/joi and install it with npm i joi or yarn add joi


text:
Q: I want to make a entire row from a gridview "ReadOnly" I am using a Gridview and so far everything is working great! My question is how do I make the current row as a read only if a specific condition become false? I have tested and tried a few examples but with no luck.
I found a way to make the column read only but im unable to make the entire row read only.
Thanks in advance,
Irfan

A: Use event ShowingEditor.
private void  myGridView_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e) {
    var gv = sender as GridView;
    if (/* your condition to determine if the row is readokly */ ) {
        e.Cancel = true;
    }
}


text:
Q: What was Arya afraid of? In Eldest, when Eragon is traveling to the Du Weldenvarden, Eragon asks Arya what is wrong. Arya states, she is afraid. What was she afraid of?
For reference, this is found at the end of chapter Arya Svit-Kona, on page 164 in my copy of the book. It takes place immediately after Arya introduces Eragon in Elf customs.

A: After reading further in the book, I discovered the answer.

 Arya was afraid to meet her mother, the Queen. The last time that she had seen her, there had been a fight, and she was afraid for what her mother might say or do. Still, she knew that it was required of her, so she did it.


text:
Q: When downloading a javascript file from the internet, where does it go? I'm using a code like this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.js"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
// Save this following url to load the file
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
NSString *javaScript = [NSString stringWithContentsOfURL: __URL_YOU_SAVED_AVOBE__ encoding:NSUTF8StringEncoding error: nil];

[webView stringByEvaluatingJavaScriptFromString:javaScript];

Every time the app is opened, this code downloads a js file and loads it on to a uiwebview. What happens to the javascript file that is downloaded and loaded onto the uiwebview? Is it saved in the app? Is it saved on the iPhone? Every time the app is opened and the file is downloaded, is it taking up GB and memory on the iPhone? But seriously, where does the file go? lol

A: The file save on disk with the destination when you created the NSURLSessionDownloadTask.
You can delete the file with NSFileManager for sure, check it's api.
If you want a execute only js file, use NSString load from the source url so the "JS String" will be on RAM only every time you call this action.Then you can execute it on your webview as js.
Satisfy?


text:
Q: ajax/ssl/X-Forwarded-For Ok, I'm using pen for load balancing.  My apache servers see the remote IP as the IP of the load balancer.  I need the apache server to be able to see the IP address of the client for various reasons.  I can use X-Forwarded-For to get that out of a non-encrypted page, but it's not part of an SSL page...
So, not knowing Ajax, I'm wondering.  Could I use ajax to pull the X-Forwarded-For out of a non encrypted page, and set it as a variable on the client side? I know it's possible, I'm just wondering if anyone has done this, and does this cause a security error in the browser.
I thought that I could redirect them to a non-ssl page, then put the IP in a cookie, then back to the SSL page, but I think that's hokey too.
Anyway other way to get the ip to the script will work too. I tried http://stderr.net/apache/rpaf/, but it's not aware of the IP either.

A: AJAX is limited by same-origin policy, and different protocols are considered different origins, so you wouldn't be able to make HTTP AJAX request from HTTPS page.
Attempt to do it via other means could cause browsers warn about mixed secure and insecure content.
Putting IP in a cookie on HTTP page (ideally signed or stored in server-side session referenced by the cookie) would work, but it will not be as secure as reading actual IP of SSL session (since attacker could manipulate HTTP cookies, and you can't set a HTTPS-only cookie).
Another solution to this is to end SSL at the load balancer and forward it as HTTP traffic to Apache.
Yet another approach would be to use lower-level load balancing — NAT — that preserves source address.


text:
Q: Memory exploitation for setting member variables of a Structure in one step The below algorithm can output 99 0000
Would you please let me know how does this following line of code work?
*(long*)&(st->flag1) = 0;
The algorithm is:
#include <stdio.h>

struct SpecialFlags{
 int  id;
 char flag1;
 char flag2;
 char flag3;
 char flag4;
};

void ClearFlags( SpecialFlags *st )
{
  *(long*)&(st->flag1) = 0;
}

int main(void)
{
  SpecialFlags flags;
  flags.id =    99;

  flags.flag1 = 1;
  flags.flag2 = 2;
  flags.flag3 = 3;
  flags.flag4 = 4;
  ClearFlags( &flags );

  printf( "%d %d%d%d%d\n", flags.id,
    flags.flag1, flags.flag2,
    flags.flag3, flags.flag4 );
  return 0;
}

A: In the Below structure
struct SpecialFlags{
        int  id;
        char flag1;
        char flag2;
        char flag3;
        char flag4;
};

        id       flag1     flag2     flag3      flag4
     --------------------------------------------------
     | 99      | 1(49)    | 2(50)   | 3(51)   |  4(52) |
     ---------------------------------------------------
   0x100     0x104       0x105     0x106      0x107   0x108 <--lets say starting address is 0x100

When ClearFlags() is called st points to beginning of the structure. And when you do *(long*)&(st->flag1) = 0; First address of st->flags1(char type) gets converted to long* type that means it will fetch 4 bytes at a time and finally * means value in that 4 bytes.
From above figure

*

*(long*)&(st->flag1) => from 0x104 address till next 4 byte i.e till 0x108

**(long*)&(st->flag1) => what value is there in between 0x104 location to 0x108 location

**(long*)&(st->flag1) = 0 => what value is there in between 0x104 location to 0x108 location, will be overwritten with 0(zero)
After this statement your structure looks like
       id       flag1     flag2     flag3      flag4
     --------------------------------------------------
     | 99      | 0(48)    | 0(48)   | 0(48)   |  0(48) |
     ---------------------------------------------------
   0x100     0x104       0x105     0x106      0x107   0x108

Now when you prints flags.flag1, flags.flag2.. it prints 0.


text:
Q: in javascript I want to creat a simple few lines function to get Heikin-Ashi from close high low open This question if about javascript (not pyhton or pine script).
I just want to create a simple few lines function => "convert" FROM regular open, high, low and close from an exchange TO a Heikin Ashi
variables open, high, low, close are from an exchange API that return an array with regual candlesticks
here the formula
ha_open = (last_ha_open - last_ha_close) / 2;
ha_close = (open + high + low + close)/4;
ha_high = max(high, ha_open, ha_close);
ha_low = min(low, ha_open, ha_close);

where I get "stuck" is the "last_ha_open" and "last_ha_close"
**** it's easy to save ha_open and ha_close with .push into an array
**** it's easy to retrieving them with array[(array.length -1)] (last of array)
**** it's where it gets tricky... : the infinite loop of calculate the first in the chain.. if wrong, the values don't match...
is there a javascript way to do this ????
Notes i could find about Heikin-ashi
Obs:
The first Heikin-Ashi close equals the average of the open, high, low and close ((O+H+L+C)/4).
The first Heikin-Ashi open equals the average of the open and close ((O+C)/2).
The first Heikin-Ashi high equals the high and the first Heikin-Ashi low equals the low.


text:
Q: Are fitted.values available in pglm? I am using the pglm function in R to fit a Poisson fixed-effects model. According to the documentation, the pglm object should have fitted.values. However, fitted.values(model-name) returns "NULL".
When I run AIC(model-name) the AIC is followed by "attr(,"fitted.values")" and a long list of number (see example below).
Are these fitted values? If so, is there a way to obtain them directly? Can I also get fitted-values based on a synthetic dataset (i.e. predict())?
install.packages("pglm")
library(pglm)

data("PatentsRDUS", package="pglm")

     model-name <- pglm(patents ~   log(rd)  + as.numeric(year)+ I(log(capital72)*as.numeric(year)) , PatentsRDUS,
     family = poisson(link=log), model = "within", index = c("cusip", "year"))

     fitted.values(model-name)
     AIC(model-name)


text:
Q: How do I remove the black translucent overlay over the background when I scale my windows in Linux Mint via editing the codes? I know it's caused by themes as some themes has it and some don't. But I really like to keep my mint-Y-Dark theme as it looks awesome. And thus, this question arisen, I know there are some codes to it and editing them will resolve the problem but I don't know what code it is and from where is it in the mint-Y-Dark theme folder. I am using Linux mint 18 Cinnamon.
Here is the desktop; not scaled:

Here is the scaled window, notice the tranlucent black overlay:

A: Mint-Y theme folders:
~/.themes/Mint-Y
~/.themes/Mint-Y-Dark
~/.themes/Mint-Y-Darker

It should be in ~/.themes/Mint-Y-Dark/cinnamon/cinnamon.css
Please download today's version of the theme:
https://github.com/linuxmint/mint-y-theme/archive/master.zip
Instructions from GitHub on editing:
Do not makes modifications to the theme directly in the usr/share/themes directory. These are automatically generated from the files located in the src/ directory. Each subdirectory contains its own individual instructions on how to edit. Once edits are made you can generate the final themes by running the build-themes.py script.
Best would be a regular update the icons and themes using a script:
#!/bin/bash

mkdir -p ~/Downloads/themes-mint/

wget -O ~/Downloads/themes-mint/themes.zip https://github.com/linuxmint/mint-y-theme/archive/master.zip
wget -O ~/Downloads/themes-mint/icons.zip https://github.com/linuxmint/mint-y-icons/archive/master.zip

unzip -o ~/Downloads/themes-mint/themes.zip -d ~/Downloads/themes-mint/
unzip -o ~/Downloads/themes-mint/icons.zip -d ~/Downloads/themes-mint/

cp -r ~/Downloads/themes-mint/mint-y-theme-master/usr/share/themes/* ~/.themes/
cp -r ~/Downloads/themes-mint/mint-y-icons-master/usr/share/icons/* ~/.icons/

Save it as a text file in your home directory, name it e.g. update-themes and run chmod 700 update-themes, then always use it like ./update-themes.


text:
Q: improving wordpress rest api speed I have a simple wordpress plugin that defines an endpoint.
I need to load only core wordpress functionality so i can improve response times. Below is the content of my wordpress plugin
<?php
/**
 * Plugin Name: Vunjabei plugin
 * Plugin URI: http://hawavunjabei.com/vunjabei
 * Description: A plugin for customizing Hawa vunjabei wordpress stack
 * Version: 1.0
 * Author: oxo africa
 * Author URI: http://www.oxoafrica.co.tz
 */

// Tell WordPress to only load the basics
define('SHORTINIT',1);

// get path of wp-load.php and load it
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';

add_action( 'rest_api_init', function () {
  register_rest_route( 'v1', '/getTime', array(
    'methods' => 'GET',
    'callback' => 'woocommerceSimpleRoute',
  ) );
} );

function woocommerceSimpleRoute( $data ) {
    wp_send_json( array( 'time' => time() ) );

}

Calling the endpoint /v1/getTime via the plugin returns a response in 1.5seconds, that's pretty bad for such a simple request.

If i put the script in a plain php file , the result is remarkable , the response gets returned in only 300 milliseconds

How can i fine tune the plugin version to improve the response speed ?

A: As I understand you don't use any additional WP plugins, just WordPress out of the box. So they cann't slow your site.
Do you run your website locally (on Windows machine or what over) or using some hosting (on Linux or what over)? Sometimes local env is slow/unoptimized.
You should also understand that in the process of WP initializing there are many calculations that a typical PHP file does not do.
Without specifics, I can only advise enable caching via some existing WP plugins.


text:
Q: ASP-routing from tavlerow instead of anchor I'm trying to learn asp.net and I'm trying to use the ASP routing directly from the tablerow (tr), instead of for each anchor point inside the cell.
Below code, I'm able to click the "Case ID" in my table, but this leaves some unclickable area around the actual text. I basically want to be able to simply select the row and pass the @sc.ID for a database query in the ViewCase-page.I want end-user to click "category" (and several columns in the future), without having to define  tags everyhwere.
@foreach (var sc in Model.Cases)
{

            Case @Html.DisplayFor(Moldel  => @sc.ID)

            @Html.DisplayFor(Moldel  => @sc.Category)

}

A: It seems you do not want not want to specify the a tag every where. Tag helper does not work for table element, you just add js in the tr element like below:

    @foreach (var sc in Model.Cases)
    {

                Case @Html.DisplayFor(Moldel  => @sc.ID)

                @Html.DisplayFor(Moldel  => @sc.Category)

    }


text:
Q: PMOSFET Ideal Diode for 24V After some browsing I found transistor circuit very similar to my needs:
Understanding an 'ideal' diode made from a p-channel MOSFET and PNP transistors
Unfortunately its application is limited by the Emitter-Base breakdown voltage of used PNP transistors. Does anybody know similar circuits for 24V?
Thank you in advance.

A:
simulate this circuit – Schematic created using CircuitLab
Can you work with a discrete version with a higher PIV rating for D2?


text:
Q: In Swift NSData contentsOfURL function is gradually increase memory in use func saveImage(tweet: Dictionary<String, AnyObject>)
{
    var names : Array<String> = []
    var urls : Array<String> = []

    if let entity = tweet["extended_entities"] as? NSDictionary {
        if let mediatag = entity as? Dictionary<String, AnyObject> {
            if let medias = mediatag["media"] as? NSArray {
                if let mediaSwift = medias as? Dictionary<String, AnyObject>[]
                {
                    for i in 0..mediaSwift.count {
                        if let url = mediaSwift[i]["media_url"] as? NSString
                        {
                            urls.append(url + ":orig")
                            let nsstring = url as NSString
                            let splits = nsstring.componentsSeparatedByString("/") as Array<String>
                            names.append(splits[splits.endIndex-1])
                        }
                    }
                }
            }
        }
    }

    for i in 0..names.count
    {
        let string: NSString = urls[i]
        let nsurl = NSURL(string: urls[i])
        let nsdata = NSData(contentsOfURL: nsurl, options: NSDataReadingOptions.DataReadingUncached, error: nil)
    }
}

I write simple swift app that save user's twitter picture.
But, after I add simple line below
let nsdata = NSData(contentsOfURL: nsurl, options: NSDataReadingOptions.DataReadingUncached, error: nil)

It consume too much memory and release small memory. So my app's memory is gradually increase.

Each action contains 150 urls and each url contain image about 400kb.
Is there are any mistake?
Please help.
Thanks in advance
https://github.com/newpolaris/shiny-ninja.git


text:
Q: Android Studio Cannot resolve symbol R I'm having this problem in a project. If I open a previous project, it works. If I create a new one, it doesn't work. It doesn't even complete the build, keeps stuck on executing tasks. So I guess it's not a xml problem, since it's happening to all new projects. This bug started yesterday.
I already tried these solutions:
-Clean and build
(It takes forever on "executing tasks". Usually when it's around 20 or 30 minutes I close the project. – My gradle is already set to work offline and it does great in previous projects)
-Reinstall platform build tools
Also, I got this external ide error some minutes ago.
 No message
com.intellij.openapi.externalSystem.model.ExternalSystemException:
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:238)
    at com.android.tools.idea.gradle.invoker.GradleTasksExecutor.invokeGradleTasks(GradleTasksExecutor.java:416)
    at com.android.tools.idea.gradle.invoker.GradleTasksExecutor.run(GradleTasksExecutor.java:222)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:126)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:366)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:55)

I have no clue what else I can do. Please help me.
Main Activity
    package example.appmedico;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button btProx, btEsp;
    TextView tvAche;
    Context ctx = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvAche = (TextView)findViewById(R.id.tvAche);
        btProx = (Button)findViewById(R.id.btProx);
        btProx.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(ctx,NearbyActivity.class);
                startActivity(intent);
            }
        });

    }

XML
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="example.appmedico.MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Ache médicos por:"
        android:id="@+id/tvAche"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Proximidade"
        android:id="@+id/btProx"
        android:layout_marginTop="20dp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Especialidade"
        android:id="@+id/btEsp"
        android:layout_marginTop="10dp" />
</LinearLayout>

A: Try restart/invalidate cache, or delete .iml file and import project

A: Open Build.gradle(Project level)
remove everything after your android studio version in dependencies like alhpa  or beta something.
Example:
My Android Studio version is 2.2.2 so my dependencies will be:
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

A: The simplest way to solve it is to create a new project and add the previous project code to it, it is likely you have an error in code or resources name.
Also try to rebuild the project.
If it doesn't work then the go to File/Invalidate Caches Restart

A: Finally it worked. When I invalidated caches and restarted the R error was gone, but everything was still very slow. I've try many solutions, but in the end I decided to delete many files to clean my computer (almost 100G was gone). Now it works fine, up to 2 or 4 minutes for graddle to build.


text:
Q: problemas al calcular porcentaje con array saludos comunidad tengo un problema a la hora de calcular el porcentaje ya que ahora utilizo los input como array y no me funciona el mínimo de campos son 4 y el máximo de campos son 14 también tengo mi función para agregar campos si lo deseo, pero como dije no me funciona y no me hace el calculo, anexo los códigos.
archivo anadircarrerascaballos.php

<input id="ejemplar" type="text" name="ejemplar[]" autocomplete='off' title='no pueden haber campos vacios, solo se permiten letras.' pattern='[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+' required/>
Ejemplar:

<input id="peso" type="text" name="peso[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{2,2}'  required/>
Peso:

<input id="dividendo" type="text" name="dividendo[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.'  required/>
Dividendo:

<input id="icon_prefix" type="text" class="black-text" name="porcentaje[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' onblur="multiplica(this.form)"  required/>
porcentaje:

 <input id="total" type="text" name="total[]" readonly/>
 Total:

 <input id="ejemplar" type="text" name="ejemplar[]" autocomplete='off' title='no pueden haber campos vacios, solo se permiten letras.' pattern='[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+' required/>
 Ejemplar:

  <input id="peso" type="text" name="peso[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{2,2}'  required/>
  Peso:

 <input id="dividendo" type="text" name="dividendo[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{1,2}' required/>
   Dividendo:

   <input id="porcentaje" type="text" name="porcentaje[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' onblur="multiplica(this.form)" pattern='[0-9]{1,2}' required/>
    porcentaje:

     <input id="total" type="text" name="total[]" autocomplete="off" readonly/>
   Total:

  <input id="ejemplar" type="text" name="ejemplar[]" autocomplete='off' title='no pueden haber campos vacios, solo se permiten letras.' pattern='[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+' required/>
  Ejemplar:

  <input id="peso" type="text" name="peso[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{2,2}'  required/>
   Peso:

   <input id="dividendo" type="text" name="dividendo[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{1,2}' required/>
   Dividendo:

  <input id="porcentaje" type="text" name="porcentaje[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' onblur="multiplica(this.form)" pattern='[0-9]{1,2}' required/>
  porcentaje:

    <input id="total" type="text" name="total[]" autocomplete="off" readonly/>
   Total:

   <input id="ejemplar" type="text" name="ejemplar[]" autocomplete='off' title='no pueden haber campos vacios, solo se permiten letras.' pattern='[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+' required/>
    Ejemplar:

    <input id="peso" type="text" name="peso[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{2,2}'  required/>
      Peso:

    <input id="dividendo" type="text" name="dividendo[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{1,2}' required/>
     Dividendo:

     <input id="porcentaje" type="text" name="porcentaje[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' onblur="multiplica(this.form)" pattern='[0-9]{1,2}' required/>
       porcentaje:

      <input id="total" type="text" name="total[]" autocomplete="off" readonly/>
     Total:

funcion multiplica

funcion_agregar_campos.js
var inputs = 4;
$(document).ready(function(e) {
$('#agregar').on('click', function() {
if (inputs == 14) {
  return false;
   }
  inputs = inputs + 1;
  if ($('#ejemplar' + inputs + '').length > 0) {
  $('#ejemplar' + inputs + '').show();
  } else {

    $('.inputs').append('

<input id="ejemplar" type="text" name="ejemplar[]" autocomplete="off"  title="no pueden haber campos vacios, solo se permiten letras." pattern="[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+" required/>Ejemplar:

<input id="peso" type="text" name="peso[]" autocomplete="off" title="no pueden haber campos vacios, solo se permiten numeros." pattern="[0-9]{2,2}" required/>Peso:

<input id="dividendo" type="text" name="dividendo[]" autocomplete="off" title="no pueden haber campos vacios, solo se permiten numeros." pattern="[0-9]{2,2}" required/>Dividendo:

<input id="porcentaje" type="text" name="porcentaje[]" autocomplete="off" title="no pueden haber campos vacios, solo se permiten numeros." pattern="[0-9]{2,2}" required/>porcentaje:

<input id="total" type="text" name="total[]" autocomplete="off" readonly/>Total:

');

     }

      $('#quitar').fadeIn();
      if (inputs == 14) {
      $('#agregar').fadeOut();

        }
         });
          $('#quitar').on('click', function() {
           if (inputs == 4) {
           return false;
           }
              $('#ejemplar' + inputs + '').hide();
              inputs = inputs - 1;
              $('#agregar').fadeIn();
              if (inputs == 4) {
              $('#quitar').fadeOut();
             }
            });
           });

imagen de muestra

A: He modificado tu código tanto html como la función multiplicar para mostrarte un ejemplo válido. Esto calcula total según los valores en dividendo y porcentaje.

     function multiplica(form){
     var resultado;
     var x=0;
     var y=0;

     x = parseInt(form.porcentaje.value);
     y = parseInt(form.dividendo.value);

     resultado = x * y;

      form.total.value = resultado;

        }

    <form>

                <input id="ejemplar" type="text" name="ejemplar[]" autocomplete='off' title='no pueden haber campos vacios, solo se permiten letras.' pattern='[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]+' required/>
                Ejemplar:

                <input id="peso" type="text" name="peso[]" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' pattern='[0-9]{2,2}'  required/>
                Peso:

                <input id="dividendo" type="text" name="dividendo" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.'  required/>
                Dividendo:

                <input id="icon_prefix" type="text" class="black-text" name="porcentaje" autocomplete="off" title='no pueden haber campos vacios, solo se permiten numeros.' onblur="multiplica(this.form)"  required/>
                porcentaje:

                <input id="total_result" type="text" name="total" readonly/>
                Total:

    </form>

A: Ejemplo de como usar los Input arrays

function readInputArray() {
  $('input[name^="field_name"]').each(function() {
      console.log($(this).val());
  });
 }

<input type="text" value="2" name="field_name[1]">
<input type="text" value="1" name="field_name[2]">

<button onclick="readInputArray()">Test Array Fields</button>


text:
Q: Insert new custom row at the end of table while reloadData Xcode Frankly, I know how to insert new custom row end of table without reloadData but now I want to know is how to insert new custom row end of UITable while reloadData.
Here is my piece of code to insert new custom row while reloadData. But new inserted row appeared at the top of table which is not what I want.
    CoachPadItem *newCoachPadItem = [[CoachPadItem alloc]init];
    newCoachPadItem.coachpadDescription = textView.text;
    newCoachPadItem.coachpadTagId = @"0";
    [_tagPointsArray addObject:newCoachPadItem];
    [_coachpadTableView reloadData];

cellforrowatindexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Configure the cell...
    CoachPadPointCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoachPadPointCell" forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[CoachPadPointCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CoachPadPointCell"];
    }

    counter += 1;

    cell.tagBtn.hidden = YES;
    cell.btnRemove.hidden = YES;

    cell.tagBtn.userInteractionEnabled = canEdit;
    [cell.tagBtn addTarget:self action:@selector(removeTag:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnRemove addTarget:self action:@selector(removePad:) forControlEvents:UIControlEventTouchUpInside];
    cell.btnRemove.tag = counter;
    cell.txtPoint.delegate = self;
    cell.txtPoint.tag = counter;
    cell.txtPoint.textContainer.maximumNumberOfLines = 2;
    cell.tagBtn.tag = counter;
    cell.txtPoint.textAlignment = NSTextAlignmentLeft;
    cell.txtPoint.backgroundColor = [UIColor clearColor];
    cell.txtPoint.userInteractionEnabled = canEdit;

    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    CoachPadItem *curr = _tagPointsArray[indexPath.row];
    cell.txtPoint.text = cure.MyDesc;

    return cell;
}

Please help me how to put new row at the end of UITable?

A: I'm not sure what's happen.
But, if [_tagPointsArray addObject:newCoachPadItem]; cause new inserted row appeared at the top of table which is not what I want, you can try:
[_tagPointsArray insertObject: newCoachPadItem atIndex:0];

A: Trusting you are using _tagPointsArray in your cellForRowAtIndexPath method, iOS should automatically take care of new row insertion as I can see you have updated your model _tagPointsArray before reloadData call on your table view.
Just scroll down and see!
EDIT: After OP edited the post
Check these two lines:
CoachPadItem *curr = _tagPointsArray[indexPath.row];
cell.txtPoint.text = cure.MyDesc;

You are not consuming the fetched model object from the array. This must work if object was added at right position in the array. Double check your model data positioning and also the above two lines I mentioned.


text:
Q: how to extract just the percentage from psutil.phymem_usage() python I want to get the memory used percentage from psutil.phymem_usage()  in python but when I run the function it returns this:
usage(total=520048640L, used=503255040L, free=16793600L, percent=81.5)

How can I filter it so that only the percent comes through?

A: What you get is a named tuple (see also this question), and you can just access it like any tuple or as an attribute. Assuming you store the return value in a variable usage, you can access the percentage using usage[3](regular tuple access) or usage.percent, with the second option being (imho) the most best option. You can also use psutil.phymem_usage().percent.


text:
Q: Get ONLY panel from other forms to mdi containter I'm creating an Inventory system and what I want to happen is when I click the buttons the content will change but not the header and navigation panel.
WHAT I ALREADY TRIED:
-created panels and used panel.show()/panel.hide() (GETS out of control when I have created many panels and put it in same position as others, when I hide one, all of them is hidden.)
now my main form is a MDI container and I created new forms that contains ONLY the panels that I will be needing. I wanted to know if there's any way that I could get ONLY the panel from other form to the MDI container.
this is my MDI form

A: You can show your forms in panel. like
  panel1.Controls.Add(Form1);


text:
Q: How to clean form after submitting ajax? First of all: I tried to search the answer in the web and I found like 20 examples of code. But I failed. still nothing is working.
I'm making a simple chat and i need to clean my form after submitting data via ajax. Here is the code:
<form id="ChatFrom" class="chatMessageField" action="Amess.php" method="post">
    <input class="chatMessageField" type="text" name="mess" /><br />
    <input class="chatMessageBtn" type="button" value="Отправить" onclick="SendForm();" />
</form>

<script type="text/javascript" src="http://scriptjava.net/source/scriptjava/scriptjava.js"></script>
<script type="text/javascript">
    function SendForm() {
        $$f({
            formid:'ChatFrom',
            url:'Amess.php',
        });
    }
</script>

A: $("#ChatFrom")[0].reset()
    // or
 $("#ChatFrom").get(0).reset()

A: You could do it like this:
function SendForm() {
   $.post( "Amess.php", function( data ) {
      resetFields();
   });
}

function resetFields(){
    $(':input')
      .not(':button, :submit, :reset, :hidden')
      .val('')
      .removeAttr('checked')
      .removeAttr('selected');
}

Hope it helps!

A: $(".chatMessageField").val(''); is a simple way, but you have to do it to all the fields individually. A better solution would be to give all of your inputs a class name that is the same and clear them all at once. Or just use jquery reset()


text:
Q: Does your reputation deteriorate over time? I used to have full allied status with the Federation, but then I didn't play Elite: Dangerous for a few weeks due to business travel. When I started playing the game again, my reputation with the Federation superpower was only mid-friendly.
Does your reputation with minor factions and superpowers deteriorate over time, if you don't play the game at all, or continually work on the status?

A: Yes it does, with the Major Factions.
According to the Wiki

Reputation decay only applies to the Major factions, Alliance, Federation & Empire.
When your status with a major faction is above 75% Friendly, it will slowly decay down to 75%, by a percentage point every couple of days. Reputation decay happens whether you're logged into the game or not. To stay Allied you have to keep doing good deeds that gain you reputation for the major faction.


text:
Q: Launching Minikube as normal User on Windows 10 I'm trying to run minikube with hyperv without open an Administrator powershell.
Is there any way?
I'm doing this:
choco install minikube
minikube.exe start --vm-driver "hyperv"

If I try to launch minikube start from a normal powershell it gives me this message:
X hyperv does not appear to be installed

A: To launch minikube from non-admin powershell. You need to add a non-admin user to "Hyper-V Administrators" group.
Open PowerShell with administrator right. And run below command to add current user name to
"Hyper-V Administrators" group. You need to sign off and sign in to take effect.
Add-LocalGroupMember -Group "Hyper-V Administrators" -Member [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

A: This issue occurs when you didn't install Hyper-V or it wasn't installed properly due to Windows updates or some environment issues. You can check if Hyper-V works properly if you will execute systeminfo. More info in Minikube docs. There are many ways to install Hyper-V. Easiest one is to install via Turn Windows features on or off, it's mentioned in this article as Solution 7. If it wouldn't help you can try others.
After proper installation of Hyper-V you need to install Docker for windows, Minikube and Kubectl. I've already created mini tutorial here. You can also check this tutorial about Minikube on Windows.
As additional information, I am not using admin rights.

A: Minikube works only with elevated rights on Windows
https://github.com/kubernetes/minikube/issues/6585#issuecomment-585269831


text:
Q: list subdirectories recursively I want to write a shell script so as to recursively list all different subdirectories which contain NEW subdirectory (NEW is a fixed name).
Dir1/Subdir1/Subsub1/NEW/1.jpg
Dir1/Subdir1/Subsub1/NEW/2.jpg
Dir1/Subdir1/Subsub2/NEW/3.jpg
Dir1/Subdir1/Subsub2/NEW/4.jpg
Dir1/Subdir2/Subsub3/NEW/5.jpg
Dir1/Subdir2/Subsub4/NEW/6.jpg

I want to get
Dir1/Subdir1/Subsub1
Dir1/Subdir1/Subsub2
Dir1/Subdir2/Subsub3
Dir1/Subdir2/Subsub4

How can I do that?

A: find . -type d -name NEW | sed 's|/NEW$||'

--- EDIT ---
for your comment, sed does not have a -print0.   There are various ways of doing this (most of which are wrong).   One possible solution would be:
find . -type d -name NEW -print0 | \
  while IFS= read -rd '' subdirNew; do \
          subdir=$(sed 's|/NEW$||' <<< "$subdirNew"); \
          echo "$subdir"; \
  done

which should be tolerant of spaces and newlines in the filename

A: ls -R will list things recursively.
of find . | grep "/NEW/" should give you the type of list you are looking for.

A: You could try this:
find . -type d -name "NEW" -exec dirname {} \;


text:
Q: Deploy node.js in production What are the best practices for deploying a nodejs application in production?
I would like to know how deploy for production Api's nodejs is being done today, today my application is in docker and running locally.
I wonder if I should use a Nginx inside the container and deploy my server on it or just upload my image node that is already running today.
*I need load balance

A: There are few main types of deployment that are popular today.

*

*Using platform as a service like Heroku

*Using a VPS like AWS, Digital Ocean etc.

*Using a dedicated server

This list is in the order of growing difficulty and control. So it's easiest with PaaS but you get more control with a dedicated server - thought it gets significantly more difficult, especially when you need to scale out and build clusters.
See this answer for more details on how to install Node on a VPS or a dedicated server:

*

*how to run node js on dedicated server?

A: I can only add from experience on AWS using a NAT Gateway which is a dedicated Node server with a MongoDB server behind the gateway. (Obviously this is a scalable system and project.)

*

*With or without Docker, you need to control the production environment. This means clearly defining which NPM libraries you will need for production, how you handle environment variables and clusters for cores.

*I would suggest, very strongly, using a tool like PM2 to handle clusters, server shutdowns and restarts and logs. (Workers & slaves also if you need them and code for them).
This list can go on and on, but keep in mind this is only from an AWS perspective. Setting up a Gateway correctly on AWS is also not an easy process. Be prepared for some gotcha's along the way.


text:
Q: Multiple Authentication Middlewares Good Day
I am in the process of moving an API over from using:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

for validating tokens, to using IdentityServer.
I want to however also be able to validate any tokens issued previously, using the above middleware.
So at first I replaced the line above with the following (IdentityServer3.AccessTokenValidation):
    .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = "http://localhost:5000",
            RequiredScopes = new[] { "api.tablet" },
            ClientId = "TabletAPI",
            ClientSecret = "secret",
        });

This worked and correctly authorized requests to protected endpoints, but only for tokens issued by the IdentityServer.
So my setup in IdentityServer is fine I believe, as using a reference token correctly validated and allowed access.
I however want the old OAuth tokens to also be validated, and so doing support the older OAuth tokens as well as any JwT's or reference tokens issued by my IdentityServer.
The way I found to do this (if there is a better way let me know please) was to add both middlewares into the pipeline, as below:
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
        {
            AuthenticationType = "BearerLegacy",
        })
        .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = WebConfigurationManager.AppSettings["AuthServer"],
            RequiredScopes = new[] { "api.tablet" },
            AuthenticationType = "BearerIdSrv",
            ClientId = "TabletAPI",
            ClientSecret = "secret",
        });

This is were I am stuck, it seems that the IdentityServer middleware is always the one trying to validate a token, and once it fails, it seems it never tries the "legacy" OAuth middleware.
Do I need to explicitly add something to all my [Authorize] endpoints to indicate that both types should be tried? Or is there a way to specify this globally?
I've found this, which seems more or less exactly like what I want to achieve, but is unfortunately in Asp.Net Core.
Any help or nudge in the right direction would be greatly appreciated.

A: I found this link, where they suggest to remove the RequiredScopes from the IdentityServerBearerTokenAuthenticationOptions. I tried that and it started working.
So in essence this:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
    {
        AuthenticationType = "BearerLegacy",
    })
    .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = WebConfigurationManager.AppSettings["AuthServer"],
        RequiredScopes = new[] { "api.tablet" },
        AuthenticationType = "BearerIdSrv",
        ClientId = "TabletAPI",
        ClientSecret = "secret",
    });

Needs to become this:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
    {
        AuthenticationType = "BearerLegacy",
    })
    .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = WebConfigurationManager.AppSettings["AuthServer"],
        AuthenticationType = "BearerIdSrv",
        ClientId = "TabletAPI",
        ClientSecret = "secret",
    });


text:
Q: Separate model and UI view model in Spring (sort of MVVM in Spring) I would like to start a discussion on separating pure model and UI model in Spring 3.
By pure model I mean main object/objects that I retrieve from database, let's say some "user account". It contains enough info to display it in HTML view or to pass it to web service.
By UI model I mean all the auxillary stuff I need in UI to work with that object. E.g. if a "user account" has "state", then I need to fetch all the "states" from the database for, say, a combo box. The views are tricky and in some cases they require more information, in others - less. It would also be nice to be able to alter some lists by adding items like "Select all", which is pure UI stuff (and not quite conveniently done from view template).
I heard there's so called Model-View-ViewModel pattern, which seems to address these issues, but I have never tried its implementations.
The solution I use right now is to break logics into two services - one for pure model and one for UI model. It looks like this:
@RequestMapping(value="app/user_accounts/{id}")
public String getUserAccount(@PathVariable("id") String id) {
    service.getUserAccount(id); // Gets main object and puts it into model
    presenter.formUserAccount(); // Gets all classifier for main object's properties
    return "user_account";
}

What I dislike about this is that the view and its so-called view model are not attached to each other. I can call presenter.formUserAccount() and return totally unrelated view name.
Another approach I see is similar to Spring controller annotation. We have classes annotated as @ViewModels and methods which map to view names. An interceptor finds and executes these methods before rendering a certain view. These seems elegant enough, but requires much code writing.
How would you solve this problem?

A: I have been thinking about this in the context of Grails, which is based on Spring MVC. My approach is to use Command Objects as View Models as it gives you the data binding and validation features that you would want in a View Model.  With Command Objects you can abstract your "Pure Model" (or Domain Model) out of your View by using the Command Objects to map the view properties onto you domain objects.


text:
Q: Excel automatically update graph when adding new columns and rows in data
My excel graph comes from a table in another sheet, as shown in the above image.
The X-axis of the graph shows the month/year headers in blue in row 3 except column A&B (.... 43.july17, 44.aug17, ...).
The Y axis shows the Ave. subs length in row 57 except column A&B.
Every month I need to insert a new month/year column, in this case between column AY and AZ. I also need to insert new monthly row data, in this case under Month 14 in row 17, so that the Ave. Subs length row is moving 1 row down every month.
Data under the TOTALS column (AZ) are not included in the graph. I currently use the graph formula:
=SERIES(,'Cohorts(32015)'!$C$3:$AX$3,'Cohorts(32015)'!$C$57:$AX$57,1)

However, it does not automatically update when I add new columns to the table. Is there a way to do this?

A: Yes it is :).
There is a function in Excel called "Name Manager". There you can define ranges (name a range or a cell/cells) and therefore make ranges dynamic as you insert or delete columns or rows.
Guide:
Go to "Formulas" -> "Defined Names" -> "New.."

I create two ranges (notice I use absolute reference with $).

1 - The first one is for the axis values (43.july17, 44.aug17 etc..). I call it "Month_Name". Notice you need to do it from $C$3 given your example.
=OFFSET(Sheet1!$AS$3,0,0,1,COUNTA(Sheet1!$AS$3:$AZ$3)-1)

2- The second one is for your data range (Ave. subs length). I call the range: "Ave_Sub".
=OFFSET(Sheet1!$AS$57,0,0,1,COUNTA(Sheet1!$AS$57:$AZ$57)-1)

Click on your series (in your graph/chart) and change your series names to the sheet name + named range i.e. in my case the sheet name is "Sheet1":
=SERIES(;Sheet1!Month_Name;Sheet1!Ave_Sub;1)

When you add rows or columns now, the graph will automatically expand (I added 1 row and one column).

Details about formula:
So how does it work?
Syntax for the formula is:
=OFFSET(reference, rows, cols, [height], [width])

and in our case
=OFFSET(Sheet1!$AS$3,0,0,1,COUNTA(Sheet1!$AS$3:$AZ$3)-1)

Where:
reference: is our start column, $AS$3.
rows and cols: We don't want to offset any column or rows. Therefore: 0,0.
[height]: = 1 since we have one row.
[width] = COUNTA(Sheet1!$AS$3:$AZ$3)-1, we take the first column we want to have in our chart and the last column in the range we possible want to add or delete a column. In our case the "Total" will be our last column. But we don't want "Total" to appear therefore we take -1 in our range.
Generic formulas to expand ranges:
For columns:
=OFFSET(<sheet name="">!<start cell="">,0,0,1,COUNTA(<sheet name="">!<column name="">:<column name="">) - 1)

For rows:
=OFFSET(<Sheet name>!<start cell>,0,0,COUNTA(<Sheet name>!<Column name>:<Column name>) - 1)


text:
Q: How can I tell if my banana fits in the banana hole? Are all banana plugs the same? Can I use these Fluke brand banana plugs and plug them in to this Extech brand phase rotation tester? Will they fit?

What defines banana plugs anyway? Is there an ISO standard or something?
MSC Direct has a better picture of the phase rotation tester that makes it look to me like it uses standard "banana" connections.

But what really IS the standard for banana connections, and how can I be sure that my banana fits into the banana hole?

A: The actual connector part will fit without problems - a 4mm banana connector always fits the same across all vendors.
Unfortunately the plastic protection is not standardized - I experience problems every now and then. Either the plastic is too long or the thicker part of the connector starts too early or the tiny plastic cap in the middle of the banana plug just got stuck in the socket. Some devices only accept straight connectors as well.
TL/DR: Impossible to say without actually trying it.

A: They're all the same 4mm diameter banana hole same diameter shroud and a compatible springy pin.
For a phase sequence meter choosing plugs with a shroud that's deep enough to fully protect the pin is probably important.


text:
Q: Functional way to fill an array in Swift I need to fill an Array that describes a Matrix [[Double]]. Each element of the matrix is of the following form :
a(i,j) = exp(a*(i+j) + b*min(i,j))

Is there an elegant way of doing that rather than using 2 embedded loops ?

A: You can use map twice to create your matrix.  This is a functional approach that is really just two loops under the hood:
let maxi = 5  // largest acceptable index
let maxj = 3  // largest acceptable index

let a = 2.3
let b = 3.4

let matrix = (0...maxi).map { i in (0...maxj).map { j in exp(a * Double(i + j) + b * Double(min(i, j))) } }

which might be a little easier to read if we format it like this:
let matrix = (0...maxi).map { i in
                 (0...maxj).map { j in
                     exp(a * Double(i + j) + b * Double(min(i, j)))
                 }
             }

One advantage this has over using loops is that you can create a matrix that is read-only (let).  Of course, you can always make it var if you want it to be mutable.


text:
Q: Joi Validation - Field is not required when the condition is not met I am writing an update endpoint in nodeJs. I want to make sure that additional fields wont be allowed, if certain flags are checked.
all_restaurant: Joi.boolean().required(),
merchant_id: Joi.when('all_restaurant',{'is':false,
                then: Joi.string().required(), otherwise:Joi.disallow()})

If all_restaurant is true, I need to throw an error when the user tries to include any merchant_id, but it still allowing me to update.
I tried using strict() after the field and in the top level but nothing is working. is there any way to achieve that?

A: You can use Joi.forbidden instead of Joi.disallow:
const schema = Joi.object({
    all_restaurant: Joi.boolean().required(),
    merchant_id: Joi.string().when('all_restaurant', {
        is: false,
        then: Joi.required(),
        otherwise: Joi.forbidden()
    })
})

As the name suggests, forbidden marks a key as forbidden.

A: This is a variant asked by @shubham-verma (asked on the answer above).
Imagine that all_resturant is an array with valid strings: 'A', 'B' or 'C':
all_resturant: Joi.array().items(Joi.string().valid('A', 'B', 'C'))

How can we make merchant_id required only if all_resturant[0] is equal to 'A'?
We can still use .when  combined with .ordered:
Joi.object({
  all_resturant: Joi.array().items(Joi.string().valid('A', 'B', 'C')),
  merchant_id: Joi.string()
}).when(Joi.object({ all_resturant: Joi.array().ordered(Joi.string().valid('A')).items(Joi.string()) }).unknown(), {
  then: Joi.object({
    merchant_id: Joi.required()
  })
})

Joi.array().ordered(Joi.string().valid('A')).items(Joi.string()) means that the array must have first item as "A" and 1 or more subsequent items as one strings.
Here are a few cases:
{ all_resturant: ["A", "B", "A", "C"] }
// merchant_id required
{ all_resturant: ["C", "B", "A", "C"] }
// passed
{ all_resturant: ["C"] }
// passed
{ all_resturant: ["A"] }
// merchant_id required
{ all_resturant: ["A"], merchant_id: '123' }
// passed


text:
Q: Hazelcast management center shows get latency of 0 ms for replicated map Setup :

*

*3 member embedded cluster deployed as a spring boot jar.

*Total keys on each member: 900K

*Get operation is being attempted via a rest api.

Background:

*

*I am trying to benchmark the replicated map of hazelcast.

*Management center UI shows around 10k/s request being executed but avg get latency per sec is coming 0ms.

*I believe it is not showing because it might be in microseconds.

Please let me know how to configure management center UI to show latency in micro/nanoseconds?

A:
Management center UI shows around 10k/s request being executed but avg get latency per sec is coming 0ms.

I believe you're talking about Replicated Map Throughput Statistics in the replicated map details page. The Avg Get Latency column in that table shows on average how much time it took for a cluster member to execute the get operations for the time period that is selected on the top right corner of the table. For example, if you select Last Minute there, you only see the average time it took for the get operations in the last minute.

I believe it is not showing because it might be in microseconds.

Cluster is sending it as milliseconds (calculating it as nanoseconds in a newer cluster version but still sending as milliseconds). However, since a replicated map replicates all data on all members and every member contains the whole data set, get latency is typically very low as there's no network trip.
I guess that the way we render very small metric values confused you. In Management Center UI, we only show two fractional digits. You can see it in action in the below screenshots:

As you can see, since the value is very low, it is shown as 0. I believe we can do a better job rendering these values though (using a smaller time unit for example). I will create an issue for this on our private issue tracker.


text:
Q: Trying to save original name of uploaded pdf on my sql table Im uploading pdfs with this code below:
$folder = '../uploads/pdfs';
$year = date('Y');
$month = date('m');
$pdf = $_FILES['pdf'];
$ext = substr($pdf['name'],-3);
$pdf_name = $pdf['name'].'-FROM-'.$date_begin.'-TO-'.$date_end.'';
$f['pdf'] = $year.'/'.$month.'/'.$pdf_name.'.'.$ext;
move_uploaded_file($pdf['tmp_name'], $folder.$year.'/'.$month.'/'.$pdf["name"]);

Im my sql table when I do the insert, Im getting this in my pdf_name field:
2014/05/F:\Xampp\tmp\phpE92C.tmp
And I want to save my pdf in sql like this:
2014/05/nameofpdf.pdf
Do you see what Im doing wrong here?
My insert sql statment:
$inseretInPdf = $pdo->prepare("INSERT INTO pdfs (pdf_name, date_begin, date_end) VALUES (:pdf_name, :date_begin, :date_end)");
$inseretInPdf->bindValue(':pdf_name', $f['pdf']);
$inseretInPdf->bindValue(':date_begin', $f['date_begin']);
$inseretInPdf->bindValue(':date_end', $f['date_end']);
$inseretInPdf->execute();

A: Your passing the full path with $inseretInPdf->bindValue(':pdf_name', $f['pdf']);
which is:
$f['pdf'] = $year .'/'.$month .'/'.$f['url'].'.'.$ext;
              2014  /    05     /  F:\Xampp\tmp\phpE92C  .  tmp
So change $f['pdf'] to what you want it to display when it's added to the database.
EDIT: I updated the answer to visually show you what $f was passing. (:


text:
Q: (Symfony 2.3) Doctrine Mapping column names Is it possible to map column names using a .yml file with Symfony 2.3?
The annotation method works, but not using YAML files.
Here's what I'm doing:
    dateCreated:
        type: string
        name: date_created
        length: '100'

the line  name: date_created doesn't affect anything. The same with single/double quotes.
Am I missing something trivial here, or is it just not supported yet?
Thank you.

A: Try column: insted of name:
dateCreated:
    type: string
    column: date_created
    length: 100

http://docs.doctrine-project.org/en/2.0.x/reference/basic-mapping.html


text:
Q: Success function of bootstrap validator is not working? My form validation works perfectly but success function is not being triggered at the end. Syntax seems fine. But i am not sure if we can include success function with validator
However, prevent default is doesn't stop it from submitting. any help???
$('#editVolForm').bootstrapValidator({

  // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
  feedbackIcons: {
    valid: 'glyphicon glyphicon-ok',
    invalid: 'glyphicon glyphicon-remove',
    validating: 'glyphicon glyphicon-refresh'
  },

  editPapSub: {
    validators: {
      stringLength: {
        min: 1,
      },
      regexp: {
        regexp: /^[0-9]+$/,
        message: "'Submitted Papers' can only consist of numeric characters."
      },
      notEmpty: {
        message: "A valid number of 'Papers Submmited' is required."
      }
    }
  },
  editPapAcc: {
    validators: {
      stringLength: {
        min: 1,
      },
      regexp: {
        regexp: /^[0-9]+$/,
        message: "'Accepted Papers' can only consist of numeric characters."
      },
      notEmpty: {
        message: "A valid number of 'Papers Accepted' is required."
      }
    }

  }
}).on('success.form.bv', function(e) {

  e.preventDefault();
  console.log("test");
});


text:
Q: Converting Multiple DPLYR Commands into a Single DPLYR Command I am working with the R programming language.
I have the following dataset ("my_data"):
structure(list(idd = 1:50, group_1 = c("B", "B", "A", "B", "B",
"A", "A", "A", "B", "A", "A", "B", "B", "B", "A", "A", "A", "A",
"B", "B", "A", "B", "A", "B", "A", "B", "B", "A", "B", "B", "B",
"A", "B", "A", "B", "B", "A", "A", "A", "A", "A", "B", "B", "B",
"A", "B", "B", "B", "B", "B"), v1 = c(15.7296737049317, -4.33377704672207,
-0.551850185265, 2.66888122578048, 12.109072642513, 0.0107927293899017,
20.7785032320562, -1.98974382507874, 12.1663703518471, 11.4308702978893,
-0.657500910529805, 5.71376589298221, 3.43820523228653, 19.5939432685761,
25.5605263610222, -0.407964337882465, 19.3057240854025, 9.24554068987809,
-9.6719534905096, 2.44096357354807, 14.6114916050676, 11.4510663104787,
-14.4231132108142, 15.8031868545157, 16.5505199848675, 6.95491162740581,
2.92431767382703, 29.7157201447823, 9.10001319352251, 9.85982748068076,
-1.23456937110154, -3.44130123376206, -5.23155771062088, 5.78031789617826,
23.6092446408098, 27.5379484533487, 25.6836473435279, 22.9675556994775,
7.62403748556388, -2.24150135680706, 6.72187319859928, -14.1245027627225,
6.8620712655661, 26.5987870464572, 11.3095310060752, 20.9588868268958,
14.8934095694391, 2.21089704551347, 27.4355935292935, 9.21612714668934
), group_2 = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)), row.names = c(NA, -50L), class = "data.frame")

head(my_data)

   idd group_1          v1 group_2
1    1       B 15.72967370       1
2    2       B -4.33377705       2
3    3       A -0.55185019       3
4    4       B  2.66888123       4
5    5       B 12.10907264       5
6    6       A  0.01079273       6
7    7       A 20.77850323       7
8    8       A -1.98974383       8
9    9       B 12.16637035       9
10  10       A 11.43087030      10
11  11       A -0.65750091       1
12  12       B  5.71376589       2

For this dataset, I want to perform the following steps in "dplyr":

*

*For each grouping of 10 rows, find the sum of "v1" for group_1 = "A" and group_2 = "B"

*For each of these groupings, create a new variable ("v2") that is : "A" if sum(group_1 = A) > sum(group_1 = B), "B"  if sum(group_1 = A) < sum(group_1 = B) or "0"  if sum(group_1 = A) = sum(group_1 = B)

I know how to do this manually in R:
#STEP 1: since my_data has 50 rows, break my_data into 5 groups of 10 rows

rows_1 = my_data[1:10,]
rows_2 = my_data[11:20,]
rows_3 = my_data[21:30,]
rows_4 = my_data[31:40,]
rows_5 = my_data[41:50,]

# STEP 2: find out values of "v2"

library(dplyr)

dplyr_row_1 = data.frame(rows_1 %>% group_by(group_1) %>% summarize(sum = sum(v1)))

dplyr_row_1$v2 = ifelse(dplyr_row_1[1,2] > dplyr_row_1[2,2], "A", ifelse(dplyr_row_1[1,2] < dplyr_row_1[2,2], "B", 0))

dplyr_row_2 = data.frame(rows_2 %>% group_by(group_1) %>% summarize(sum = sum(v1)))

dplyr_row_2$v2 = ifelse(dplyr_row_2[1,2] > dplyr_row_2[2,2], "A", ifelse(dplyr_row_2[1,2] < dplyr_row_2[2,2], "B", 0))

dplyr_row_3 = data.frame(rows_3 %>% group_by(group_1) %>% summarize(sum = sum(v1)))

dplyr_row_3$v2 = ifelse(dplyr_row_3[1,2] > dplyr_row_3[2,2], "A", ifelse(dplyr_row_3[1,2] < dplyr_row_3[2,2], "B", 0))

dplyr_row_4 = data.frame(rows_4 %>% group_by(group_1) %>% summarize(sum = sum(v1)))

dplyr_row_4$v2 = ifelse(dplyr_row_4[1,2] > dplyr_row_4[2,2], "A", ifelse(dplyr_row_4[1,2] < dplyr_row_4[2,2], "B", 0))

dplyr_row_5 = data.frame(rows_5 %>% group_by(group_1) %>% summarize(sum = sum(v1)))

dplyr_row_5$v2 = ifelse(dplyr_row_5[1,2] > dplyr_row_5[2,2], "A", ifelse(dplyr_row_5[1,2] < dplyr_row_5[2,2], "B", 0))

# STEP 3: append "v2" to first 5 files:

rows_1$v2 = dplyr_row_1$v2
rows_2$v2 = dplyr_row_2$v2
rows_3$v2 = dplyr_row_3$v2
rows_4$v2 = dplyr_row_4$v2
rows_5$v2 = dplyr_row_5$v2

# STEP 4: create final file:

final_file = rbind(rows_1,rows_2, rows_3, rows_4, rows_5)

As a result, the final file looks something like this:
  idd group_1          v1 group_2 v2
1    1       B 15.72967370       1  B
2    2       B -4.33377705       2  B
3    3       A -0.55185019       3  B
4    4       B  2.66888123       4  B
5    5       B 12.10907264       5  B
6    6       A  0.01079273       6  B
7    7       A 20.77850323       7  B
8    8       A -1.98974383       8  B
9    9       B 12.16637035       9  B
10  10       A 11.43087030      10  B
11  11       A -0.65750091       1  A

My Question: Can someone please show me how to perform Steps 1 to Step 4 in a single "dplyr" command?
Thanks!

A: *

*First I'll create a group_index to group every 10 rows together.

*Then group_by the relevant columns and calculate sum.

*Remove the grouping layer of group_1, since we need to compare the values in A and B.

*If the unique length of sum is equal to "1", that means they are the same, then input "0" in column v2. If they are not the same, output the maximum category stored in group_1.

*Finally remove the sum column and sort by idd.

This method is able to solve problem with more than two groups in group_1.
The first 20 rows are shown here for example.
library(tidyverse)

df %>%
  mutate(group_index = rep(1:(nrow(df)/10), each = 10)) %>%
  group_by(group_index, group_1) %>%
  mutate(sum = sum(v1)) %>%
  group_by(group_index) %>%
  mutate(v2 = ifelse(length(unique(sum)) == 1, 0, group_1[which.max(sum)])) %>%
  ungroup() %>%
  select(-c(sum, group_index))

# A tibble: 20 x 5
     idd group_1      v1 group_2 v2
   <int> <chr>     <dbl>   <int> <chr>
 1     1 B       15.7          1 B
 2     2 B       -4.33         2 B
 3     3 A       -0.552        3 B
 4     4 B        2.67         4 B
 5     5 B       12.1          5 B
 6     6 A        0.0108       6 B
 7     7 A       20.8          7 B
 8     8 A       -1.99         8 B
 9     9 B       12.2          9 B
10    10 A       11.4         10 B
11    11 A       -0.658        1 A
12    12 B        5.71         2 A
13    13 B        3.44         3 A
14    14 B       19.6          4 A
15    15 A       25.6          5 A
16    16 A       -0.408        6 A
17    17 A       19.3          7 A
18    18 A        9.25         8 A
19    19 B       -9.67         9 A
20    20 B        2.44        10 A

A: Here is alternative method.
library(tidyverse)

df %>%
  mutate(group_index = rep(1:(n() /10), each = 10)) %>%
  group_by(group_index) %>%
  mutate(
   v2 = case_when(
    sum(v1[group_1 == 'A']) > sum(v1[group_1 == 'B']) ~ 'A',
    sum(v1[group_1 == 'A']) < sum(v1[group_1 == 'B']) ~ 'B',
    TRUE ~'0')
)


text:
Q: matplotlib.pyplot: align axes labels when using a colorbar for each subplot The Problem: I am using matplotlib to create a figure with multiple subplots. Each subplot has both x- and y-axis labels, and may also have its own colorbar.
By default, axis labels are placed next to the tick marks (Figure 1, left). However, I want the y-axis labels to vertically align (Figure 1, right). I am using fig.align_labels() to do this.
Figure 1:

I want to include colorbars on each subplot (Figure 2, left). However, when I use fig.align_labels(), the axis labels are simply collapsed onto the same position (Figure 2, right).
Figure 2:

The Question: How can we align the y-axis labels when colorbars are used?
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np

x = np.array(np.arange(5))
y = [np.random.uniform(0.5,2,5)*np.random.random(5)+100,   # <-- 'Long' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5)+100,    # <-- 'Long' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5),        # <-- 'Short' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5)]        # <-- 'Short' tick labels

fig = plt.figure()

for plotnum,yvals in enumerate(y):
    ax = fig.add_subplot(2,2,plotnum+1)
    sc = ax.scatter(x,yvals,c=yvals)
    fig.colorbar(sc, ax=ax)

    ax.set(ylabel=f'Y Values {plotnum}', xlabel=f'X Values {plotnum}')
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.1f}'))

plt.tight_layout()
plt.subplots_adjust(wspace=0.8, hspace=0.6)
fig.align_labels()
plt.show()

A: The most optimal way to handle this in your code is to add a line to the loop process.
fig = plt.figure()

for plotnum,yvals in enumerate(y):
    ax = fig.add_subplot(2,2,plotnum+1)
    sc = ax.scatter(x,yvals,c=yvals)
    fig.colorbar(sc, ax=ax)
    ax.yaxis.set_label_coords(-0.4, 0.5) # update
    ax.set_ylabel(f'Y Values {plotnum}')
    ax.set_xlabel(f'X Values {plotnum}')
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.1f}'))

plt.tight_layout()
plt.subplots_adjust(wspace=0.8, hspace=0.6)
#fig.align_ylabels()

plt.show()


text:
Q: Creating a classification system using C# Dictionary I'll try to give you an idea of what I am trying to do.
Let's say I have 4 columns in my datagridview/table:

+----+-------------+------------+------------+
| ID | Description |    Type    |   Class    |
+----+-------------+------------+------------+
|  1 | Soft        | Strawberry | Fruit      |
|  2 | Round       | Grape      | Fruit      |
|  3 | Sharp       | Pencil     | Stationary |
+----+-------------+------------+------------+

This is what the final form should look like after the program is through.
Let's assume the second and last row are empty and the third row, Type, is the only one available.
I had originally attempted something like this with a switch code block like so:
switch (Type)
{
    (Strawberry){
     B2 = Soft;
     C3 = Fruit;
    }
    (Grape){
     etc...
    }
}

Basically, we take type as the criteria argument for the other two cells.
Strawberry is soft and fruit, Grape is round and fruit, etc.
I was advised to use a dictionary instead of a switch block because of the lengthy criteria's (maybe 1000 types) however, as far as I know while a dictionary can be called using a key (like Strawberry, or Grape) it will only be capable of returning one type, say, the data of Description. Moreover, I do not know how I will be able to handle writing the dictionary into datagridview format, compared to the ease of writing it with a switch statement.

Solution I came up with for future viewers:
    public class DictionarySetup
    {
        public string theDescription { get; set; }
        public string theClass { get; set; }
    }

    public class DictionaryInit
    {
        public Dictionary<int, DictionarySetup> accountRevenue = new Dictionary<int, DictionarySetup>()
            {
                { 400000, new DictionarySetup {theDescription="Black", theClass="Weapon"}},
                { 400001, new DictionarySetup {theDescription="White", theClass="Mouse"}},
                { 410000, new DictionarySetup {theDescription="Opaque", theClass="Obstacle"}}
            };
     }

Active control:
    DictionaryInit theDictionary;
    private void btnFixer_Click(object sender, EventArgs e)
    {
        theDictionary = new DictionaryInit();
        for (int rowindex = 0; rowindex < DGVMain.RowCount; rowindex++)
        {
            foreach (var item in theDictionary.accountRevenue)
            {
                int theKey = item.Key;
                DictionarySetup theValues = item.Value;
                DGVMain.Rows[rowindex].Cells[5].Value = theValues.theDescription;
                DGVMain.Rows[rowindex].Cells[6].Value = theValues.theClass;
            }
        }
    }

A: No, do not use a switch statement.
The value part of the dictionary entry can be an object of any type, not just something simple like String. So populate your value with a class of any complexity you wish.
// NOT TESTED

class thing
{
public:
    string theType;
    string theClass;
};

Dictionary<string, thing> dict = new Dictionary<string, thing>();

thing x;
x.theType = "Soft";
x.theClass = "Fruit";
dict.Add("Strawberry", x);

Edited to add:
Iterating through the Dictionary (code taken from here)
foreach(var item in myDictionary)
{
    string theKey = item.Key;
    thing theValues = item.Value;

    /*
        theKey, theValues.theClass, and theValues.theType
        have the values you want for your datagrid
    */
}


text:
Q: Attaching middleware to a specific route in ASP.NET Core Web API? Inside the configure, I can attach a global middleware using:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   ....
   app.UseMiddleware<MyMiddleware>();
   ...
}

This will apply to all actions.
However, I thought to myself, how can I attach a middleware to a specific route/action? (Sure I can put some if's inside the code but I don't like the approach)
But then I saw this:
 app.UseEndpoints(endpoints =>
  {
      endpoints.Map("/version", endpoints.CreateApplicationBuilder()
               .UseMiddleware<MyMiddleware>()
               .UseMiddleware<VersionMiddleware>()
               .Build())
               .WithDisplayName("Version number");
  }

This will work but will create a NEW endpoint /version.
Question
How can I attach custom middleware to an existing controller action route?
I've tried:
endpoints.Map("/weatherforecast", endpoints.CreateApplicationBuilder()
    .UseMiddleware<MyMiddleware>()
    .UseMiddleware<VersionMiddleware>()
    .Build())
    .WithDisplayName("Version number");

But it doesn't seem to affect. I see a regular response from the controller. Without new headers which the middleware adds.

A: You need the MapWhen
https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core
from the link, modified:
app.UseMiddlewareOne();

app.MapWhen(context => context.Request.Path.StartsWithSegments("/version", StringComparison.OrdinalIgnoreCase)), appBuilder =>
{
    appBuilder.UseMiddlewareTwo();
});

app.UseMiddlewareThree();


text:
Q: How can I play.google for Skype? This code is to msg somethone om Skype but I don't know how to set https://play.google.com/store/apps/details?id=com.skype.raider in case I didn't have Skype.
skypename.setOnClickListener(new OnClickListener() {
                  @Override
                   public void onClick(View v) {
                      Uri skypeUri = Uri.parse("skype:username?chat");
                      Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
                      myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
                      myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                      startActivity(myIntent);
                      }
                  });

Code added ...................................................................................................
skypename.setOnClickListener(new OnClickListener() {
   @Override
     public void onClick(View v) {
      if (!isSkypeClientInstalled(activity)) {
        Context activity;
        goToMarket(activity);
        return;
     } else{
       Uri skypeUri = Uri.parse("skype:username?chat");
       Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
       myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
       myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       startActivity(myIntent);
       }

public void goToMarket(Context myContext) {
   Activity activity;
  try {
      activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + "com.skype.raider")));
                    } catch (android.content.ActivityNotFoundException anfe) {
                         activity. startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + "com.skype.raider")));
                    }
                      return;
                     }
                public boolean isSkypeClientInstalled(Context myContext) {
                      PackageManager myPackageMgr = myContext.getPackageManager();
                      try {
                       myPackageMgr.getPackageInfo("com.skype.raider", PackageManager.GET_ACTIVITIES);
                      }
                      catch (PackageManager.NameNotFoundException e) {
                       return (false);
                      }
                      return (true);
                     });

A: First you check skype is already  installed or not using this code .if insalled msg something.else go to google play to download skype
skypename.setOnClickListener(new OnClickListener() {
           @Override
             public void onClick(View v) {
              if (!isSkypeClientInstalled(MainActivity.this)) {

                goToMarket(MainActivity.this);
                return;
             } else{
               Uri skypeUri = Uri.parse("skype:username?chat");
               Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
               myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
               myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               startActivity(myIntent);
               }
           }
                });

public void goToMarket(Context myContext) {

    try {
       activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + "com.skype.raider")));
    } catch (android.content.ActivityNotFoundException anfe) {
         activity. startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + "com.skype.raider")));
    }

      return;
     }
public boolean isSkypeClientInstalled(Context myContext) {
      PackageManager myPackageMgr = myContext.getPackageManager();
      try {
       myPackageMgr.getPackageInfo("com.skype.raider", PackageManager.GET_ACTIVITIES);
      }
      catch (PackageManager.NameNotFoundException e) {
       return (false);
      }
      return (true);
     }

A: Hi Tina Please check below code its working fine.
If not install skype on device open google play otherwise open skype.
Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try {
                    if (appInstalledOrNot("com.skype.raider")) {
                        Intent sky = new Intent("android.intent.action.VIEW");
                        sky.setData(Uri.parse("skype:" + ""));
                        startActivity(sky);
                    } else {
                        Intent i = new Intent(
                                android.content.Intent.ACTION_VIEW);
                        i.setData(Uri
                                .parse("https://play.google.com/store/apps/details?id=com.skype.raider"));
                        startActivity(i);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    private boolean appInstalledOrNot(String uri) {
        PackageManager pm = getPackageManager();
        boolean app_installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        }
        return app_installed;
    }