text:
Q: Babel Preset ENV issues Good day:
I've just installed Babel Preset-ENV through NPM and getting this issue:
[nodemon] starting `babel-node server.js server.js`
/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
        throw e;
        ^

TypeError: Cannot read property 'loose' of undefined (While processing preset: "/home/vagrant/api/node_modules/@babel/preset-env/lib/index.js")
    at _default (/home/vagrant/api/node_modules/@babel/plugin-transform-modules-commonjs/lib/index.js:19:22)
    at Function.memoisePluginContainer (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:113:13)
    at Function.normalisePlugin (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:146:32)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (native)
    at Function.normalisePlugins (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (native)

My Package.JSON is the following:
{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -L server.js --ignore 'db/schema.json' --exec babel-node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.0.0-beta.32",
    "@babel/preset-env": "^7.0.0-beta.32",
    "babel-core": "^6.26.0",
    "express": "^4.16.2",
    "express-graphql": "^0.6.11",
    "express-oauth-server": "^2.0.0",
    "graphql": "^0.11.7",
    "jsonwebtoken": "^8.1.0",
    "mongo": "^0.1.0",
    "mongoose": "^4.13.2",
    "password-hash": "^1.2.2",
    "react-relay": "^1.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0"
  }
}

And also my .babelrc is this:
vagrant@vagrant-ubuntu-trusty-64:~/api$ cat .babelrc
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Before the upgrade I was using stage-0 and es2015 presets that were working however, after the upgrade this has been buggy. Note, my NPM version is 4.6.1.
Thanks.

A: Make sure your Babel dependencies are compatible with each other.
this:
"@babel/core": "^7.0.0-beta.32",
"@babel/preset-env": "^7.0.0-beta.32",
"babel-core": "^6.26.0",
"babel-cli": "^6.26.0"

should be this:
"@babel/cli": "^7.0.0-beta.34",
"@babel/core": "^7.0.0-beta.34",
"@babel/node": "^7.0.0-beta.34",

A: I followed this instruction for setup https://github.com/babel/babel/tree/master/experimental/babel-preset-env however, the documentation here seems outdated. I was advised to use the official babel documentation mentioned here for the preset setup https://babeljs.io/


text:
Q: I have created a table named "option" through python, now how can I access or delete this table? After I typed "DESCRIBE option", an error occurred:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option' at line 1.

A: Option is a reserved keyword.
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
But you can use backticks like this.
DESCRIBE `option`

To delete this table.
DELETE TABLE `option`

A: Like this:
 connection = pymysql.connect("localhost", "user", "password", "database")
 cursor = connection.cursor()

 db_table = input("Table Name: ")
 show_table = "SELECT * FROM %s"%(db_table)
 cursor.execute(show_table)
 result = cursor.fetchall()

 for row in result:
 print("-----------------------------")
 print(row[0], row[1], row[2], row[3], row[4])
 print("-----------------------------")

 connection.commit()
 connection.close()

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get the system to exit if the user is wrong? If the user guesses wrong the system prints out wrong. I want the game to end whenever the user is wrong, can anyone help me? I tried using a system exit but that was exiting when the guess was correct as well. I want the system to print "Game Over" if the user is wrong and for the next cards to appear after that.
static Scanner console = new Scanner(System.in);
    public static void main(String[] args) {
        int[] cards = {6,4,2,7,5,9,11,1,12};

        System.out.println("predict next number by typing in 'higher' or 'lower'");

        for (int i = 1; i < cards.length; i++)
        {
            printHead(cards, i);
            System.out.println("");;
            String predict = console.next();
            if (predict.equals("higher"))
                checkHigher(cards, i-1, i);
            if (predict.equals("lower"))
                checkLower(cards, i-1, i);
        }
        printAll(cards);
    }

    public static void printAll(int[] cards){
        for (int i =0; i< cards.length; i++)
            System.out.print(cards[i]+ " ");
    }

    public static void printHead(int[] cards, int upTo){
        for (int i =0; i< upTo; i++)
            System.out.print(cards[i]+ " ");
    }

    public static void checkHigher (int[] cards, int pos1, int pos2){
        if (cards[pos2]>cards[pos1])
             System.out.println ("Correct!");
        else
             System.out.println("Wrong");
    }

    public static void checkLower (int[] cards, int pos1, int pos2){
        if (cards[pos2]<cards[pos1])
            System.out.println ("Correct!");
        else
            System.out.println("Wrong");
    }
}

A: The simpler way is to exit from the program with a
System.exit(0);

An alternative is to return a boolean value from each check and use it to decide if exit or not.
A third alternative is to wrap the main method code in a try catch and  through an Exception when the user is wrong, then exit.
Follow the three alternatives with snippet of codes:

Exiting directly from the check
public static void checkLower (int[] cards, int pos1, int pos2){
    if (cards[pos2]<cards[pos1]) {
        System.out.println ("Correct!");
    } else {
        System.out.println("Wrong");
        System.exit(0);
    }
}

Use a boolean return value
public boolean void checkLower (int[] cards, int pos1, int pos2){
    if (cards[pos2]<cards[pos1]) {
        System.out.println ("Correct!");
        return true;
    } else {
        System.out.println("Wrong");
        return false;
    }
}

and in the main
if (!checkLower(cards, i-1, i)) {
    System.exit(0);
}

Throw an exception
public boolean void checkLower (int[] cards, int pos1, int pos2) throws Exception {
    if (cards[pos2]<cards[pos1]) {
        System.out.println ("Correct!");
    } else {
        System.out.println("Wrong");
        throw new Exception("Wrong answer");
    }
}

and in the main
public static void main(String[] args) {
    try {
        // Your code here
    } catch (Exception e) {
       System.out.println("There was an exception in the input");
    }
}

A: Just simply type this after every single wrong answer:
System.exit(0);

I tried using a system exit but that was exiting when the guess was
  correct as well.

That's probably because you used else statement istead of else code block. Forgot about braces?


text:
Q: Auto assign an Entitlement to a specific record type case I am looking to auto assign a particular entitlement process to all cases of a particular record type once the case is created. The case page layout contains an Entitlement Name field which is used as a look up to the entitlement processes that the agents currently use to manually assign an entitlement to a case. How can I accomplish this requirement?

A: As I understand it correctly, you want to auto assign entitlement for a particular type of cases. You can achieve this using trigger. "EntitlementId" field in case is used to assign entitlements to case.
In your code you can check if record type is matching, you can populate that entitlement in case. You can refer to below article.
https://help.salesforce.com/s/articleView?id=sf.entitlements_auto_add.htm&type=5
Let me know if this helps.


text:
Q: How can i get this type of plugin in wordpress I need a plugin in wordpress which turns around the circle.
Here is the image link http://tinypic.com/r/2z4mvk8/8

A: There is a wordpress plugin CC Circle Progress Bar which will work for you.
Here is the link:
https://wordpress.org/plugins/cc-circle-progress-bar/


text:
Q: IE not working Windows 7 I'm using windows 7 and I am connected to wifi for my internet. At the moment, my skype is working but IE is unable to do any kind of browsing. I'm unable to understand what is issue. I tried chromo to and it is also not working.
Can anyone please help me fix this issue?
when i try to ping www.yahoo.com from cmd i get following message:
C:\Users\alpha>ping www.yahoo.com

Ping request could not find host www.yahoo.com. Please check the name and try ag
  ain.

A: I suspect any one of below scenario might caused,

*

*You might have working on proxy servers

*Your network got disconnected

Try below steps to make it working:-

*

*Shutdown your laptop

*Switch off modem and router

*Give some 2 minutes gap

*Start modem and router

*Once connected, Switch On the laptop

*Try accessing www.google.com

A: issue was related to DNS Server. I just executed following commands and it was working again:
ipconfig /flushdns
ipconfig /release
ipconfig /renew

after restart my internet was working properly.


text:
Q: How to convert u_char* to char[] in C I am working with snmp and the requests->requestvb->val.string function returns me a u_char* and I am trying to store that into a char[255].
u_char newValue = *(requests->requestvb->val.string)
char myArray[255];

I have tried a few approaches to copy the contents of newValue into myArray but everything seems to segfault. What am I doing wrong?
I have tried
memcpy(myArray, newValue);
Another attempt strncopy(myArray, newValue, sizeof(myArray));
What am I doing wrong?

A: Your newValue is of type char, and for all intents and purposes, your myArray is of type char*.
First off, I'm going to assume that you're using memcpy correctly, and that you're passing in 3 parameters instead of 2, where the 3rd parameter is the same as the one you use in strncpy.
When you try using strncpy or memcpy, you're going beyond the one character "limit" in newValue when attempting to copy everything to myArray.
The fix should be quite simple:
u_char* newValue = requests->requestvb->val.string;

Once you've done that, this should work. Of course, that's assuming that the size of myArray is in fact greater than or equal to 255 :)
As a side note (and this should go without saying), please make sure that your myArray has a null terminating character at the end if you ever plan on printing it. Not having one after performing copy operations, and then trying to print is a very common mistake and can also lead to seg faults.


text:
Q: What's the difference between custom url schemes that have two forward slashes vs those that do not? I'm looking at supporting a custom url scheme in my app. Apple's documentation notes this format without two forward slashes after the colon: myphotoapp:Vacation?index=1
URL schemes I've seen previously use :// not just : for example myphotoapp://Vacation?index=1. Both seem to work so what's the difference? Is one more technically correct than the other, one a newer format, or something?
It seems most of Apple's apps use :// according to this unofficial list.
I see there are important differences in parsing the URL with URLComponents that would cause your URL handling code to fail if you were to use them interchangeably:

*

*: path is Vacation and host is nil

*:// path is empty string and host is Vacation


text:
Q: What is better when using constructor parameters? Ill start with an example or two. Take the following sample class:
class Sample
{
    private object _someObject;

    public Sample(object someobject)
    {
        _someObject = someobject;

        // If I then wanted to pass someobject to a method within the constructor,
        // is it better to use the field version or the parameter version. Example:

        SomeMethod(someobject);

        // OR

        SomeMethod(_someObject);
    }
}

Additionally, I have just finished the book titled "Efficient C#" by Bill Wagner and would like to know if there are any more books out there with a similar format as this one.
I am interested in knowing why I should write code the way it is written (More efficient IL for example)
Thanks in advance guys :)

A: It makes no difference, they're all references to the same object.


text:
Q: 'mydata$column <- NULL' not working in function This is the function:
remove_column <- function(column_vector) {
  for (column in column_vector) {
    if (grepl('.y$', column)) {
      mydata$column <- NULL
    }
  }
}

What I think it'd doing: I'm passing a vector of my column names to the function, it's looping through list of names and asking whether the last characters of each column name are ".y". If that is the case, the function eliminates the column.
I've tried putting prints here and there to see my vector and to see whether the conditional evaluates to TRUE or FALSE, and everything seems to be working fine, but for some reason, it doesn't get rid of the column.
The following function returns my column vector:
duplicate_names <- function(col_names) {
  duplicates <- c()
  for (name in col_names) {
    # split by period i.e. colname.x would be [colname, x]
    if (lengths(strsplit(name, '\\.')) > 1) {
      duplicates <- c(duplicates, name)
    }
  }
  return(duplicates)
}

I usually call it like this:
duplicate_names(names(mydata))

This is what the vector of columns looks like:
c('v1.x', 'v2.y')

When I print the function it returns the following:
[1] "v1.x" "v2.y"

As requested by a user, the dput(droplevels(horsedata[1:5, 1:5])) (data that I am using for this):
dput(droplevels(horsedata[1:5, 1:5]))
structure(list(ÿþhorse_name = structure(c(3L, 1L, 2L, 4L, 5L), .Label = c("IM PRETTY FAMES",
"JESS ROYAL BUCKS", "KISS ME IM SUGAR", "LOLAMO", "RUN MADISON RUN"
), class = "factor"), owner_name = structure(c(3L, 2L, 1L, 5L,
4L), .Label = c("Christine Tavares", "Heste Sport, Inc.", "Picov Cattle Co.",
"Procter, Wayne and Carol", "Ruth F. Barbour"), class = "factor"),
    program = structure(1:5, .Label = c("1", "2", "3", "4", "5"
    ), class = "factor"), pp = 1:5, todays_cls = c(61L, 61L,
    61L, 61L, 61L)), .Names = c("ÿþhorse_name", "owner_name",
"program", "pp", "todays_cls"), row.names = c(NA, 5L), class = "data.frame")

A: We don't need a loop to subset the columns.
mydata[!grepl('\\.y$', column_list)]

If there are other columns not in the column_list and we want to keep them (assuming that the 'column_list' is ordered)
mydata[setdiff(1:ncol(mydata), grep('\\.y$', column_list))]

We can modify your function by

*

*changing .y$ to \\.y$ as . means any character and not just the dot

*Instead of $, we use [ to subset the dataset

*Return the dataset after the assignment

remove_column <- function(dat, column_vec) {
 for (column in column_vec) {
  if (grepl('\\.y$', column, perl=TRUE)) {
   dat[column] <- NULL
       }
    }
  dat
}

remove_column(mydata, column_list)
#   v1.x v2.x v3
#1     6    1  9
#2     4   11  7
#3    14   15  5
#4    10    2  4
#5    13    4  0
#6    19   14  1
#7     5    1  8
#8    16   12  7
#9    16   13  5
#10    5    0  7

data
mydata <- structure(list(v1.x = c(6L, 4L, 14L, 10L, 13L, 19L, 5L, 16L,
16L, 5L), v1.y = c(12L, 7L, 14L, 14L, 6L, 18L, 4L, 0L, 10L, 2L
), v2.x = c(1L, 11L, 15L, 2L, 4L, 14L, 1L, 12L, 13L, 0L), v2.y = c(6L,
5L, 7L, 3L, 19L, 4L, 15L, 13L, 14L, 20L), v3 = c(9L, 7L, 5L,
4L, 0L, 1L, 8L, 7L, 5L, 7L)), .Names = c("v1.x", "v1.y", "v2.x",
"v2.y", "v3"), row.names = c(NA, -10L), class = "data.frame")

column_list <- c('v1.x', 'v1.y', 'v2.x', 'v2.y')


text:
Q: command to report in sonar 5.2 I installed plugin "sonar-report-plugin" to get PDF report from sonar.
I have done all required setup in sonar for this plugin.
Now I just want to know what command to execute to get the report as "sonar-runner report" command is no longer functional in sonarqube5.2.

A: Indeed for technical reasons the Report plugin could not be kept compatible with SonarQube 5.2. Support is back in version 5.3, which first release candidate has been published today.
http://docs.sonarqube.org/display/SONAR/Release+5.2+Upgrade+Notes


text:
Q: How to exclude hypen and match first digit after it? i have a string "proofs 161798-2 PDF_Review_2.1_Whats_New"
I want to find the first digit after the hyphen.
however, i am using Enfocus Switch program and does not allow expressions such as (?<=-)/d{1}. It marks the ? and the () red. Does anyone have any suggestions or alternate ways of writing this without using a ? or ()
I tried using /(?<=-)\d{1} using regex 101 generator, and it worked. But after plugging it into Enfocus Switch program, it won't accept it as a valid expression. It states that there is an invalid grouping.

A: Would a JS solution work? You could try this:

const str = '161798-2 PDF_Review_2.1_Whats_New'
const afterHypen = str.split('-')[1].split('')
const digit = afterHypen.filter(character => !isNaN(Number(character)))[0]

console.log(digit)

OR if the digit will always be the first character after the hyphen then you could even just do this:

const str = '161798-2 PDF_Review_2.1_Whats_New'
const digit = str.split('-')[1][0]

console.log(digit)


text:
Q: line is the perpendicular bisector of a segment obtained by reflecting twice through two rays Given two rays, L and M, with common origin O, and a point Q inside the acute angle formed by the rays, reflect Q across L to obtain Q' and then reflect Q' across M to obtain Q''.  Similarly, reflect Q across M to obtain P' and then reflect P' across L to obtain P''.
Show that the line through O and Q is the perpendicular bisector of the segment joining P'' and Q''.
How do you do this?
It is easy to show that Q and all reflected points lie on the circle with center O that passes through Q.  I thought of using reflection across the line through O and Q and then use a symmetry argument but couldn't see just how to implement this idea.
I would really appreciate any help. Thanks

A: Thanks Emmad. As you said, the result follows. The fact you mention combined with the following show that the triangles that need to be shown are congruent in fact are:
the angle Q''Q'Q equals the angle P''P'Q so the arcs they intercept are the same.
Thank you for your answer


text:
Q: Using function_exists to check if a PHP function is found Is there a way using function_exists that I could check that if for example if 'mysql_query' is called and therefore I can run some code via the if statement? to basically error it so that I can go and change it to PDO?

A: function_exists() is only for checking if a function is defined rather than if a function is being called.
However you can rename and override a PHP function to get the desired effect, using a wrapper as @wogsland mentioned in the comments. This method requires APD installed. For example:
<?php

// First rename existing function
rename_function('mysql_query', 'original_mysql_query');

// Override function with another
override_function('mysql_query', '$query', 'return override_mysql_query($query);');

// Create the other function
function override_mysql_query($query)
{
    echo "Calling original_mysql_query($query)";
    return original_mysql_query($query);
}

A: In php 7, mysql_* functions are deleted and you are then able to redefine them pointing them to their new functions, such as mysqli or PDO.
But to answer your question, you could also rename the internal functions in PHP explained in this page:
http://php.net/manual/en/function.runkit-function-rename.php
And create a user function with the same name as the function you're trying to call and let it do something else instead. But I would not recommend it.
As NoChecksum also stated, "rename_function" and "override_function" is also an option.


text:
Q: Where is the kaggle competitions submodule? I am new to the kaggle python module and do not understand the structure. I am trying to execute the following command from a sample script here, but when I try to run the import it fails:
ModuleNotFoundError: No module named 'kaggle.competitions'

I used pip3 to install the module originally and did not have any errors in my install. Additionally, I can run import kaggle without errors, and I can use the command line interface for kaggle to download datasets. I looked at the github repository and also do not see a directory named competitions or a competitions.py. Can someone explain to me what step I missed here to have a competitions submodule? Is there an install script I should have run but didn't?
Also I tried iterating through the submodules of kaggle like this:
>>> l = [l for l in pkgutil.walk_packages(path = kaggle.__path__,
>>> [r[1] for r in l]
['api', 'api.kaggle_api', 'api.kaggle_api_extended', 'api_client', 'cli', 'configuration', 'models', 'models.dataset_column', 'models.dataset_new_request', 'models.dataset_new_version_request', 'models.dataset_upload_file', 'models.error', 'models.kaggle_models_extended', 'models.kernel_push_request', 'models.result', 'rest', 'tests', 'tests.test_authenticate']

But I don't see any competitions so not sure where to go from here. I'd welcome suggestions.
Thanks!

A: The module you're trying to use is only available in the Kernels environment and it's specific to that particular competition. It's a custom module used to interact with this competition's dataset within the Kernels environment.
By contrast, the module you're pip installing is Kaggle's public API.
I hope that helps clarify the behavior you're seeing.


text:
Q: Rich text editor with variables for email letters, localized I've got an acceptance email letter that we send. It has some user generated data. No problem with a standard erb email template, right? But changing it require redeploy. We also need it in many languages. I'd like an admin interface where we have guys maintaining these texts. Maybe using {{variable}} in some rich text editor, to be replace in Ruby when sending the email? Or use a lightweight CMS?
Summarize:

*

*rich text

*variables from data to populate them

*localization

The variables(from db) doesn't need localization, just the surronding content.
Any suggestions?


text:
Q: Using angularjs to request elasticsearch as cross domain I am making a web app using angularjs. I am making request on elasticsearch api. This is the code:
app.controller('usersDatas', function($scope, $http){
  $http.post("http://192.168.6.55:9200/userdata/_search", {headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
    data: "{ 'query': { 'query_string': { 'query': 'png' } } }"
    // Access-Control-Allow-Origin: true
  }).success(function(data){
    console.log(data);
  });
});

This is error I have :
XMLHttpRequest cannot load http://192.168.6.55:9200/userdata/_search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

I have added this :
http.cors:
  enable: true
  allow-origin: /https?:/\/\/localhost(:[0-9]+)?/

to my elasticsearch (/etc/elasticsearch/elasticesarch.yml) config. I don't know if the problem comes from elasticsearch or from angularjs.
How can I solve this ?
Thanks.

A: You must add in HEADER Access-Control-Allow-Origin
PHP Example:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

A: This is browser issue First close all the chrome browser windows ...

*

*open terminal

*sudo -i

*(Your Password)

then type

*

*google-chrome --disable-web--security

Then try the link in that url


text:
Q: forgot the technical term for capturing a value in returned function What is a function called that returns a function with earlier passed values populating it?
I know it's not a continuation, but I forget the functional-programming name for it.
Sorry this is a horrible question; my memory is just really bad today.
function negate(func) {
  return function(x) {
    return !func(x);
  };
}


text:
Q: How to change model structure of angular powered bootstrap ngbDatepicker I am using angular powered bootstrap ngbDatepicker. I have created my own custom control which will be used in different pages for date capturing as follows.
<form-date
  [label]="'Date of birth'"
  [name]="'inputCPDDOB'"
  [(ngModel)]="birthDate"
  placeholder="mm/dd/yyyy"
  required
  >
</form-date>

Here I have passed birthDate as my model object.
I want

*

*User should be able to choose the date by clicking the CAL button (beside the text box),

*User should be able to type a date in format 'MM/DD/YYYY' in the textbox.

*After selecting or typing the date, the model should be updated as string with format 'YYYY-MM-DD' by two way data binding.

I have successfully did point#1 and point#2 the date format of text box as MM/DD/YYYY by inheriting NgbDateParserFormatter
But I am not able to change the model structure. While I need to communicate with my web service as 'YYYY-MM-DD' format.
Please help me to achieve the same. Here is the plunker attached.

A: So I think the easiest way to solve your problem is to provide your own implementation of NgbDateAdapter and inject that into you component. You will need to add
{provide: NgbDateAdapter, useClass: NgbUTCStringAdapter}

to you components providers array and define the NgbUTCStringAdapter somewhere:
@Injectable()
export class NgbUTCStringAdapter extends NgbDateAdapter<string> {

  fromModel(date: string): NgbDateStruct {
    return (date && Number(date.substring(0, 4)) && Number(date.substring(5, 7) + 1) && Number(date.substring(8, 10))) ?
                {year: Number(date.substring(0, 4)),
                    month: Number(date.substring(5, 7)),
                    day: Number(date.substring(8, 10))} : null;
  }

  toModel(date: NgbDateStruct): string {
    return date ? date.year.toString() + '-' + String('00' + date.month).slice(-2)
                            + '-' + String('00' + date.day).slice(-2) : null;
  }
}

The other way to do it would be to put this code into your custom form control something like this:
@Component({
selector: 'app-date',
templateUrl: './date.component.html',
providers: [
    {
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => DateComponent),
        multi: true
    },
    {provide: NgbDateParserFormatter, useClass: NgbDateOmniParserFormatter}]
})

export class DateComponent implements ControlValueAccessor {

  model;

  writeValue(value: any) {
    this.model =  (value && Number(value.substring(0, 4)) &&
                        Number(value.substring(5, 7) + 1) &&
                        Number(value.substring(8, 10))) ?
                            {year: Number(value.substring(0, 4)),
                             month: Number(value.substring(5, 7)),
                             day: Number(value.substring(8, 10))} : null;
  }

  propagateChange = (_: any) => {};

  registerOnChange(fn) {
    this.propagateChange = fn;
  }

  registerOnTouched() {}

  change() {
    const date = this.model ? this.model.year.toString() + '-' +
                   String('00' + this.model.month).slice(-2) + '-' +
                   String('00' + this.model.day).slice(-2) : null;

    this.propagateChange(date);
  }
}


text:
Q: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' I got an error when I clicked submit button to edit the data.
my error :

"SQLSTATE[42S22]: Column not found: 1054 Unknown column '5' in 'where clause' (SQL: select * from users where (5 is null and role = siswa and name = Tom and email = tom@gmail.com and email_verified_at = 2021-09-13 11:35:17 and password = $2y$10$O5iNeRK0MM4PsRSW27KeMezkVYMZqgfJOXJW35zuh3Ve5lDi7buf2 and remember_token = PGLP0c51ArZHLHRzpGM8NYSlRofQ6umTq4rFaRGRr0ZnD7MtP7gmtBTdL7tX) limit 1)"

My Controller
public function store(Request $request)
{

    $user = User::updateOrCreate([
        [
            'id' => $request->id,
        ],
            'role' => 'siswa',
            'name' => $request->nama_depan,
            'email' => $request->email,
            'email_verified_at' => now(),
            'password' => bcrypt('rahasia'),
            'remember_token' => Str::random(60),
        ]);

    $siswa = Siswa::updateOrCreate(['user_id'=>$user->id, 'id'=>$request->id],
    [
        'nama_depan' => $request->nama_depan,
        'nama_belakang' => $request->nama_belakang,
        'jenis_kelamin' => $request->jenis_kelamin,
        'agama' => $request->agama,
        'alamat' => $request->alamat,
        'avatar' => $request->avatar,
    ]);

    if($request->hasfile('avatar')) {
        $request->file('avatar')->move('images/', $request->file('avatar')->getClientOriginalName());
        $siswa->avatar = $request->file('avatar')->getClientOriginalName();
        $siswa->save();
    }

    return json_encode(array(
        "statusCode"=>200
    ));
}

public function edit($id, Request $request)
{
    $this->validate($request, [
        'avatar' => 'mimes:jpg,png'
    ]);

    // $where = array('users.id' => $id);
    $siswa = Siswa::select(

        "siswa.id",
        "siswa.nama_depan",
        "siswa.nama_belakang",
        "siswa.jenis_kelamin",
        "users.email as email",
        "siswa.agama",
        "siswa.alamat"

    )

    ->join('users', 'users.id', '=', 'siswa.user_id')
    ->where('siswa.id', $id)
    ->first();

    if($request->hasfile('avatar')) {
        $request->file('avatar')->move('images/', $request->file('avatar')->getClientOriginalName());
        $siswa->avatar = $request->file('avatar')->getClientOriginalName();
        $siswa->update();
    }

    return response()->json($siswa);
}

My Model
public function user()
{
    return $this->belongsTo(User::class);
}

 public function siswa()
{
    return $this->hasOne(Siswa::class);
}

Jquery code
// /TOMBOL EDIT DATA PER PEGAWAI DAN TAMPIKAN DATA BERDASARKAN ID PEGAWAI KE MODAL
//ketika class edit-post yang ada pada tag body di klik maka
$('body').on('click', '.edit-siswa', function () {
    var data_id = $(this).data('id');
    $.get('siswa/' + data_id + '/edit', function (data) {
        console.log(data);
        $('#modal-judul').html("Edit Siswa");
        $('#btn-simpan').val("edit-siswa");
        $('#tambahModal').modal('show');
        //set value masing-masing id berdasarkan data yg diperoleh dari ajax get request diatas
        $('#id').val(data.id);
        $('#user_id').val(data.user_id);
        $('#nama_depan').val(data.nama_depan);
        $('#nama_belakang').val(data.nama_belakang);
        $('#jenis_kelamin').val(data.jenis_kelamin);
        $('#email').val(data.email);
        $('#agama').val(data.agama);
        $('#alamat').val(data.alamat);
    })
});

//SIMPAN & UPDATE DATA DAN VALIDASI (SISI CLIENT)
//jika id = formSiswa panjangnya lebih dari 0 atau bisa dibilang terdapat data dalam form tersebut maka
//jalankan jquery validator terhadap setiap inputan dll dan eksekusi script ajax untuk simpan data
if ($("#formSiswa").length > 0) {
    $("#formSiswa").validate({
        submitHandler: function (form) {
            var actionType = $('#btn-simpan').val();
            $('#btn-simpan').html('Sending..');
            $.ajax({
                data: $('#formSiswa')
                    .serialize(), //function yang dipakai agar value pada form-control seperti input, textarea, select dll dapat digunakan pada URL query string ketika melakukan ajax request
                url: "{{ route('siswa.store') }}", //url simpan data
                type: "POST", //karena simpan kita pakai method POST
                dataType: 'json', //data tipe kita kirim berupa JSON
                success: function (data) { //jika berhasil
                    $('#formSiswa').trigger("reset"); //form reset
                    $('#tambahModal').modal('hide'); //modal hide
                    $('#btn-simpan').html('Simpan'); //tombol simpan
                    var oTable = $('#table-siswa').dataTable(); //inialisasi datatable
                    oTable.fnDraw(false); //reset datatable
                    toastr.success({ //tampilkan iziToast dengan notif data berhasil disimpan pada posisi kanan bawah
                        title: 'Data Berhasil Disimpan',
                        message: '{{ Session('
                        success ')}}',
                        position: 'bottomRight'
                    });
                },
                error: function (data) { //jika error tampilkan error pada console
                    console.log('Error:', data);
                    $('#btn-simpan').html('Simpan');
                }
            });
        }
    })
}

A: u need to pass as array

updateOrCreate([condition],[values])

       public function store(Request $request)
       {

           $user = User::updateOrCreate(
               [
                   'id' => $request->id,
               ],[
                   'role' => 'siswa',
                   'name' => $request->nama_depan,
                   'email' => $request->email,
                   'email_verified_at' => now(),
                   'password' => bcrypt('rahasia'),
                   'remember_token' => Str::random(60),
                  ]
               );
       }


text:
Q: Confine dimension of an existing memmap (NumPy) I have a .dat file containing a large (600000,6,8000) float array generated with numpy.memmap.
The third axis represents a date range. At runtime, the user specifies a narrower date range.  The result is that I end up slicing along the 3rd dimension array[i, :, user_start:user_end] millions of times during execution.
I know it's possible to offset the memmap by a fixed number, but is there a way to confine the dimensions of the array at the beginning of the run such that I don't need to slice the third axis each time?

A: A slice of a memory mapped array creates another memory mapped array with the same underlying file, so you could create a new array that is the slice defined by the user input, and use the new array from then on.
If a is the memory mapped array, define
b = a[:, :, user_start:user_end]

and then use b instead of repeatedly making the same slice of a.  That is, instead of a[i, :, user_start:user_end], use b[i, :, :] (or b[i, :] or even just b[i], since the final : in a numpy index is optional).


text:
Q: Vagrant with VMware-Fusion gets connection timeout at `vagrant up` but not `vagrant ssh` I am using Vagrant and VMware-Fusion to build a simple centos 7 vm. The box is custom built with our own private key.
When running vagrant up --provider=vmware_fusion I get the error
Warning: Connection timeout. Retrying...

and the job times out (even when I set a very very high timeout with config.vm.boot_timeout)
However, I am able to successfully connect to the box with vagrant ssh, therefore I assume that my private key file is correct.
I have opened the VMware Fusion GUI and see that the box is just sitting at the login prompt while vagrant is trying to get into it. When there, I am able to manually login with my username and password.


text:
Q: Rendering PartialView to string inconveniences I'm developing ASP.NET MVC5 (Razor) project. I would like to render partial view into a DIV when Test ActionLink clicked, so code for Controller is this:-
public ActionResult Accion(string vista)
{
    if (string.IsNullOrEmpty(vista) || !Request.IsAjaxRequest())
        return View();
    else
    {
            object vistaModelo = null;
            if (vista.Contains("Usuarios"))
                vistaModelo = new UsuariosVistaModelo();
            string render = PartialView(vista, vistaModelo).RenderToString();
            return Json(new { data = render });
    }
}

Code for cshtml:-

@Html.ActionLink("Test","Accion","Navigation",new { vista = "~/Views/Soporte/Usuarios.cshtml" }, new { @class = "accion" })

When I click on Test ActionLink,  $('.accion').live("click" ... event is not triggered and go straighforward to Accion into controller. Please need help. Thanks

A: Some modifications in your code to make it working
** Modify your action to
@Html.ActionLink("Test","Accion","Navigation",new { vista = "~/Views/Soporte/Usuarios.cshtml" }, new { @class = "accion", onclick = "javascript:return false;"  })

Now anchor default behaviour would not work.
** Now modify your Jquery like
//Dispara la acción en el controlador del servidor
$('.accion').click(function () {
    $.ajax({
        url:this.href,
        type:'post',
        data : {"vista" : "~/Views/Soporte/Usuarios.cshtml"},
        success:function(data)
        {
            //data contiene el resultado devuelto por el servidor
            $('.content').html(data);
        },
        error: function (req, status, error) {
            alert(error);
        }
    });
    //Se retorna falso para prevenir reenviar a otra pagina
    return false;
});

//Add Post on the top of action
[HttpPost]
public ActionResult Accion(string vista)
{
if (string.IsNullOrEmpty(vista) || !Request.IsAjaxRequest())
    return View();
else
{
        object vistaModelo = null;

        if (vista.Contains("Usuarios"))
            vistaModelo = new UsuariosVistaModelo();

        string render = PartialView(vista, vistaModelo).RenderToString();
        return Json(new { data = render });
}
}

Also use on/click instead of live

A: Some modification on Jquery level
   // code
        success:function(data)
        {
            $('.content').html(data.data);
        },
        error: function (req, status, error) {
            alert(error);
        }
  //  code

try to replace
 $('.content').html(data);  to  $('.content').html(data.data); Here 2nd data is the parameter which holds the value on controller.


text:
Q: Using Android app to manipulate Webpages I used to know of Selenium and WebDriver which allowed through code to manipulate webpage elements such as Textfields and Buttons, but i am not sure if these tools exist now or are relevant.
Say for example, i have a button on my app that does a specific search on Google
1) Enter www.google.com
2) Enter Text in the Search field
3) simulate a button click (Search)

A: You can use a WebView and inject JavaScript. You will need to set a JavaScript Interface to interact between native android code and the webpage.


text:
Q: Non-independence in data and GLMMs I am working with a dataset that consists of categorical variables and count data. My response variable is DPM SpeciesA (detection positive minutes of Species A, where for each hour I have a count of how many minutes species A was vocalizing), and my predictors are Season, Time of day (classified as "Morning", "Evening", "Night" and "Day"), Tidal cycle ("High tide", "Ebbing tide"...) and DPM SpeciesB.
I am wondering how to account for the non-independence in my data. Because the vocalizations of Species A are being recorded, but we have no way of knowing which individual is vocalizing, there is non-independence since the same individual may be vocalizing for multiple minutes, or different individuals, and each hour it could be the same individuals, or different individuals.
So my question is, is it not possible to use GLMs in this case because of the non-independence? And if it is not possible, then how could I account for the non-independence in a mixed model? I don't understand how to incorporate any dependency into the model because I can't add the ID of the individual as a random factor, since we never know which individual is being counted.
Thanks for your help everyone!
Edit: I have now included some plots that I have made to try to determine whether violating independence would be a problem (at least in terms of temporal autocorrelation) in a quasipoisson GLM for this data. These are Acf, Residuals vs Index and a residuals lag plot. But I am not very experienced interpreting these plots! To me it looks like there is no particular problem with the residuals vs index (except that everything is above zero, not sure if there should also be negatives) but the Acf and Residuals lag both seem to have a pattern.

A: Welcome to the site, roc. It may be possible to employ a mixed modeling framework to your data. How many different species did you record? If there are 10-15 or more, then you could have the grouping variable be species. This would indicate that you believe that vocalization frequency is more correlated within species than it is across different species. That being said, this doesn't really solve the problem you identified about individual members of the species. That is not something you can deal with given your data. You would have to use some sort of machine learning algorithm to try to identify individuals within species, and I'm not sure that would work (it might, I just don't know much about that).
However, if you only have two species (you mention SpeciesA and SpeciesB), then you are in a more difficult position. Since you cannot identify individuals within SpeciesA and SpeciesB, you cannot account for the likely fact that some members of the Species will be more likely to repeatedly call. Is it correct to assume that you want to have a predictor for SpeciesB in the model for SpeciesA vocalizations? Or were you just saying you wanted to generate the same model for each species?
If you have multiple species, there are many different R packages for doing this type of analysis with your count outcome, including glmer() in lme4, glmmTMB() and GLMMadaptive.


text:
Q: How to use re module in python to extract information? I write a little script to use collins website for translation. heres my code:
import urllib.request
import re
def translate(search):
    base_url = 'http://www.collinsdictionary.com/dictionary/american/'
    url = base_url + search
    p = urllib.request.urlopen(url).read()
    f = open('t.txt', 'w+b')
    f.write(p)
    f.close()
    f = open('t.txt', 'r')
    t = f.read()
    m = re.search(r'()(\w.*)(]*)',t)
    n = m.group(2)
    print(n)
    f.close()

I have some questions:

*

*I can't use re.search on p. it raises this error:
TypeError: can't use a string pattern on a bytes-like object
is there a way to use re.search without saving it?

*After saving file I should reopen it to use re.search otherwise it raises this error: TypeError: must be str, not bytes why this error happens?

*in this program I want to extract information between  and  from first match. but pattern that I wrote not work good in all cases. for example translate('three') is good. out put is : "totaling one more than two" but for translate('tree') out put is:
"a treelike bush or shrub   ⇒ a rose tree"
is there a way to correct this pattern. regular expression or any other tools?

A: When you call read on the response returned by urllib, you get a bytes object, which you need to decode to convert it to a string.
Change
    p=urllib.request.urlopen(url).read()

to
    p=urllib.request.urlopen(url).read().decode('utf-8')

You should read this https://docs.python.org/3/howto/unicode.html to understand why because issues like this come up a lot.
Also, you probably don't want to parse HTML using regex. Some better alternatives for Python are mentioned here.


text:
Q: Can't extract the contents of $_FILES using exif_read_data I am just new to using php and have been totally stumped for the last several days.
I am trying to extract and use the Key-value pairs extracted from multiple arrays in the $_FILES. I am sure this is a ridiculously dumb question but I am stumped.  if I run the following code I get the following results.
$exif = exif_read_data('/uploads/'.$file['name'],  0, true);

  foreach($_FILES as $file){
  echo $file['name']  .  " :
\n";
  foreach ($exif as $key => $section) {
      foreach ($section as $name => $val) {

          echo "
This is \$name" . $name ."
";
          echo "
This is \$val" . $val ."
";
          }
        }
     }

The following is the output:
Uploaded Image
Image contains headers
Across the Field - LK.jpg :
FILE.FileName: Across the Field - LK.jpg
FILE.FileDateTime: 1361055472
FILE.FileSize: 294785
FILE.FileType: 2
FILE.MimeType: image/jpeg
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, EXIF
COMPUTED.html: width="700" height="525"
COMPUTED.Height: 525
COMPUTED.Width: 700
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 0
COMPUTED.ApertureFNumber: f/9.0
COMPUTED.Copyright: Copyright 2010
IFD0.ImageWidth: 1024
IFD0.ImageLength: 768
IFD0.BitsPerSample: Array
IFD0.PhotometricInterpretation: 2
IFD0.Model: NIKON D300
IFD0.Orientation: 1
IFD0.SamplesPerPixel: 3
IFD0.XResolution: 720000/10000
IFD0.YResolution: 720000/10000
IFD0.ResolutionUnit: 2
IFD0.Software: Adobe Photoshop CS5 Windows
IFD0.DateTime: 2013:01:24 16:33:16
IFD0.Artist: lken
IFD0.Copyright: Copyright 2010
IFD0.Exif_IFD_Pointer: 316
THUMBNAIL.Compression: 6
THUMBNAIL.XResolution: 72/1
THUMBNAIL.YResolution: 72/1
THUMBNAIL.ResolutionUnit: 2
THUMBNAIL.JPEGInterchangeFormat: 642
THUMBNAIL.JPEGInterchangeFormatLength: 0
EXIF.ExposureTime: 1/100
EXIF.FNumber: 9/1
EXIF.ISOSpeedRatings: 400
EXIF.ExifVersion: 0221
EXIF.DateTimeOriginal: 2010:08:15 05:57:17
EXIF.DateTimeDigitized: 2010:08:15 05:57:17
EXIF.ShutterSpeedValue: 6643856/1000000
EXIF.ApertureValue: 633985/100000
EXIF.FocalLength: 1700/100
EXIF.ColorSpace: 65535
EXIF.ExifImageWidth: 700
EXIF.ExifImageLength: 525

For brevity sake I left out the data from the second photo.
The following is the output of $_FILES:
Array
(
    [userfile] => Array
        (
            [name] => Across the Field - LK.jpg
            [type] => image/jpeg
            [tmp_name] => C:\wamp\tmp\php223.tmp
            [error] => 0
            [size] => 294785
        )

    [userfile1] => Array
        (
            [name] => autumn-panorama - lk.jpg
            [type] => image/jpeg
            [tmp_name] => C:\wamp\tmp\php224.tmp
            [error] => 0
            [size] => 106349
        )
)

I have looked on every site and in every book I can find to find how to access the name value pairs (such as IFD0.ImageWidth: 1024 and IFD0.ImageLength: 768 ) so I can set restrictions on upnload sizes etc.
I am now very confused and will appreciate any help or direction.  Resources are especially appreciated.  Thank you.

A: Well, that code snippet already does the job, hence for your first file, you should be able to do the below.
$exif = exif_read_data($_FILES['userfile']['tmp_name'],  0, true);

if (isset($exif['IFD0']['ImageWidth']) && isset($exif['IFD0']['ImageLength']))
{
    // good to go!
    $width = $exif['IFD0']['ImageWidth'];
    $height = $exif['IFD0']['ImageLength'];
}
else
{
    // size data not present, fallback onto something else
    return;
}

Now, with that said, you should not trust the exif data to do your constraint validation! Exif data are metadata. They can be spoofed/injected easily, or not be there at all. Instead do an analysis of the actual image data, by firstly checking file size itself, and then using getimagesize() for example. See http://www.php.net/manual/en/function.getimagesize.php


text:
Q: Is there a way to shut off the comic relief voices in Oddworld: New 'n' Tasty? I'm playing Oddworld: New 'n' Tasty on Steam. It's taken some liberties over the original game, some good and some not so much. There's one that's grating for me: the Sligs and Mudokons all have some idle comic relief commentary, and they'll mutter it constantly, stuff like:

Slig: Ugh, when's lunch?
Slig: Maybe I'll even get paid this month.
Mudokon: Another day in the office...
Mudokon: Employee of the month! Now I even have my own brush!

In the original, everyone was silent and there was a really oppressive atmosphere to Rupture Farms. Suffice to say this commentary is really atmosphere-breaking for me and is making it hard to fully enjoy the game.
Is there a way to shut off the commentary, and only the commentary?
The volume control for voices also controls gamespeak and cues like a Slig saying "what!?", and subtitles don't display these messages, so that in itself doesn't solve much.


text:
Q: Intermittent OLEObject Name property error This morning I've had problems with a section of my code which had previously worked fine.  Now i get (seemingly at random) one of 3 different error messages to do with the OLEObject i am referencing.  The most commonly occuring message is this:

Object library invalid or contains  references to onject definitions
  that could not be found

edit:  when stepping into the code once the workbook has been reopened i get this message:

Run-time error '1004':
  Activate method of OLEObject Class failed

Removing the .ActivateLine, I get:

Run-time error '1004':
  Unable to get the name property of the OLEObject class

The debuger stops on the sub line, however it should be said that sometimes this code will run fine, to the point where sometimes it will throw an error for the name, I will end, restart and it will loop again, hit the same error and we repeat until all objects are deleted.
I am currently trying to replicate the  two messages that occur during the code to add them to the post.  From memory they were something to do with the name property of OLECont- however this should not be a problem.
My code is below:
Sub ClearGenerate()
Dim rngToClear As Range
Dim OLECont As OLEObject

'Clean down worksheet
Set rngToClear = Worksheets("Generate").Range("b17:F17")
rngToClear.Clear
Set rngToClear = Worksheets("Generate").Range("b24:F150")
rngToClear.Clear

'Clear out modules and buttons

For Each OLECont In Worksheets("Generate").OLEObjects
    OLECont.Activate
    ClearModule OLECont.Name
    OLECont.Delete
Next

End Sub

I added the OleCont.Activate in response to this post, but to no avail:
I found an Excel configuration error: Unable to get the Object property of the OLEObject class


text:
Q: Permissions for Banner notification in Android I am trying to implement an application in Android which needs to show Banner notifications, like in the image below.

It works well on most of the devices. But on some devices it doesn't show banner notification, instead it just shows as a normal notification.
It doesn't work especially in Huawei devices. Looking for the issues I was able to see that there is an options in the settings which will let you customize the notifications. And some apps will have the banner permission enabled for showing notifications.

I was able to see that some apps including WhatsApp was able to get the Banner permission enabled, directly after the app is installed. If I toggle the banner permission to enabled manually in my application, then everything works as expected.
Is there some special AndroidManifest permission needed or should I be doing something specific to have the banner notification enabled.

A: You can try this -
 <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

Source - Android notification turn on banner setting programmatically
For more info have a look on Manifest and Notification documentation.


text:
Q: The Decimal Data Type in SQL Server Why does the following return .500000 rather than .500?
SELECT 50 / CAST(100 AS decimal(3))

A: Because you are casting the divisor not the result. And you have not specified precision.
See this for examples:
SELECT 50 / CAST(100 AS decimal(3))
      ,50 / CAST(100 AS decimal(6,3))
      ,CAST (50 / CAST(100 AS decimal(3)) AS decimal(3))
      ,CAST (50 / CAST(100 AS decimal(3)) AS decimal(6,3))

Precision, Scale, and Length (Transact-SQL)

Precision is the number of digits in a number. Scale is the number of
  digits to the right of the decimal point in a number. For example, the
  number 123.45 has a precision of 5 and a scale of 2.

DECIMAL uses a default precision of 18 and scale of 3.
Therefore when you case to DECIMAL(3) you get a DECIMAL(3,0). Then you use it as a divisor and SQL Server follows its rules for the resultant scale.
Operation  Result precision                     Result scale
e1 / e2    p1 - s1 + s2 + max(6, s1 + p2 + 1)   max(6, s1 + p2 + 1)


text:
Q: strong maximum principle for $u$ such that $u'' \geq c(x)u$ I want to prove that if $I$ is an interval in $R$, $c(x) \geq 0$ is continuous and $u \leq 0$ is $C^2$ then if for all $x$
$$u''(x) \geq c(x)u(x)$$ then the strong maximum principle holds for $u$, i.e. if there exists a point $x_0 \in I$ such that $u(x_0) = 0$ then $u$ is identically equal to 0 on the whole interval.
in the notes I'm using there's something like a proof, although it's not complete in my opinion or I just don't get it. it is said that $u$ is a solution of a differential equation $u'' - cu = g(x)$ (which is actually the definition of $g$) and so the Cauchy-Lipschitz theorem ends the proof because the zero function is also a solution. That doesn't seem to work very well because $g$ needs not be $0$ as a function of $x$. on the other hand if we take it to be a function of $(x,u)$ then it's not even well defined with respect to $u$ (because of the derivative) and we have no means of knowing if its Lipschitz with respect to $u$.
can anyone provide any suggestions please?


text:
Q: How to pass parameter from masterpage to all pages xamarin form I have Masterpage which appear after I click on button.
Here is my code.
App.cs
public App()
 {
   // The root page of your application
   MainPage = new NavigationPage(new Login());
 }

Login.cs
public void button(object sender, EventArgs e)
 {
   MasterDetailPage fpm = new MasterDetailPage();
   fpm.Master = new MasterPage(**test.Text**) { Title = "Main Page" }; // You have to create a Master ContentPage()
   fpm.Detail = new NavigationPage(new PageOne()); // You have to create a Detail ContenPage()
   Application.Current.MainPage = fpm;
 }

From login page i'm passing parameter to Masterpage (i.e.) test.text, I want to pass this parameter to all pages in the Mastepage, but I dont know how to do it.
MasterPage.cs
public MasterPage(string id)
 {
   InitializeComponent();
   BindingContext = new MasterViewModel();
 }

MasterViewModel.cs
public ICommand NavigationCommand
 {
  get
   {
     return new Command((value) =>
      {
        // COMMENT: This is just quick demo code. Please don't put this in a production app.
        var mdp = (Application.Current.MainPage as MasterDetailPage);
        var navPage = mdp.Detail as NavigationPage;
        // Hide the Master page
        mdp.IsPresented = false;
         switch(value)
          {
            case "1":
                    navPage.PushAsync(new PageOne());
                    break;
            case "2":
                    navPage.PushAsync(new PageTwo());
                    break;
          }
      });
   }
}

So basically what I need is after login I want to pass id to Masterpage, so all pages in Masterpage can get that id and based on id I can work on this project.

A: You can use the messaging center.
You send like this :
MessagingCenter.Send<MainPage> (this, "Hi");

You receive like this :
MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});

And don't forget to unsubscribe :
MessagingCenter.Unsubscribe<MainPage> (this, "Hi");


text:
Q: how to delete a component in react? I want to delete it.But it won't be deleted.
If you click the delete text in the modal, it should be deleted, but it doesn't work.What should I do to delete it?
There's an error saying that onRemove is not a function.Please help me.
I want to delete it.But it won't be deleted.
If you click the delete text in the modal, it should be deleted, but it doesn't work.What should I do to delete it?
There's an error saying that onRemove is not a function.Please help me.
export default function Modal({ onRemove, id }) {
  return (
    <OptionModalWrap>
      <ModalWrapper>
        <TitleWrap>Edit</TitleWrap>
        <TitleWrap>Duplicate</TitleWrap>
        <DeleteText onClick={() => onRemove(id)}>Delete</DeleteText>
      </ModalWrapper>
    </OptionModalWrap>
  );
}

export default function GroupList({ title, onRemove }) {
  const [showModal, setShowModal] = useState(false);

  const optionModal = () => {
    setShowModal(prev => !prev);
  };

  return (
    <AdGroups>
      <Header>
        <Container>
          <ActiveWrap>
            <ActiveIcon src={Active} />
            <SubTitle>Active</SubTitle>
          </ActiveWrap>
          <Alaram>
            <Bell src={bell} />
            <Text className="alarmCount">10</Text>
          </Alaram>
        </Container>
        <EtcIconWrap>
          <EtcIcon src={plus} onClick={optionModal} />
          {showModal && (
            <OptionModal showModal={showModal} onRemove={onRemove} />
          )}
        </EtcIconWrap>
      </Header>
      <GroupTitle>{title}</GroupTitle>
    </AdGroups>
  );
}

export default function GroupPage() {
  const [Groupdata, setGroupData] = useState([]);

  const onRemove = item => {
    setGroupData(Groupdata.filter(item => item.id !== item));
  };

  useEffect(() => {
    fetch('./data/AdsGroup/AdsGroupList.json')
      .then(res => res.json())
      .then(res => setGroupData(res));
  }, []);

  return (
    <GroupPages>
      {Groupdata.map(item => {
        return (
          <GroupList key={item.id} title={item.title} onRemove={onRemove} />
        );
      })}
    </GroupPages>
  );
}

A: You have not passed the id in GroupList and then also to the OptionModal component.
So here is the revised code:
Group Page Component:
Passing the id to GroupList Component
const onRemove = id => {
    setGroupData(Groupdata.filter(item => item.id !== id)); // you were item.id !== item which was wrong
  };

<GroupList key={item.id} title={item.title} id={item.id} onRemove={onRemove} /> // passing the id

Group List Component:
Added id in the props and passed that to Modal Component. Also calling optionModal function to close the Modal after it deleted
export default function GroupList({ id, title, onRemove }) {
  const [showModal, setShowModal] = useState(false);

  const optionModal = () => {
    setShowModal(prev => !prev);
  };

  return (
    <AdGroups>
      <Header>
        <Container>
          <ActiveWrap>
            <ActiveIcon src={Active} />
            <SubTitle>Active</SubTitle>
          </ActiveWrap>
          <Alaram>
            <Bell src={bell} />
            <Text className="alarmCount">10</Text>
          </Alaram>
        </Container>
        <EtcIconWrap>
          <EtcIcon src={plus} onClick={optionModal} />
          {showModal && (
            <OptionModal id={id} showModal={showModal} onRemove={onRemove;optionModal} />
          )}
        </EtcIconWrap>
      </Header>
      <GroupTitle>{title}</GroupTitle>
    </AdGroups>
  );
}

Modal Component: No change in this component
export default function Modal({ onRemove, id }) {
  return (
    <OptionModalWrap>
      <ModalWrapper>
        <TitleWrap>Edit</TitleWrap>
        <TitleWrap>Duplicate</TitleWrap>
        <DeleteText onClick={() => onRemove(id)}>Delete</DeleteText>
      </ModalWrapper>
    </OptionModalWrap>
  );
}

A: Didn't your IDE complaint about this piece of code? both of the onRemove & filter functions' props are called item, it shouldn't be.
  const onRemove = itemId => {
    setGroupData(Groupdata.filter(item => item.id !== itemId));
  };


text:
Q: openmp parallelization of spmv in csc How would one OpenMP parallelize following sparse matrix vector multiplication where matrix is in compressed sparse column format?
do i=1,lastcol
   do k=ia(i),ia(i+1)-1
      ind=ja(k)
      y(ind)=y(ind)+x(i)*a(k)
   end do
end do

Here, ia, ja, and a are column pointer, row index, and nonzero value of matrix respectively. Thanks.

A: Does the following work for you (updated with ATOMIC clause to prevent problem identified by Massimiliano)
!$ OMP PARALLEL DO PRIVATE(k, ind, temp)
do i=1,lastcol
   do k=ia(i),ia(i+1)-1
      ind=ja(k)
      temp = x(i)*a(k)
      !$ OMP ATOMIC
      y(ind)=y(ind)+temp
      !$ OMP END ATOMIC
   end do
end do
!$ OMP END PARALLEL DO

This should divide the "work" of the outer loops over a number of different processors, whilst making sure that there are separate copies of the inner loop variables k and ind
It's been a while since I have used OMP - if this doesn't work for you please use the comments to let me know. Meanwhile there is a very nice reference/tutorial here
Also - you will find a similar question was asked earlier - although the language was C, the basic loop structure was very similar. The conversation there suggests that when the matrix gets quite large (exceeding the size of the cache), the speedup from parallelization is minimal.


text:
Q: Household mail merge (code golf) I wrote some mail merge code the other day and although it works I'm a turned off by the code. I'd like to see what it would look like in other languages.
So for the input the routine takes a list of contacts
Jim,Smith,2681 Eagle Peak,,Bellevue,Washington,United States,98004
Erica,Johnson,2681 Eagle Peak,,Bellevue,Washington,United States,98004
Abraham,Johnson,2681 Eagle Peak,,Bellevue,Washington,United States,98004
Marge,Simpson,6388 Lake City Way,,Burnaby,British Columbia,Canada,V5A 3A6
Larry,Lyon,52560 Free Street,,Toronto,Ontario,Canada,M4B 1V7
Ted,Simpson,6388 Lake City Way,,Burnaby,British Columbia,Canada,V5A 3A6
Raoul,Simpson,6388 Lake City Way,,Burnaby,British Columbia,Canada,V5A 3A6

It will then merge lines with the same address and surname into one record. Assume the rows are unsorted). The code should also be flexible enough that fields can be supplied in any order (so it will need to take field indexes as parameters). For a family of two it concatenates both first name fields. For a family of three or more the first name is set to "the" and the lastname is set to "surname family".
Erica and Abraham,Johnson,2681 Eagle Peak,,Bellevue,Washington,United States,98004
Larry,Lyon,52560 Free Street,,Toronto,Ontario,Canada,M4B 1V7
The,Simpson Family,6388 Lake City Way,,Burnaby,British Columbia,Canada,V5A 3A6
Jim,Smith,2681 Eagle Peak,,Bellevue,Washington,United States,98004

My C# implementation of this is:
var source = File.ReadAllLines(@"sample.csv").Select(l => l.Split(','));
var merged = HouseholdMerge(source, 0, 1, new[] {1, 2, 3, 4, 5});

public static IEnumerable<string[]> HouseholdMerge(IEnumerable<string[]> data, int fnIndex, int lnIndex, int[] groupIndexes)
{
    Func<string[], string> groupby = fields => String.Join("", fields.Where((f, i) => groupIndexes.Contains(i)));

    var groups = data.OrderBy(groupby).GroupBy(groupby);

    foreach (var group in groups)
    {
        string[] result = group.First().ToArray();

        if (group.Count() == 2)
        {
            result[fnIndex] += " and " + group.ElementAt(1)[fnIndex];
        }
        else if (group.Count() > 2)
        {
            result[fnIndex] = "The";
            result[lnIndex] += " Family";
        }

        yield return result;
    }
}

I don't like how I've had to do the groupby delegate. I'd like if C# had some way to convert a string expression to a delegate. e.g. Func groupby = f => "f[2] + f[3] + f[4] + f[5] + f[1];" I have a feeling something like this can probably be done in Lisp or Python. I look forward to seeing nicer implementation in other languages.
Edit: Where did the community wiki checkbox go? Some mod please fix that.

A: Ruby — 181 155
Name/surname indexes are in code:a and b. Input data is from ARGF.
a,b=0,1
[*$<].map{|i|i.strip.split ?,}.group_by{|i|i.rotate(a).drop 1}.map{|i,j|k,l,m=j
k[a]+=' and '+l[a]if l
(k[a]='The';k[b]+=' Family')if m
puts k*','}

A: Python 2.6.6 - 287 Characters
This assumes you can hard code a filename (named i). If you want to take input from command line, this goes up ~16 chars.
from itertools import*
for z,g in groupby(sorted([l.split(',')for l in open('i').readlines()],key=lambda x:x[1:]), lambda x:x[2:]):
 l=list(g);r=len(l);k=','.join(z);o=l[0]
 if r>2:print'The,'+o[1],"Family,"+k,
 elif r>1:print o[0],"and",l[1][0]+","+o[1]+","+k,
 else:print','.join(o),

Output
Erica and Abraham,Johnson,2681 Eagle Peak,,Bellevue,Washington,United States,98004
Larry,Lyon,52560 Free Street,,Toronto,Ontario,Canada,M4B 1V7
The,Simpson Family,6388 Lake City Way,,Burnaby,British Columbia,Canada,V5A 3A6
Jim,Smith,2681 Eagle Peak,,Bellevue,Washington,United States,98004

I'm sure this could be improved upon, but it is getting late.

A: Python - 178 chars
import sys
d={}
for x in sys.stdin:F,c,A=x.partition(',');d[A]=d.get(A,[])+[F]
print"".join([" and ".join(v)+c+A,"The"+c+A.replace(c,' Family,',1)][2<len(v)]for A,v in d.items())

Output
Jim,Smith,2681 Eagle Peak,,Bellevue,Washington,United States,98004
The,Simpson Family,6388 Lake City Way,,Burnaby,British Columbia,Canada,V5A 3A6
Larry,Lyon,52560 Free Street,,Toronto,Ontario,Canada,M4B 1V7
Erica and Abraham,Johnson,2681 Eagle Peak,,Bellevue,Washington,United States,98004

A: Python - not golfed
I'm not sure what the order of the rows should be if the indices are not 0 and 1 for the input file
import csv
from collections import defaultdict

class HouseHold(list):
    def __init__(self, fn_idx, ln_idx):
        self.fn_idx = fn_idx
        self.ln_idx = ln_idx

    def append(self, item):
        self.item = item
        list.append(self, item[self.fn_idx])

    def get_value(self):
        fn_idx = self.fn_idx
        ln_idx = self.ln_idx
        item = self.item
        addr = [j for i,j in enumerate(item) if i not in (fn_idx, ln_idx)]
        if len(self) < 3:
            fn, ln = " and ".join(self), item[ln_idx]
        else:
            fn, ln = "The", item[ln_idx]+" Family"
        return [fn, ln] + addr

def source(fname):
    with open(fname) as in_file:
        for item in csv.reader(in_file):
            yield item

def household_merge(src, fn_idx, ln_idx, groupby):
    res = defaultdict(lambda:HouseHold(fn_idx, ln_idx))
    for item in src:
        key = tuple(item[x] for x in groupby)
        res[key].append(item)
    return res.values()

data =  household_merge(source("sample.csv"), 0, 1, [1,2,3,4,5,6,7])
with open("result.csv", "w") as out_file:
    csv.writer(out_file).writerows(item.get_value() for item in data)

A: Haskell - 341 321
(Changes as per comments).
Unfortunately Haskell has no standard split function which makes this rather long.
Input to stdin, output on stdout.
import List
import Data.Ord
main=interact$unlines.e.lines
s[]=[]
s(',':x)=s x
s l@(x:y)=let(h,i)=break(==k)l in h:(s i)
t[]=[]
t x=tail x
h=head
m=map
k=','
e l=m(t.(>>=(k:)))$(m c$groupBy g$sortBy(comparing t)$m s l)
c(x:[])=x
c(x:y:[])=(h x++" and "++h y):t x
c x="The":((h$t$h x)++" Family"):(t$t$h x)
g a b=t a==t b

A: Lua, 434 bytes
x,y=1,2 s,p,r,a=string.gsub,pairs,io.read,{}for j,b,c,d,e,f,g,h,i in r('*a'):gmatch('('..('([^,]*),'):rep(7)..'([^,]*))\n')
do k=s(s(s(j,b,''),c,''),'[,%s]','')for l,m in p(a)do if not m.f and (m[y]:match(c) and m[9]==k) then z=1
if m.d then m[x]="The"m[y]=m[y]..' family'm.f=1 else m[x]=m[x].." and "..b m.d=1 end end end if not z then
a[#a+1]={b,c,d,e,f,g,h,i,k} end z=nil end for k,v in p(a)do v[9]=nil print(table.concat(v,','))end


text:
Q: how to change src of an img element even before the DOM loads I was wondering if there exists a carousel which has a bunch of images  shown to the user, but lets say that based on the User, the img shown in the carousel needs to change to something else. How can one change the img src, even before the page loads?  The DOM does not actually exist for us to get the dom element for img element and change its src to the new image? how can one do it?
I was thinking may be have a inline script tag within the head section where the async is set to false which does not block the loading of the DOM. I am not sure. Please let me know if there are any other alternatives or html5 features for this

A: You can't use JavaScript to access the DOM before it is loaded. The best way to deal with this is to compile your HTML on the server-side using a templating language like handlebars (depends on what your backend language is). However, if this isn't an option you could also just put a place-holder loading symbol in the place of your image and then dynamically add a src url once your  has loaded in the DOM and then use JS or jQuery to change the src attribute.
Hope that helps!

A: It doesn't make much sense to literally "change" the source before the DOM loads, otherwise why did you set that source to begin with, right?  But as others are saying, Javascript will be executed the moment it comes to the browser, so if you are having the image sources loaded as per any session criteria, etc. etc., you could use the event that when the page is loaded, to perform any particular AJAX requests, e.g. using jQuery:
$(document).ready(function() {
    $.ajax({
        url: '/getPhotos',
        success: function(res) {
            res = JSON.parse(res);
            for (var i in res) {
                $('ul#carousel').append('

');
            }
        }
    });
);

Something like what you are after?


text:
Q: Converting UL to SELECT - grabbing 'data-attr' not working So I'm working on a mobile version of a market selector. Clicking on a continent shows available countries and then clicking on a country shows available languages.
Clicking on a language should then change the href of the button based on the original data-val"http://linkhere.com" that was in the li. - but this for some reason isn't pulling through.
I'm trying to set the value of the option according to what its' original data-val was when it was still an li, but it's not working as you can see from my jsfiddle: http://jsfiddle.net/2GM8v/
How do I pull in that original data-val attr? what I have isn't working (line 68 in the jsfiddle).
EDIT: I've also tried data('val') - and this doesn't pull it through either.
Sorry that my code is such a mess, I'm still learning.
sample code here:
$('section ul', this.$element).hide();

// Create the dropdown base
$("<select />").appendTo(".continents", this.$element);

// Create default option "Go to..."
$("<option />", {
    "selected": "selected",
        "value": "",
        "text": $('.continents span.selected', this.$element).text()
}).appendTo(".continents select", this.$element);

// Populate dropdown with menu items
$(".continents li a", this.$element).each(function () {
    var el = $(this);
    $("<option />", {
        "value": el.attr("href"),
            "text": el.text()
    }).appendTo(".continents select", this.$element);
});

$(".continents select", this.$element).change(function () {

    //get the value of the selected item
    var selectVal = $(this).find("option:selected").val();

    //when the select changes, do this

    $("<select />").appendTo('.countries', this.$element);

    // Create default option "Go to..."
    $("<option />", {
        "selected": "selected",
            "value": "",
            "text": $('.countries span.selected', this.$element).text()
    }).appendTo(".countries select", this.$element);

    // Populate dropdown with menu items
    $(selectVal + " li a", this.$element).each(function () {
        var el = $(this);
        $("<option />", {
            "value": el.attr("href"),
                "text": el.text()
        }).appendTo(".countries select", this.$element);
    });

    $(".countries select", this.$element).change(function () {

        //get the value of the selected item
        var selectVal = $(this).find("option:selected").val();

        //when the select changes, do this

        $("<select />").appendTo('.languages', this.$element);

        // Create default option "Go to..."
        $("<option />", {
            "selected": "selected",
                "value": "",
                "text": $('.languages span.selected', this.$element).text()
        }).appendTo(".languages select", this.$element);

        // Populate dropdown with menu items
        $(selectVal + " li a").each(function () {
            var el = $(this);
            $("<option />", {
                "value": el.attr('data-val'),
                    "text": el.text()
            }).appendTo(".languages select", this.$element);
        });

        $(".languages select", this.$element).change(function () {
            var selectVal = $(this).find("option:selected").val();
            $('#continue', this.$element).removeClass('disabled');
            $('#continue', this.$element).attr('href', selectVal);
        });

    });

});

A: Your el in jsfiddle is the anchor element, and the data attribute is set to the list item.
To read the value of the list item, when anchor is given, do this:
var value = el.closest('li').data('val');


text:
Q: Dependent features configured but no package ID was set. Android two apps of one project.... Admin and User error screen while building superadmin
Hello guys, I wanted to make an android app of admin separate from user app so I decided to make a module for it .SuperAdmin is an application module.I want to make it for only admin and this error is showing while building..... This error is only showing when I am using something from default App module i.e User app .
Is there necessary to make a library between them to communicate with each other?

A: Better way to solve this is by using build variants and product flavors . Read about this here.  You will doing something like this below in build.gradle
android {
    defaultConfig {...}
    buildTypes {
        debug{...}
        release{...}
    }
    // Specifies one flavor dimension.
    flavorDimensions "type"
    productFlavors {
        user {
            dimension "type"
            applicationIdSuffix ".user" //It will be like com.example.app.user . You can remove this applicationIdSuffix property here. So it will build as com.example.app with no suffix
            versionNameSuffix "-demo"
        }
        admin {
            dimension "type"
            applicationIdSuffix ".admin" //It will be building as com.example.app.admin
            versionNameSuffix "-full"
        }
    }
}

In code , you can do conditional logics something like below.
if(BuildConfig.FLAVOR == "user"){
//showUserScreen or hide some button
}else{
//showAdminScreen or show some button
}

In build variants you will be having userDebug, userRelease , adminDebug and adminRelease for two different flavours.


text:
Q: How to intercept the response from REST API in case of 403 http status, in Spring class AuthenticationProvider I have the following problem: I customize the AuthenticationProvider class, provided by spring boot, to call a rest service in order to make the login on remote server.
If the credentials are correct, no problem.
The problem arises when the credentials are incorrect, and the server response http status is 403.
In practice, I can not get the response, because it is automatically raised an exception of API rest:
ResponseEntity <UserResponse> resp = restTemplate.exchange (url, HttpMethod.POST, requestEntity, UserResponse.class);

I tried to create custom class, to catch the exception with
@ControllerAdvice annotation, But it can not be called because the exception does not arise in a controller but in AuthenticationProvider class.
Is there a way to intercept response of a rest API exception?
public class CustomAuthenticationProvider implements AuthenticationProvider {

private static final Logger log = LoggerFactory.getLogger(CustomAuthenticationProvider.class);

@Value("${search.login}")
private String searchLogin;

@Autowired
private HttpServletRequest request;

private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    User user=new User();
    ObjectWriter ow = new ObjectMapper().writer();
    String json="log-> ";
    UserResponse response=new UserResponse();
    try {

                RestTemplate restTemplate = new RestTemplate();
                URI url;
                url = new URI(searchLogin);
                MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
                map.add("username",URLEncoder.encode(authentication.getName(), "utf-8"));
                map.add("password",URLEncoder.encode(authentication.getCredentials().toString(), "utf-8"));
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                List<MediaType> acceptableMediaTypes=new ArrayList<MediaType>();
                acceptableMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
                requestHeaders.setAccept(acceptableMediaTypes);
                HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map,requestHeaders);
                ResponseEntity<UserResponse> resp = restTemplate.exchange(url, HttpMethod.POST, requestEntity, UserResponse.class);
                response = resp.getBody();

Thanks in advance.

A: I'm afraid you will have to handle it from Spring Security as @ControllerAdvice only intercepts exceptions being thrown directly from your controller. I think this link will give you the solution you are looking for.

A: your can  try add @ExceptionHandler in your Rest . just like e.g.
    @ExceptionHandler
    public String exp(HttpServletRequest request, Exception ex) {
//balabala
}


text:
Q: How to calculate distance between time excluding chunks of time efficiently? I'm trying to calculate how many minutes are between two dates while excluding periods of time that are arbitrarily defined and occur weekly. I also need to be able to calculate the reverse, where given a time, calculate X number of minutes forward excluding those time periods.
For example, I may have two periods [Fri 5:31pm - Sat 2:26pm] and [Tuesday 3:37am - Thursday 1:14am] that I don't want to count when figuring out the minutes between two dates and when calculating forward.
I currently have code that does this for only one gap, though it's not super efficient and is becoming a strain on my system. I also need to accommodate multiple defined gaps which I currently do not do.
My code which does this for one gap looks like this (hideStart and hideEnter are the start and end DateTime for the gap, absoluteLowValue is the starting time from which I am calculating the distance or time between):
public int absoluteDistance(DateTime high){
    long totalMinutes = new Duration(absoluteLowValue,high).getStandardMinutes();

    if (!gapHider.isHidingGaps())
        return (int)totalMinutes;

    int minutesPerWeek = 10080;
    long minutesPerHide = new Duration(hideStart, hideEnd).getStandardMinutes();

    long numFullWeeks = totalMinutes/minutesPerWeek;
    long remainder = totalMinutes%minutesPerWeek;

    totalMinutes -= numFullWeeks*minutesPerHide;

    DateTime latestEnd = high;
    if (latestEnd.getDayOfWeek() == hideEnd.getDayOfWeek() && latestEnd.getSecondOfDay() < hideEnd.getSecondOfDay()){
        latestEnd = latestEnd.minusWeeks(1);
    }
    while (latestEnd.getDayOfWeek() != hideEnd.getDayOfWeek())
        latestEnd = latestEnd.minusDays(1);
    latestEnd = latestEnd.withTime(hideEnd.getHourOfDay(),
                                hideEnd.getMinuteOfHour(),
                                hideEnd.getSecondOfMinute(),
                                hideEnd.getMillisOfSecond());

    DateTime latestStart = high;
    if (latestStart.getDayOfWeek() == hideStart.getDayOfWeek() && latestStart.getSecondOfDay() < hideStart.getSecondOfDay()){
        latestStart = latestStart.minusWeeks(1);
    }
    while (latestStart.getDayOfWeek() != hideStart.getDayOfWeek())
        latestStart = latestStart.minusDays(1);
    latestStart = latestStart.withTime(hideStart.getHourOfDay(),
                                    hideStart.getMinuteOfHour(),
                                    hideStart.getSecondOfMinute(),
                                    hideStart.getMillisOfSecond());

    long timeToNearestEnd = new Duration(latestEnd, high).getStandardMinutes();
    long timeToNearestStart = new Duration(latestStart, high).getStandardMinutes();

    if (timeToNearestEnd < remainder){
        totalMinutes -= minutesPerHide;
    }else if (timeToNearestStart < remainder){
        totalMinutes -= new Duration(latestStart, high).getStandardMinutes();
    }

    return (int)totalMinutes;
}

public DateTime timeSinceAbsLow(int index){
    if (absoluteLowValue != null){

        if (!gapHider.isHidingGaps())
            return absoluteLowValue.plusMinutes(index);

        DateTime date = absoluteLowValue;
        long minutesPerWeek = 10080;
        long minutesPerHide = new Duration(hideStart, hideEnd).getStandardMinutes();
        int difference = (int)(minutesPerWeek - minutesPerHide);
        int count = 0;

        while (index - count >= difference){
            date = date.plusWeeks(1);
            count += difference;
        }

        int remaining = index - count;

        DateTime nextStart = date;

        while (nextStart.getDayOfWeek() != hideStart.getDayOfWeek())
            nextStart = nextStart.plusDays(1);
        nextStart = nextStart.withTime(hideStart.getHourOfDay(),
                                    hideStart.getMinuteOfHour(),
                                    hideStart.getSecondOfMinute(),
                                    hideStart.getMillisOfSecond());

        long timeDiff = new Duration(date, nextStart).getStandardMinutes();

        if (timeDiff < remaining){
            date = nextStart.plusMinutes((int)minutesPerHide);
            count+= timeDiff;
            remaining = index - count;
        }

        date = date.plusMinutes(remaining);
        return date;
    }
    return new DateTime();
}

Is there a better or easier way of doing this process? I imagine that if I add in the amount of logic to loop through a list of "gaps" that it will just slow it down even more. I'm open to not using Jodatime, I just happen to be using that currently. Any help appreciated!

A: If I understood correctly, you want to compute the total time between a start and end date, and subtract one ore more periods. So, you could work with Duration objects and then, in the end, convert to whatever you want (minutes, seconds, etc):
// compute all periods you don't want to count
List<Duration> hideList = new ArrayList<>();
// duration between friday and saturday (assuming they have the values of your example)
hideList.add(new Duration(friday, saturday));
// add as many periods you want

// total duration between start and end dates
Duration totalDuration = new Duration(start, end);

// subtract all periods from total
for (Duration duration : hideList) {
    totalDuration = totalDuration.minus(duration);
}

// convert to total number of minutes
long totalMinutes = totalDuration.getStandardMinutes();

I'm assuming that all dates used in hideList are between start and end dates (but it's easy to check this using isAfter and isBefore methods).

To do the opposite, you add the totalMinutes to the start date, and then sum all the durations in hideList:
// sum total minutes to start
DateTime dt = start.plusMinutes((int) totalMinutes);

// sum all the periods
for (Duration duration : hideList) {
    dt = dt.plus(duration);
}
// dt is the end date

There's one detail: when converting the Duration to a number of minutes, you'll lose the seconds and milliseconds precision, so when doing the opposite algorithm, those fields will be lost. If that's not an issue, just do it as above. But if you want to preserve all the precision, just start by adding the totalDuration object instead of adding the number of minutes:
// sum totalDuratin to start (to preserve seconds and milliseconds precision)
DateTime dt = start.plus(totalDuration);


text:
Q: How to fix errors encountered while processing? It all started when I installed an Arc theme for VLC. Afterwards VLC got kind of screwed up so I uninstalled it and tried to install it again. However I've been getting problems using sudo apt-get [anything]. The Terminal keeps telling me to use sudo apt-get install -f but all I get is an error.

A: First, you could/should have copied the text, pasted it into your question, and Formatted with the {} button just left of the image button.
Second, it looks like it's complaining about /etc/python2.7/sitecuston.py. You should move this file to some other directory, do the sudo apt-get install -f, then compare and merge the saved copy with the installed copy.
Read the error messages slowly and carefully - programmers try very hard to make them helpful.


text:
Q: Rename W3 Total Cache admin menu I'm developing a plugin that I'll install for all my clients to make WordPress slightly easier to use for them. One of the things it will change is name of the W3 Total Cache Admin menu from "Performance" to "Ytelse (avansert)".
I know how to rename the default admin menus. The code below changes "Posts" to "Nyheter"(News in Norwegian).
function change_post_menu_label_news() {
global $menu;
$menu[5][0] = 'Nyheter';
echo '';
}

add_action( 'admin_menu', 'change_post_menu_label_news' );

I find the ID to change by temporarily using this code:
add_action('admin_init','dump_admin_menu');
function dump_admin_menu() {
 if (is_admin()) {
header('Content-Type:text/plain');
var_dump($GLOBALS['menu']);
exit;
}
}

However, it's harder to rename the Performance menu since the ID increments by one when I try to rename it!. W3 Total Cache probably thinks that the ID is taken and tries a higher one.
How can I change the name of the W3 Total Cache admin Menu while avoiding this issue and without editing anything related to the plugin?

A: You may be able to use the WordPress filter 'gettext':
http://codex.wordpress.org/Plugin_API/Filter_Reference/gettext
add_filter( 'gettext', 'rename_menu_item' );
function rename_menu_item( $translated )
{
    $translated = str_replace( 'Performance', 'Ytelse', $translated );
    return $translated;
}

A: jQuery is your friend.
jQuery(document).ready(function() {
jQuery('a.toplevel_page_w3tc_general').text('Ytelse (avansert)');
});

Working example: http://jsfiddle.net/c3mdigital/Lq7UX/4/

A: I used your code to locate W3 Total Cache in the $menu array (in my case it was 102), I then copy / pasted your code to change the label, and these were the results:

I realize I got the wrong label here, but this otherwise appears to be correct, menu works as expected.


text:
Q: VM Resolution can't go over 640x480, even after guest additions were installed This is on VirtualBox, guest is Xubuntu 32bits 14.04, host is Windows 8.1 64bits
I should point my hardware does not allow x86 virtualization, hence why VirtualBox only allowed a 32bits VM to be installed.
Side note : It's an AMD FX 6300, although in the specifications it says virtualization supported, my BIOS says otherwise.

A: When your VM is shut down, change the available video memory to something higher.  (I use 128 MB - the max allowed)

A: I've had a similar issue with Bodhi Linux. Something in the installer for vboxedition fails. You can temporarily work around the problem but running
vboxuser

If that corrects the issue, then you need to set the system to run vboxuser on start up. You can do this by adding the command to the /etc/rc.local file.


text:
Q: Avoid having to map hundreds or thousands of hostnames to an Azure Web Site I have a need to have hundreds or even thousands of hostnames point at a single Azure Web Site.  For a simple rationale, you could think of this as a vanity/branding redirection site.  For example:

*

*Visiting http://marketing.example.com would get you redirected to say https://example.sharepoint.com/sites/themarketingteam

*Visiting http://finance.example.com would get you redirected to say http://someinternalservce.example.com/reports/finance

*Visiting http://hr.example.com/ would get you redirected to say https://saponline.net/examplecorp

I know I can have a *.example.com DNS entry mapped to my azure web application but that isn't attractive because the domain only gets one of those and trying to convince the powers to be that this relatively simple/silly needs is how they use the wild card entry.
Likewise, I know I can go into the Azure portal and/or use Powershell to manually add entries to the configuration but that seems like a lot of extra work and requires the people managing the redirect mappings to have a lot more control over the Azure settings for the web application.

Is there any clever workarounds to this solution? Is there a tier of service that gets my app my own IP address that lets me do DNS aliases for? Is there some other Azure offering that might do url rewriting/forwarding to my app that doesn't have the above limitations?

A: Per my understanding, you could leverage IIS URL Rewrite and Using rewrite maps for redirection for configuring the following code into the system.webServer section of web.config file for your website as follows:
<rewrite>
  <rewriteMaps>
    <rewriteMap name="hostRedirects">
      <add key="marketing.example.com" value="https://example.sharepoint.com/sites/themarketingteam"/>
      <add key="finance.example.com" value="http://someinternalservce.example.com/reports/finance"/>
    </rewriteMap>
  </rewriteMaps>

  <rules>
    <rule name="Redirect rule" stopProcessing="true">
      <match url=".*"/>
      <conditions>
        <add input="{hostRedirects:{HTTP_HOST}}" pattern="(.+)"/>
      </conditions>
      <action type="Redirect" url="{C:1}" appendQueryString="true" redirectType="Permanent"/>
    </rule>
  </rules>
</rewrite>

Also, you could use DbProvider, FileMapProvider, etc for storing the URL mappings into the db or file. I would recommend you using the FileMapProvider which could store the rewrite map entries in a single file instead of keeping them in a web.config file. For more details, you could refer to Using Custom Rewrite Providers with URL Rewrite Module.
Additionally, you could write your code and build a custom HttpMoudle to check the incoming host, then redirect as you wish. Here is a blog talking about the detailed steps, you could refer to here.


text:
Q: MyBatis with postgres throws "ERROR: relation "dual" does not exist" I am using MyBatis to do a very simple select in a postgres database in a java web based application
Setup is as follows:
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.2</version>
    </dependency>

And the the following driver:
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.2-1004-jdbc41</version>
    </dependency>

The mapper looks as follows:
<select id="getLicenseUsage"  parameterType="long"  resultMap="licenseUsage">
    select ('1970-01-01 00:00:00 GMT'::timestamp + (event_time/1000)::text::interval)::date as day, license_key, count(distinct event_id) as recos, max(id) as venm_id
    from venm_raw
    where target_id is not null and id > #{fromId}
    group by license_key,day;
</select>

When i execute this query i get the following error:
"ERROR: relation "dual" does not exist"

From the different readings over the net, it seems that MyBatis is looking behind the scenes for a table named "dual" which exists in Oracle but not in postgres. This is just a guess at this point.
I am stuck here, help s much appreciated. Thx in advance.
Full trace below:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ERROR: relation "dual" does not exist)
### The error may exist in file [/opt/tomcat/webapps/ROOT/WEB-INF/classes/META-INF/mappers/redshift/LicenseUsageMapper.xml]
### The error may involve com.qualcomm.vuforia.redshift.mappers.LicenseUsageMapper.getLicenseUsage
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ERROR: relation "dual" does not exist)
        at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
        at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371)
        at com.sun.proxy.$Proxy36.selectList(Unknown Source)
        at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198)
        at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:114)
        at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:58)
        at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:43)
        at com.sun.proxy.$Proxy49.getLicenseUsage(Unknown Source)
        at com.qualcomm.vuforia.sumtables.summarizers.SummarizerProcessor.process(SummarizerProcessor.java:60)
        at org.apache.camel.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:63)

A: Looking at the stack trace of the error I can say that apache database connection pool is used. And it looks like it has validationQuery configured to something like SELECT 1 FROM dual. mybatis itself does not use dbcp and has its own implementation for pooled datasource so this dbcp is something that is configured in your project.
As you were able to figure out dual does not exist in postgres so you need to change that query to SELECT 1. There are many ways to use dbcp so you need to find how it is used and configured in your project.
You are using spring so most probably you have BasicDataSource configured in spring context with validationQuery set.
The other way is to do a full text search for dual in your project.

A: Based on your response that you don't have any config setup, I suspect that that may be the crux of the issue here.
Check out the Getting Started Guide for an overview, and the config section for more details.
The example config they listed in the Getting Started tutorial is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

Which in turn hooks into a properties file to set the environment variables such as ${driver} et al.
In particular, you would likely want to focus on these settings:
<property name="driver" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/db"/>

Where localhost changes to your host name, and db is the name of your database. 5432 is generally the default port with Postgres, but if your port is non-standard, you'll want to change that as well.


text:
Q: Thymeleaf does not recognize Kotlin Extension Functions defined in SpringBoot How can i use Kotlin extension function in a Thymeleaf template ?
For example, let's take a simple case

    <div th:text="${mystring.test()}">placeholder</div>

where test() is an extension function for String class defined in a Spring Boot kotlin file as

    fun String.test(): String = this

With this code I obtain a SpelEvaluationException
    org.springframework.expression.spel.SpelEvaluationException:
EL1004E: Method call: Method test() cannot be found on type java.lang.String

org.springframework.boot:spring-boot-starter-thymeleaf version is 2.1.1.RELEASE
Thank you


text:
Q: how to handle spring wrapped hibernate exception? spring template will wrap hibernate exceptions into DataAccessExceptions.  so trying to directly capture hibernate exceptions won't work. like this
try{
    springdao.update(row)
}
catch(HibernateException e) {
    //won't do
}

questions:

*

*what's the best practice to capture DataAccessException wrapped hibernate exception ? just catch(DataAccessException) ?

*even though spring has wrapped that exception, when it is thrown. it exhibits as just original hibernate exception. like below, why ?

Could not synchronize database state with session
  org.hibernate.StaleObjectStateException: Row was updated or deleted by
  another transaction (or unsaved-value mapping was incorrect):

A: I think its better to handle DataAccessException instead of HibernateException or SQLException. Because it describes the issue in more generalized way. In case if you change your ORM/ Database later, it will handle your database related exception handling in same manner. And also it contains the same exception as that of Hibernate. Even in case of Non-SQL databases, same exception is thrown
Spring documentation says:

This exception hierarchy aims to let user code find and handle the
  kind of error encountered without knowing the details of the
  particular data access API in use (e.g. JDBC). Thus it is possible to
  react to an optimistic locking failure without knowing that JDBC is
  being used.