text:
Q: WordPress REST API Authentication Using Fetch I'm attempting to use cookie authentication for WordPress REST API access using the Fetch API, however the auth is failing with the following error.

403: Cookie Nonce is Invalid

I'm using the following script to connect to the API.
const headers = new Headers({
   'Content-Type': 'application/json',
   'X-WP-Nonce': WPAPI.nonce
});

fetch(WPAPI.root + 'my-endpoint/upload/', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
})

When I switch from using Fetch to XMLHttpRequest it works as expected.
let request = new XMLHttpRequest();
request.open('POST', WPAPI.root + 'my-endpoint/upload/', true);
request.setRequestHeader('X-WP-Nonce', WPAPI.nonce);
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));

Is it possible there an issue with the way headers are being sent in the Fetch method?

A: WordPress nonce authentication requires the use of cookies and by default Fetch doesn't send those along. You can use the credentials option to make this work:
fetch(endpoint, {
  credentials: 'same-origin'
})

https://github.com/github/fetch#sending-cookies

A: Came across my post from 4 years ago looking for the same issue :)
This solves the problem.
const response = await fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce' : my_var.nonce
    },
    body: JSON.stringify(data),
});
const content = await response.json();
console.log(content);

A: Late, but maybe helpful for other readers as I added code specifically for fetch() promise according to this question.
WordPress uses nonce automatically within their cookies, as I found out.
Solution: Permission Callback function checking for cookie
WordPress: version 5.7.2
PHP: version 7.4
host: hostmonster.com
client: Windows 10
browsers: tested on Chrome, Firefox, even Edge  worked
Code (PHP code in function.php of your installed theme):
add_action('rest_api_init', function() {
    /**
     * Register here your custom routes for your CRUD functions
     */
    register_rest_route( 'my-endpoint/v1', '/upload/', array(
        array(
            'methods'  => WP_REST_Server::READABLE, // = 'GET'
            'callback' => 'get_data',
            // Always allow, as an example
            'permission_callback' => '__return_true'
        ),
        array(
            'methods'  => WP_REST_Server::CREATABLE, // = 'POST'
            'callback' => 'create_data',
            // Here we register our permissions callback
            // The callback is fired before the main callback to check if the current user can access the endpoint
            'permission_callback' => 'prefix_get_private_data_permissions_check',
        ),
    ));
});

// The missing part:
// Add your Permission Callback function here, that checks for the cookie
// You should define your own 'prefix_' name, though

function prefix_get_private_data_permissions_check() {

    // Option 1: Password Protected post or page:
    // Restrict endpoint to browsers that have the wp-postpass_ cookie.
    if ( !isset($_COOKIE['wp-postpass_'. COOKIEHASH] )) {
        return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not create or edit private data.', 'my-text-domain' ), array( 'status' => 401 ) );
    };

    // Option 2: Authentication based on logged-in user:
    // Restrict endpoint to only users who have the edit_posts capability.
    if ( ! current_user_can( 'edit_posts' ) ) {
        return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not create or edit private data.', 'my-text-domain' ), array( 'status' => 401 ) );
    };

    // This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check.
    return true;
};

function create_data() {
    global $wpdb;

    $result = $wpdb->query(...);

    return $result;
}

function get_data() {
    global $wpdb;

    $data = $wpdb->get_results('SELECT * from `data`');

    return $data;
}

Make sure to include in your HTML page credentials: 'same-origin' in your HTTP request, as stated correctly in previous answers and comments above.
Code (HTML with inline <script> ... </script>):
<script>

// Here comes the REST API part:
// HTTP requests with fetch() promises

function getYourData() {
  let url = 'https://example.com/wp-json/my-endpoint/v1/upload/';
  fetch(url, {
    method: 'GET',
    credentials: 'same-origin', // <-- make sure to include credentials
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        //'Authorization': 'Bearer ' + token  <-- not needed, WP does not check for it
    }
  }).then(res => res.json())
  .then(response => get_success(response))
  .catch(error => failure(error));
};

function insertYourData(data) {
  let url = 'https://example.com/wp-json/my-endpoint/v1/upload/';
  fetch(url, {
    method: 'POST',
    credentials: 'same-origin', // <-- make sure to include credentials
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        //'Authorization': 'Bearer ' + token  <-- not needed, WP does not check for it
    },
    body: JSON.stringify(data)
  }).then(res => res.json())
  .then(response => create_success(response))
  .catch(error => failure(error));
};

// your Success and Failure-functions:

function get_success(json) {
  // do something here with your returned data ....
  console.log(json);
};

function create_success(json) {
  // do something here with your returned data ....
  console.log(json);
};

function failure(error) {
  // do something here ....
  console.log("Error: " + error);
};

</script>

Final thoughts:
Is 'Authorization': 'Bearer ' + token necessary in header of HTTP request?
After some testing, I realized that if ( !isset($_COOKIE['wp-postpass_'. COOKIEHASH] )) { ... within the Permission Callback not only checks if the Cookie is set on client browser, but it seems also to check its value (the JWT token).
Because I dobble checked as with my initial code, passing a false token, eliminating the cookie, or leaving session open but changing in the back-end the password of site (hence WordPress would create a new token, hence value of set wp_postpass_ cookie would change) and all test went correctly - REST API blocked, not only verifying presence of cookie, but also its value (which is good - thank you WordPress team).
Sources:
I found following resource concerning above thoughts in the FAQ section:
Why is the REST API not verifying the incoming Origin header? Does this expose my site to CSRF attacks?

Because the WordPress REST API does not verify the Origin header of
incoming requests, public REST API endpoints may therefore be accessed
from any site. This is an intentional design decision.
However, WordPress has an existing CSRF protection mechanism which
uses nonces.

And according to my testing so far, the WP-way of authentication works perfectly well.
Thumbs up  for the WordPress team
Additional 2 sources from the WordPress REST API Handbook:
REST API Handbook / Extending the REST API / Routes and Endpoints
REST API Handbook / Extending the REST API / Adding Custom Endpoints
And 1 source form WordPress Code Reference concerning rest_cookie_check_errors() function:
Reference / Functions / rest_cookie_check_errors()
For those interested in full story of my findings, following link to my thread with answers, code snippets and additional findings.
How to force Authentication on REST API for Password protected page using custom table and fetch() without Plugin


text:
Q: Not able to Create HANA Stored Procedure in Repository of Development Perspective I have been trying to create Stored Procedure in the repository section of HANA Development perspective.
Even though I can see my schema in repository, I dont see the create procedure option.
Can you please help me here.
Am I missing any authorization?
Any other way to create(Path)
Version using - HANA 1.0 SPS 12
Thanks in Advance.

A: If I am not mistaken you cannot create HANA database procedure from HANA Development Perspective. There you will be able to create DB procedure proxy object. And for that you have to create database procedure before.
You can create HANA database procedure on the Repositories tab under a package.
Then you will be able call it using CALL statement
Or you can create database procedure directly on the database using SQLScript
Please check the referred samples, I hope they help for a solution

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu 20.04 сетевая карта rtl8821ce Проблема в том, что у меня сначала не хотел вставать модуль сетевой карты, и выдавал ошибку:
Чтение списков пакетов… Готово
Построение дерева зависимостей
Чтение информации о состоянии… Готово
Следующие НОВЫЕ пакеты будут установлены:
  rtl8821ce-dkms
Обновлено 0 пакетов, установлено 1 новых пакетов, для удаления отмечено 0 пакетов, и 22 пакетов не обновлено.
Необходимо скачать 0 B/2 197 kB архивов.
После данной операции объём занятого дискового пространства возрастёт на 25,2 MB.
Выбор ранее не выбранного пакета rtl8821ce-dkms.
(Чтение базы данных … на данный момент установлено 181324 файла и каталога.)
Подготовка к распаковке …/rtl8821ce-dkms_5.5.2.1-0ubuntu4~20.04.4_all.deb …
Распаковывается rtl8821ce-dkms (5.5.2.1-0ubuntu4~20.04.4) …
Настраивается пакет rtl8821ce-dkms (5.5.2.1-0ubuntu4~20.04.4) …
Loading new rtl8821ce-5.5.2.1 DKMS files...
Building for 5.15.0-11.1-liquorix-amd64
Building initial module for 5.15.0-11.1-liquorix-amd64
ERROR (dkms apport): kernel package linux-headers-5.15.0-11.1-liquorix-amd64 is
not supported
Error! Bad return status for module build on kernel: 5.15.0-11.1-liquorix-amd64
(x86_64)
Consult /var/lib/dkms/rtl8821ce/5.5.2.1/build/make.log for more information.
dpkg: ошибка при обработке пакета rtl8821ce-dkms (--configure):
 installed rtl8821ce-dkms package post-installation script subprocess returned e
rror exit status 10
При обработке следующих пакетов произошли ошибки:
 rtl8821ce-dkms
E: Sub-process /usr/bin/dpkg returned an error code (1)

Потом я удалил все ядра liquorix, на которые он ругался и перешёл на ядро - 5.11.0-40-generic. Проблема исчезла минут на 20 и после этого опять началась. То есть к wifi комп подключается, но вместо значка wifi отображается вопрос, и интернет при этом не работает. Также и когда я раздаю интернет с телефона. Я пробовал переустанавливать драйвер, переключать антенну, убирал проверку подключения, но ничего не помогает. Можно ли решить эту проблему? (если нужны какие то выхлопы, то все скину)

A: Все оказалось очень просто - поменял dns сервера на google: 8.8.8.8, 8.8.4.4. И теперь уже наконец-то все работает идеально.


text:
Q: My brightness Control is not working (amd) I actually have tried many ways to correct this
Perhaps I was able to correct it adding a
acpi_osi=Linux acpi_backlight=vendor

in the grub configuration file( in GRUB_CMDLINE_LINUX_DEFAULT="quiet splash")
But after a day when i star my laptop another problem occured
Guess what!! blank screen
then i have to add nomodeset in grub in grub page.
Then i see that all brightness control has lost(Empty folder in sys/class/backlight).....!!
What i am supposed to do?
can u suggest some proprietary driver... For and graphic card
My laptop is Asus VivoBook Ryzen 5 Quad Core having acpi_video

A: Guys I actually solved the problem by installing amdgpu_pro released for ubuntu 20.04.
Also it solved my blank screen problem after grub page .


text:
Q: IOS/Objective-C: Set NSItemProvider How would I render the following in Swift into Objective-C?
let vCardActivity = NSItemProvider(item: vCardData, typeIdentifier: kUTTypeVCard as String)

Can't find this in documentation.

A: My Objective-C is starting to get rusty, and I've never used an NSItemProvider before, but it should be something like:
NSItemProvider* vCardActivity =
  [[NSItemProvider alloc] initWithItem: vCardData
  typeIdentifier: (NSString *) kUTTypeVCard];


text:
Q: non-linear bootstrap slider with negative numbers I've been searching for a solution for my slider to present non-linear numbers and came across this solution:
JQuery UI Slider with Non-linear/Exponential/Logarithmic steps
HTML:
<input type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="[0,100]" id="sl2" style="width:60%">

JS:
function commafy(val) {
    var toPresent = 0;
    if (val < 10) {
        toPresent = (val / 10) * 1;
    } else if (val <= 80) {
        toPresent = 1+ (val - 10) / 70 * 20;
    } else {
        toPresent = 1+20 + (val - 80) / 20 * 500;
    };
    return toPresent;
}

        $("#sl2").slider({
            reversed : true,
            tooltip_split: true,
            formatter: function(value) {
                return parseFloat(commafy(value)).toFixed(2);
            },
        });

JSfiddle: https://jsfiddle.net/hw1aer2f/1/
The Comaffy function basically makes the slider non-linear. So first 10% of the slider is 0-1. 10% to 80% is 1 to 20 and 80% to 100% is 20 to 500. But these are all positive numbers, and when I try to make the first 10% from -100 to 0, the function basically stops working.

A: I've created a function which I think can provide a generic solution. You can try that here.
// currentValue: the actual value of the slider
// min: minimum value on the slider (0)
// max: maximum value on the slider (10)
// scaleMin: desired range minimum value (-100)
// scaleMax: desired range maximum value (0)
function calc(currentValue, min, max, scaleMin, scaleMax) {
  return scaleMin + currentValue * (scaleMax - scaleMin) / (max - min);
}


text:
Q: increment of a class attribute everytime an object is created I would like to know how to increase/increment an attribute of a class.
I have a class called Account which has an attribute: self.code which is initialized at 0 and I want each time that an object is created the attribute increases.
so, for example:
account1=Account()
account2=Account()
account3=Account()

if I do account3.code I want to have 3 as a result.
Is there a possible way to do so? thank you in advance.

A: You can define a static variable for the Account object and increment it everytime you create a new object like this:
class Account:
    code = 0
    id = 0
    def __init__(self):
        self.id = Account.code
        Account.code += 1

a = Account()
print(a.id) # 0
b = Account()
print(b.id) # 1
c = Account()
print(c.id) # 2

The code variable defines how many instances were created. Every account has an id

A: you can do it like this:
class Example:
    code = 0

    def __new__(cls, *args, **kwargs):
        cls.code += 1
        return super().__new__(Example, *args, **kwargs)

ex1 = Example()
print(ex1.code) # 1
ex2 = Example()
print(ex2.code) # 2
ex3 = Example()
print(ex3.code) # 3

using __new__ is more general than __init__ in the other answers since you can create an object without calling __init__.

A: If you also want each Account instance to store the code at which it was created you can use it like this
class Account:
    last_code = 0
    def __init__(self) -> None:
        self.code = Account.last_code + 1
        Account.last_code = self.code

a = Account()
b = Account()
c = Account()

print(a.code) # 1
print(b.code) # 2
print(c.code) # 3

A: Try to use a class attribute. Example:
class Account:

    number_of_accounts = 0  # class attribute, not initialised for every instance

    def __init__(self):
        # whatever init code
        Account.number_of_accounts += 1

account_1 = Account()
account_2 = Account()
account_3 = Account()

print(Account.number_of_accounts)

A: What about a sequence stored as static class variable.
Then with creation of each instance, the next value is drawn from that sequence.
import itertools

class Account:

    id_iter = itertools.count()  # sequence counter (usually used for IDs)

    def __init__(self):
        self.code = next(Account.id_iter)

See also:

*

*How do you create an incremental ID in a Python Class


text:
Q: p:ajax update not working after clicking commandlink I have a jsf page that adds an order from a client.
All works fine except when I click the commandLink to show the p:dialog to add a new client the update on the "reste" inputtext stop working (even if I close the p:dialog without adding the new client) :
Clients List :
Client :<

Link to a p:dialog to add a new Cleint :

Three p:inputtext items with ajax behavior :
Montant :

Avance :

Reste :

The venteSolaireBean.calcul function to execute with the listener :
public void calcul() {
    venteSolaire.setReste(venteSolaire.getMontant() - venteSolaire.getAvance());
}

I checked by logging the calcul() function and I'm sure it was invoked and the value giving to setReste() is correct.
I don't see why inputtext didn't update.
please help.

A: I think that there are some problems with the validation. As immediate=true often leads to such problems and you are not using any primefaces-functionality on the button to show the dialog, you should replace the p:commandButton with a plain HTML button to show the "add client"-dialog.


text:
Q: How can I invoke the post-build script without a build! does anyone know how I can have the post build action execute without doing a build?
There are loads of xcopy commands and it would be nice to use them on their own... but you cannot put them into a separate cmd file because of all the VS macros.
thanks
Kris

A: What you could do is put them into a separate, empty project that is not included in the final solution (however built at the same time). Then you can just right click the project and select build and the action will execute

A: Right-click on your project in the Solution Explorer window and select "Tool Build Order", uncheck everything except the Post-Build Event Tool, then build the project.
Don't forget to re-enable everything after you're done, or you'll be wondering why nothing's compiling.. :)


text:
Q: What does "||" refer to in JavaScript apart from Or? I was recently going through some JavaScript code (written by someone else) and it had something like this:
var exports = exports || null;

What does this mean? Is this the equivalent of:
var exports = exports ? exports : null;

A:
What does "||" refer to in JavaScript apart from Or?

Nothing, but its definition of "or" is not the same as some other languages.
The ||operator evaluates its left-hand operand and if that result is truthy, that's the result of the operation; otherwise, the right-hand operand is evaluated and that result is the result of the operation.
So it doesn't necessarily result in a boolean value. In your example, exports || null will be the value of exports if it's truthy, or null if it isn't.


text:
Q: Moveuploaded files function in PHP moves the file to the temp directory but not to the destination directory  $tmpName = basename($_FILES['uploadfile']['tmp_name']);
 $rightname = basename($_FILES['uploadfile']['name']);
 move_uploaded_file($_FILES['uploadfile']['tmp_name'], $workDir."/".$tmpName) or  die("Cannot move uploaded file to working directory");
 if(!is_writable($_POST['filetype']))
    die('You cannot upload to the specified directory, please CHMOD it to 777.');
 move_uploaded_file($_FILES['uploadfile']['tmp_name'], $_POST['filetype'].'/'.$rightname)    or die("Cannot move uploaded file to destination directory");

I have a form that uploads a file and posts data to a php script that contains the above code. The above code works partially, as in, the first 'move_uploaded_file' works and the uploaded file gets moved from the var/tmp folder to the $workDir folder. The file has the same name as the one given by the server when it places the uploaded file on the tmp folder with a temporary name before moving it to the destination directory. I feel this works because I am not renaming the temporary name given to the file by server, when it places the file in the tmp folder, after I submit the form. Because the second 'move_uploaded_file()' dies with the error specified. The directory is writable. It is chmoded into '777'. No issues with that. And this is where I am changing the name of the file to what it needs to be. Seems to be a minor issue but I have spent too much time on this without luck.

A: First time you called move_uploaded_file() you moved that file from temporary folder to $workDir. After that, uploaded file no longer exists in temporary directory.
Just use rename() function to move that file from $workDir."/".$tmpName to final destination.
// moves file from workdir to final destination
rename($workDir."/".$tmpName, $_POST['filetype'].'/'.$rightname);


text:
Q: Why is this code generating a scala match exception I'm trying to compare two parallel arrays of strings together.  Each array is guaranteed to be the same length.  Corresponding strings in each array may be indented differently, so I perform a trim when comparing them.  I've written the following function to do the comparison, and I'm getting a match error when I run the code:
def compare(expected: Seq[String], actual: Seq[String]): Boolean = (expected, actual) match {
    case (Nil, _) => true
    case (a :: _, b :: _) if (a.trim != b.trim) => false
    case (_ :: a, _ :: b) => compare(a, b)
}

What am I missing here?  As far as I can tell this should cover all cases.
The actual exception:
 scala.MatchError: (WrappedArray(ExpectedString), WrappedArray(ActualString)) (of class scala.Tuple2)


text:
Q: Is there any workaround to specify sender's email address for automatic email sending upon form submission? I have a script which is working for automatic email sending upon form submission.
User submit form > Email send out to specified email address from my own email that I used to setup the script.
Is there any workaround to have the email sender to specify to be the form submitter?
I look at the MailApp class specification. The best I could find is specifying a noreply as 'true'. https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
I want to tweak for my script to play a role as invisible middle man to send the email on form submitter's behalf, and also to discourage replies to the email that I used to setup the script.
Thanks

A: It is possible if the submitter is from your domain

*

*In this case, you can use a service account with domain-wide impersonation that allows to run the script on behalf of the specified user.

*Thereby, the user can be anyone in your domain and the impersonated user can be implemented dynamically into the code

*This is a library that allows you to implement the authentication with a service account in Apps Script

*If the suers are not in your domain, they cannot be impersonated by the service account, however, you can still send the emails on behalf of a dummy user on your domain, rather than from your primary email.

See here for a sample on how to sue a service account with impersonation in Apps Script.

A: I found a workaround to send with another group alias email. Instead of using MailApp class, I combine the usage of GmailApp class.
Prerequisite: adding group alias email as 'Send as' in your Gmail. How-to here
After adding the send as alias, use GmailApp.sendEmail with the option to indicate from. Step:
I'm skipping the steps of form submitting, triggers and retrieving values as this question is not about how-to do those. The steps below assumed all the steps done until retrieved email body to prepare for the email sending

*

*add group alias email as 'Send as' in your Gmail (see prerequisite above).

*test whether you can send an email in a particular group account email. (huge credit to this post). Code:

    var aliases = GmailApp.getAliases();
    var num = aliases.length-1;
    if (num<0){
        return false
      }else{
        for (var i = 0;i <= num;i++){
          if (aliases[i] == "yourGroup@Domain.com"){
            var myGroupMail=aliases[i];
            break;
          }
        }
      }
      if (myGroupMail != "yourGroup@Domain.com"){return false}

*retrieve email html body if you want to send in html. For example, you can retrieve a template from a google doc with DocumentApp.openByUrl and getId() and convert doc to HTML via code:

function docToHtml(docId) {

  // Downloads a Google Doc as an HTML string.
  var url = "{{insert your doc url}}" +
            docId + "&exportFormat=html";
  var param = {
    method: "get",
    headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  return UrlFetchApp.fetch(url, param).getContentText();
}

*Finally send your email :)

sendEmail(recipient, EMAIL_SUBJECT, '', {
    cc: email,
    htmlBody: {{insert your create Email Body Function or use the doctohtml code above}},
    from: myGroupMail
  }


text:
Q: Jquery ajax on IE11 I have some problem here. I use JQuery Ajax to send request to my back end server and it will return some clue to notice if the request successfully proceed or not.
I had try to do it in IE8 and IE7, the Jquery Ajax works well, but when i try it on IE11, it will be error for few times, and then work well after that.
My question is, how to make it run well on IE11 without have to wait few times?
This is my Jquery Ajax script
    var value = $("#record"+index).attr('value');
    var hiddenAmount = Number ($("#hiddenTotalAmount").val());
    var values=value.split('/');
    var uncheckedAmount = Number(values[1]);
    var realAmount = 0;
    var realRecord = Number ($("#totalRecord").val());
    var checkedDoc = $("#record"+index).val();
    var dataString = "action=validateDocNum&holdDocNum="+checkedDoc;
    if($("#record"+index).attr('checked')){

        $.ajax({
            type: "POST",
            url: "executeSp2d.do",

            data: dataString+"&act=check",
            cache: false,

            success : function(msg) {
            console.log(msg);
            console.log(msg.result);
            msg.result=$.trim(msg.result);
            if(msg.result=="1"){
                /* $("#uncheckRecord").dialog('close'); */
                realAmount = hiddenAmount + uncheckedAmount;
                realRecord = realRecord + 1;
                $("#totalRecord").val(realRecord);
                $("#hiddenTotalAmount").val(realAmount);
                realAmount = accounting.formatMoney(realAmount, "", 2, ".", ",");
                $("#totalAmount").val(realAmount);
            }else{
                alert('Fail to uncheck records');
                $("#record"+index).attr('checked', false);

            }
            },

            error: function() {
                alert('Fail to check records');
                $("#record"+index).attr('checked', false);
              }

        });

    }else{

        $.ajax({
            type: "POST",
            url: "executeSp2d.do",
            data: dataString+"&act=uncheck",
            cache: false,

            success : function(msg){
            console.log(msg);
            console.log(msg.result);
            msg.result=$.trim(msg.result);
            if(msg.result=="1"){
                realAmount = hiddenAmount - uncheckedAmount;
                realRecord = realRecord - 1;
                $("#totalRecord").val(realRecord);
                $("#hiddenTotalAmount").val(realAmount);
                realAmount = accounting.formatMoney(realAmount, "", 2, ".", ",");
                $("#totalAmount").val(realAmount);
            }else{
                alert('Fail to uncheck records');
                $("#record"+index).attr('checked', true);

            }
            },

            error: function() {
                alert('Fail to uncheck records');

               $("#record"+index).attr('checked', true);
              }
        });
    }


text:
Q: spark-submit: java.lang.NoSuchMethodError: org.apache.spark.SparkContext$.$lessinit$greater$default$6()Lscala/collection/Map; I'm running a simple scala example on spark. On this line:
val sc = new SparkContext("spark://login.hpc-lan.recolic.org:7077", "Recolic+Hust BigData Lab")

Spark throws:
root@ip-172-31-46-127 ~/h/hust-bigdata-lab# spark-submit --master spark://login.hpc-lan.recolic.org:7077 --class net.recolic.hust.bigdata.labx.Main  target/hust-bigdata-labx.jar
19/11/07 07:37:39 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.spark.SparkContext$.$lessinit$greater$default$6()Lscala/collection/Map;
    at net.recolic.hust.bigdata.labx.Main$.main(Main.scala:10)
    at net.recolic.hust.bigdata.labx.Main.main(Main.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
    at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:845)
    at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:161)
    at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:184)
    at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:86)
    at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:920)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:929)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

My pom.xml is pasted here. I tried to downgrade to scala 1.10, tried to build a fat jar including all dependencies, tried to use sbt, but none of them solves the problem.
Could you give any suggestions?
-- UPDATE
My spark is 2.4.4 with scala 2.11.12. So I modified pom.xml to use spark sdk 2.4.4. However, still the same error.


text:
Q: "Select ... into .." statement fails with "table or view does not exist" even though it should not be run I have the following PL/SQL script that I'm trying to run through SQL*Plus:
DECLARE
   table_exists number;
   sequence_exists number;
   sequence_start number;
BEGIN
   select count(*) into sequence_exists
       from all_sequences
       where sequence_name='DBSEQ';
   select count(*) into table_exists
       from dba_tables
       where table_name='DBTABLE';
   IF sequence_exists = 0 AND table_exists > 0 THEN
       select MAX(ID) + 1 into sequence_start from DBTABLE;
   ELSE
       sequence_start := 1;
   END;
   IF sequence_exists = 0 THEN
       execute immediate 'CREATE SEQUENCE DBSEQ
             start with ' || sequence_start || '
             increment by 1
             nomaxvalue';
   END IF;
END;

(this is somewhat minimized, to show the parts that are actually failing).
The problem is that the row
select MAX(ID) + 1 into sequence_start from DBTABLE;

fails with "PL/SQL: ORA-00942: table or view does not exist", because the table does not exist (and I've already verified that the table_exists variable is actually 0). So basically, the select runs (or at least fails) even though the if-clause does not execute. I've also verified that the if-clause indeed fails by replacing the select with e.g. creating a table, which does not exist after running the script.
I did also try catching exceptions instead, doing something like this:
BEGIN
    select MAX(ID) + 1 into sequence_start from DBTABLE;
EXCEPTION
    WHEN OTHERS THEN
        sequence_start := 1;
END;

but that produced the same error.
So, is there anything special with the select statement, that makes it run before anything else? And how should I solve my problem?

A: The problem is that Oracle has to compile the block before it can run it.  Part of compiling the block involves resolving all the static references.  If you have a reference to a table that does not exist, the block will fail to compile so it cannot be run.  Your exception handler doesn't do anything because it is a compilation error, not an execution error.
If you want your block to refer to a table that may not exist at the time the block is compiled, you would need to use dynamic SQL.
EXECUTE IMMEDIATE 'select max(id) from dbtable'
   INTO sequence_start;

That will allow the block to compile successfully since Oracle doesn't need to resolve references in dynamic SQL statements.  If your code tries to execute the dynamic SQL statement when dbtable doesn't exist, you'll get a run-time error (which you could catch with an exception handler).


text:
Q: How to change a DropDownList's BackGround colour In FLEX? This is what I've done so far.
       <!-- fill -->
        <!--- Defines the appearance of drop-down list's background fill. -->
        <s:Rect id="background" left="1" right="1" top="1" bottom="1" >
            <s:fill>
            <!---
                The color of the drop down's background fill.
                The default color is 0xFFFFFF.
            -->
                <s:SolidColor id="bgFill" color="#DB9E36"/>
            </s:fill>
        </s:Rect>

If you look closely you'll see that I've changed the default value for the bgFill color. However, when I run my application, the background color for the dropdownlist is still the default white.
Am I doing anything wrong here?
Thanks in advance.

A: Easy way to do this is by using the contentBackgroundColor style.  Something like this:
<s:DropDownList contentBackgroundColor="0xDB9E36" >
    <s:dataProvider>
        <mx:ArrayCollection>
            <fx:String>Flash</fx:String>
            <fx:String>Director</fx:String>
            <fx:String>Dreamweaver</fx:String>
            <fx:String>ColdFusion</fx:String>
            <fx:String>Flash</fx:String>
            <fx:String>Director</fx:String>
            <fx:String>Dreamweaver</fx:String>
            <fx:String>ColdFusion</fx:String>
            <fx:String>Flash</fx:String>
            <fx:String>Director</fx:String>
            <fx:String>Dreamweaver</fx:String>
            <fx:String>ColdFusion</fx:String>
        </mx:ArrayCollection>
    </s:dataProvider>
</s:DropDownList>

Some more details..
When creating a custom skin; there is a list of properties called contentFill; defined like this:
 static private const contentFill:Array = ["bgFill"];

You'll notice the value listed here is the bgFill; the same background whose color you are trying to change..  And it can be retrieved publicly by using the contentItem property:
override public function get contentItems():Array {return contentFill};

The SparkSkin class [which all MXML Skins extend by default] access this value inside of updateDisplayList.  Every property in the contentItems array has it's background color specificed using the contentBackgroundColor and it's alpha specified using contentBackgroundAlpha.
It is a bit misleading that a value is explicitly defined in the MXML then [potentially] overwritten in ActionScript.


text:
Q: Distribution of mean*standard deviation of sample from gaussian I'm trying to assess the feasibility of an instrumental variable in my project with a variable I havent seen before. The variable essentially is an interaction between the mean and standard deviation of a sample drawn from a gaussian, and im trying to see what this distribution might look like. Below is what im trying to do, any help is much appreciated.
Generate a set of 1000 individuals with a variable x following the gaussian distribution, draw 50 random samples of 5 individuals from this distribution with replacement, calculate the means and standard deviation of x for each sample, create an interaction variable named y which is calculated by multiplying the mean and standard deviation of x for each sample, plot the distribution of y.

A: Beginners version
There might be more efficient ways to code this, but this is easy to follow, I guess:
stat_pop <- rnorm(1000, mean = 0, sd = 1)

N = 50
# As Ben suggested, we create a data.frame filled with NA values
samples <- data.frame(mean = rep(NA, N), sd = rep(NA, N))
# Now we use a loop to populate the data.frame
for(i in 1:N){
  # draw 5 samples from population (without replacement)
  # I assume you want to replace for each turn of taking 5
  # If you want to replace between drawing each of the 5,
  # I think it should be obvious how to adapt the following code
  smpl <- sample(stat_pop, size = 5, replace = FALSE)
  # the data.frame currently has two columns. In each row i, we put mean and sd
  samples[i, ] <- c(mean(smpl), sd(smpl))
}

# $ is used to get a certain column of the data.frame by the column name.
# Here, we create a new column y based on the existing two columns.
samples$y <- samples$mean * samples$sd

# plot a histogram
hist(samples$y)

Most functions here use positional arguments, i.e., you are not required to name every parameter. E.g., rnorm(1000, mean = 0, sd = 1) is the same as rnorm(1000, 0, 1) and even the same as rnorm(1000), since  0 and 1 are the default values.
Somewhat more efficient version
In R, loops are very inefficient and, thus, ought to be avoided. In case of your question, it does not make any noticeable difference. However, for large data sets, performance should be kept in mind. The following might be a bit harder to follow:
stat_pop <- rnorm(1000, mean = 0, sd = 1)
N = 50
n = 5

# again, I set replace = FALSE here; if you meant to replace each individual
# (so the same individual can be drawn more than once in each "draw 5"),
# set replace = TRUE
# replicate repeats the "draw 5" action N times
smpls <- replicate(N, sample(stat_pop, n, replace = FALSE))
# we transform the output and turn it into a data.frame to make it
# more convenient to work with
samples <- data.frame(t(smpls))

samples$mean <- rowMeans(samples)
samples$sd <- apply(samples[, c(1:n)], 1, sd)
samples$y <- samples$mean * samples$sd
hist(samples$y)

General note
Usually, you should do some research on the problem before posting here. Then, you either find out how it works by yourself, or you can provide an example of what you tried. To this end, you can simply google each of the steps you outlined (e.g., google "generate random standard distribution R" in order to find out about the function rnorm().
Run ?rnorm to get help on the function in RStudio.


text:
Q: Encountering an obstacle in flexbox, positioning one div under another while keeping a third to the side Here is the CSS, from the media query, all display:flex

video {
  height: 800px;
  width: auto;
}

.info {
  order: 2;
  border: 0.5 px solid #f7f7f7;
  background: white;
  width: 566.03px;
  height: max-content;
  position: relative;
}

.video-div {
  border: 0.5 px solid #f7f7f7;
  background: white;
  width: 566.03px;
  order: 1;
}

.interaction {
  order: 3;
  border: 0.5 px solid #f7f7f7;
  background: white;
  width: 566.03px;
  height: max-content;
}

.middle {
  height: 569px;
}

 First div

 Second div

 Third div

This is where I am. I need to move the highlighted div, under the second div,(The small one "therock" div).

A: You can achieve this with flex pretty easily.
In my example below, there is a main div with flex-direction set to row.  The right column is set to display: flex with flex-direction column. This stacks the children of main horizontally and children of right vertically.

html, body {
  height: 100%
}
.main {
  display: flex;
  flex: 1 1 0;
  flex-direction: row;
  width: 100%;
  height: 100%;
}

.left {
  background: lightblue;
}

.right {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background: pink;
}

.fill {
  flex-grow: 1;
  background: yellow;
}

Blah blah blah

More blah blah


text:
Q: Curly Braces: adding half-spaces around each brace When I use the commands \{ and \},  the braces rendered are "too tight" or hug too closely to the text and math that lies between them. I would like to redefine \{ to \{\,, and \} to \,\} , but I'm not sure how to do this with delimiters.

A: A low tech solution would be to define a new command, such as:
\newcommand{\Set}[1]{\{\,#1\,\}}
Here's a MWE with picture:
\documentclass{article}
   \newcommand{\Set}[1]{\{\,#1\,\}}
\begin{document}
   \{a, b\} vs \Set{a, b}

   $\{a, b\}$ vs $\Set{a, b}$
\end{document}

A: Additional spaces (e,g,\,) can be added by redefining \{ and \}. But it will not work for \}, it breaks \right, because the space would be inserted between \right and the delimiter. Therefore the example redefines \right to look for a following \} to insert the space at the right place before the original \right. The example also assumes that the spaces are only needed in math mode, the text mode versions of the curly braces are not changed.
\documentclass{article}

\DeclareRobustCommand{\{}{\ifmmode\lbrace\,\else\textbraceleft\fi}
\DeclareRobustCommand{\}}{\ifmmode\rbracespace\else\textbraceright\fi}
\newcommand*{\rbracespace}{\,\rbrace}

\makeatletter
\let\saved@right\right
\renewcommand*{\right}{%
  \@ifnextchar\}{\,\saved@right\rbrace\@gobble}{\saved@right}%
}
\makeatletter

\begin{document}
  \[ \{ a, b \} = \left\{ \frac{c}{d}, \frac{e}{f} \right\} \]
\end{document}

Further support for \big and friends
\documentclass{article}

\DeclareRobustCommand{\{}{\ifmmode\lbrace\,\else\textbraceleft\fi}
\DeclareRobustCommand{\}}{\ifmmode\rbracespace\else\textbraceright\fi}
\newcommand*{\rbracespace}{\,\rbrace}

\makeatletter
\newcommand*{\patch@for@rbrace}[1]{%
  % #1: command to be patched without backslash
  \expandafter\@patch@for@rbrace
  \csname saved@#1\expandafter\endcsname
  \csname #1\endcsname
}
\newcommand*{\@patch@for@rbrace}[2]{%
  % #1: macro for original meaning
  % #2: command to be patched
  \@ifdefinable{#1}{%
    \let#1=#2%
    \renewcommand*{#2}{%
      \@ifnextchar\}{\,#1\rbrace\@gobble}{#1}%
    }%
  }%
}
\@for\x:=right,bigr,Bigr,biggr,Biggr,big,Big,bigg,Bigg\do{%
  \patch@for@rbrace\x
}
\renewcommand*{\bigl}{\mathopen\saved@big}
\renewcommand*{\Bigl}{\mathopen\saved@Big}
\renewcommand*{\biggl}{\mathopen\saved@bigg}
\renewcommand*{\Biggl}{\mathopen\saved@Bigg}
\renewcommand*{\saved@bigr}{\mathclose\saved@big}
\renewcommand*{\saved@Bigr}{\mathclose\saved@Big}
\renewcommand*{\saved@biggr}{\mathclose\saved@bigg}
\renewcommand*{\saved@Biggr}{\mathclose\saved@Bigg}
\makeatletter

\begin{document}
  \[ \{ a, b \} = \left\{ \frac{c}{d}, \frac{e}{f} \right\} \]
  \[ \bigl\{ \mbox{big l/r} \bigr\} \]
  \[ \Bigl\{ \mbox{Big l/r} \Bigr\} \]
  \[ \biggl\{ \mbox{bigg l/r} \biggr\} \]
  \[ \Biggl\{ \mbox{Bigg l/r} \Biggr\} \]
  \[ \big\{ \mbox{big} \big\} \]
  \[ \Big\{ \mbox{Big} \Big\} \]
  \[ \bigg\{ \mbox{bigg} \bigg\} \]
  \[ \Bigg\{ \mbox{Bigg} \Bigg\} \]
\end{document}


text:
Q: Ошибка создания COM HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG) Не получается создать объект класса Com IShellWindows. На примере документации С++ создание работает. Но при попытке создать его в С#. Получаю исключение.
static Guid CLSID_IShellWindows = new Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85");
static Guid IID_ShellWindows = new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39");

static void Main(string[] args)
{
    Type desktopType = Type.GetTypeFromCLSID(CLSID_IShellWindows, null, true);
    object shellDesktop = Activator.CreateInstance(desktopType);
}

Type возвращается, но его не возможно создать через Activator. Поиск по ошибке говорит сменить целевой процессор на x86, но это не помогает.

A: Вы откуда-то взяли неверные идентификаторы и, таким образом, пытаетесь создать объект по идентификатору интерфейса. Вот так сработает:
Guid CLSID_ShellWindows = new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39");
object shellDesktop = Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_ShellWindows, null, true));


text:
Q: Bypass default view, Kohana I want to return a view, however Kohana forces it through the default view, which I don't want. How do I temporary disable the default view?

A: As zombor comments, if you are really talking about the template controller, you can disable its rendering by putting this line in your controller:
$this->auto_render = FALSE;

A:  public function action_index()
    {
        $user_view = $this->getUserView();

        $this->request->response = View::factory('templates/main',$user_view);
    }
public function getUserView($user_details)
    {
        $user_view['list_page'] = View::factory('templates/usermgt')
                        ->bind('user_detail','data')
                        ->bind('msg','test');
        return $user_view;
    }

where getUserView() returns the view page, to action index.
hope it matches ur requirement


text:
Q: htaccess authentication not working What is wrong with this .htaccess? It's HTTP auth plus some rewrite rules. But when I enter HTTP user pass, it logs in but it gives 500 internal server error.
AuthUserFile /home/useraccount/.htpasswds
AuthName "Please Log In"
AuthType Basic
require user wiki

RewriteEngine On
RewriteRule ^/?wiki(/.*)?$ %{DOCUMENT_ROOT}/index.php [L]

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^/?images/thumb/[0-9a-f]/[0-9a-f][0-9a-f]/([^/]+)/([0-9]+)px-.*$ %{DOCUMENT_ROOT}/thumb.php?f=$1&width=$2 [L,QSA,B]

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^/?images/thumb/archive/[0-9a-f]/[0-9a-f][0-9a-f]/([^/]+)/([0-9]+)px-.*$ %{DOCUMENT_ROOT}/thumb.php?f=$1&width=$2&archived=1 [L,QSA,B]

A: The Apache error logs are the best place to start (usually at /var/log/apache2 or /var/log/httpd). That will tell you exactly what the problem is.
I'd guess that either the .htpasswds file isn't where you've specified, or there's a problem with the file contents or permissions.


text:
Q: Extend Dijit.Dialog with template I want to create a Property Sheet like one given below by extending Dijit.Dialog with a template. How can this be achieved?

A: You can extend it using dojo.declare. You can then override the templateString.
dojo.declare('PropertySheetDialog', [dijit.Dialog], {
    //this is the default template for dijit.Dialog
    templateString: dojo.cache("dijit", "templates/Dialog.html"),
});

the default template referenced above is dojo/dijit/templates/Dialog.html
you can start with that.

A: Picture in your question is quite funny...
I extend Dijit.Dialog like this:
Dialog mixed with TemplatedMixin and WidgetsInTemplateMixin, can insert any declarative widgets.
define([
    "dojo/_base/declare",
    "dijit/Dialog",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/text!./templates/custom.html",
    "dojox/form/CheckedMultiSelect"
], function (declare, Dialog, TemplatedMixin, _WidgetsInTemplateMixin, template) {
    return declare("app.management.panels.customColumn", [Dialog, TemplatedMixin, _WidgetsInTemplateMixin], {
        templateString:template,

        }
    });
});

./templates/custom.html is a copy of the original templates. put your code in containerNode.

            x

        <select multiple="true" name="multiselect" data-dojo-type="dojox.form.CheckedMultiSelect">
            <option value="VA" selected="selected">Virginia</option>
            <option value="WA" selected="selected">Washington</option>
            <option value="FL">Florida</option>
            <option value="CA">California</option>
        </select>

Update
Another way to do this, only tested under dojo 1.8.
You can use "dijit/ProgressBar" in ./templates/progressInfo.html
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojox/widget/Standby",
    "dijit/TitlePane",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/text!./templates/progressInfo.html",
    "dijit/ProgressBar"
], function (declare, lang, Standby, TitlePane, _WidgetsInTemplateMixin, template) {
    return declare("app.management.panel.cpanel.progressInfo", [TitlePane, _WidgetsInTemplateMixin], {
        'class':'cpanelProgressInfo',
        title:"progressInfo",
        toggleable:false,
        style:"width:450px;",
        mainStore:null,
        content:template,
        postCreate:function () {
            this.inherited(arguments);
            this.Standby = new Standby({target:this.domNode, zIndex:1000, color:"#eeeeee"});
            this.addChild(this.Standby);
            this.Standby.show();
        },
        refresh:function () {
            // my custom dojo store
            var rt = this.mainStore.query()[0];
            this.set('content', lang.replace(template, rt));
        }
    });
});

A: You can create an anonymous widget in the constructor and load a template into that.
However, this can cause problems with layout widgets, and you cannot use data-dojo-attach-event in the template (instead wire up buttons, etc. manually).
    define( [ 'dojo/_base/declare',
          'dijit/Dialog',

        // used for anonymous content widget
        'dijit/_WidgetBase',
        'dijit/_TemplatedMixin',
        'dijit/_WidgetsInTemplateMixin',
        'dojo/text!/js/myProject/CustomDialog/templates/CustomDialog.html',

        // for wiring up buttons
        'dojo/_base/lang',
        'dojo/on',

        // used in anonymous widget's template
        'dijit/form/ValidationTextBox',
        'dijit/form/NumberSpinner',
        'dijit/form/Textarea',
        'dijit/form/Button' ],
    function( declare, Dialog, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, template, lang, on )
    {
        return declare( [ Dialog ], // inherit from dijit/Dialog
        {
            id: 'my_custom_dialog',
            title: 'I Am Custom!',

            declaredClass: 'myProject.CustomDialog',

            constructor: function( myProjectsettings )
            {
                var contentWidget = new ( declare( [ _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin ],
                {
                    templateString: template
                } ) );
                contentWidget.startup();
                this.content = contentWidget;
            },

            postCreate: function()
            {
                // run any parent postCreate processes
                this.inherited( arguments );

                // automatically wire up the cancel button
                on.once( this.content.cancelButton, 'click', lang.hitch( this,
                function()
                {
                    this.onCancel(); // use same method as X button
                } ) );
             }
        } ); // end declare
    }
);

A: se the buildRendering to alter the templateString, thus you get all the _widget goodies from both templates. For more details see the answers in here

A: Using inner class is simple and will be fully supported by dojo.
define("sample/dialog/CreateUserDialog", [
    "dojo/_base/declare",
    "dijit/Dialog",
    "dojo/text!./resources/CreateUserDialog.html",
    "dijit/layout/ContentPane",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin"
], function(declare, Dialog, template, ContentPane, TemplatedMixin, WidgetsInTemplateMixin) {
  declare("sample.layout._CreateUserPane", [ContentPane, TemplatedMixin, WidgetsInTemplateMixin],{
    templateString: template
  });

  return declare("sample.dialog.CreateUserDialog", [Dialog],{
    title: "Create User",
    content: new sample.layout._CreateUserPane()
  });
});

You can touch content object by "(Dialog instance).content".


text:
Q: ACTIVATE after CREATE causing the toolbar to be missing in part stack I have a part stack with two parts. The second part has a ToolBar with a Direct Tool Item with an icon.
I would like to initialise the second part without displaying it as some code needs to be executed straight away not when focused.
To do this I call:
partService.showPart(secondPartID, PartState.CREATE);

After this I call:
partService.showPart(secondPartID, PartState.ACTIVATE);

This then brings the second view to the front as expected but the toolbar is missing.
I've tried getting the toolbar for the part and getting the widget but the widget is null.
If I switch to the first part (by clicking the tab) then switch back to the second, the toolbar has successfully been created.
I'm wondering if I'm using the CREATE/ACTIVATE calls incorrectly as the behaviour I'm getting is strange.
What could be causing this?

A: By wrapping this in an async it fixes it. I've tried multiple variations to fix this and this is the only thing that will.
Display.getDefault().asyncExec(() -> partService.showPart(id, PartState.ACTIVATE));

It must be that things aren't initialised/ready yet which causes the toolbar to not be added. By using async it must be waiting until it's ready to display the toolbar.
If anybody is able to give any extra information as to why this fixes it I'll update the answer.


text:
Q: How to outsource modals into another html file using AngularJS I'm using a lot of modals in my app and I want to outsource these modals into a seperate file. A modal looks like this:

In my js-file I'm attaching it like this:
$scope.configureFactory = function () {
    $uibModal.open({
        templateUrl: 'configurationModal.html',
        backdrop: true,
        windowClass: 'configuration-modal',
        controller: function ($scope, $uibModalInstance) {

            //......

Now I just want to put these modal templates into another html-file but my main index.html.
I have already tried to reference to another html file in my index.html like:
<link type="text/html" href="modals.html"/>
and I've tried using ng-include:

, but nothing works.
Always getting:
"XMLHttpRequest cannot load file:///C:/Users/Fred/foo/foo2/foo3/src/configurationModal.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
How can I outsource my modals and still attache them?

A: You can use $templateRequest as below...
app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
    // Make sure that no bad URLs are fetched. If you have a static string like in this
    // example, you might as well omit the $sce call.
    var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');

    $templateRequest(templateUrl).then(function(template) {
        // template is the HTML template as a string

        // Let's put it into an HTML element and parse any directives and expressions
        // in the code. (Note: This is just an example, modifying the DOM from within
        // a controller is considered bad style.)
        $compile($("#my-element").html(template).contents())($scope);
    }, function() {
        // An error has occurred here
    });
});


text:
Q: 'NoneType' object has no attribute 'send' This is my code. It should send message to the channel when user join the server.
@client.event
async def on_member_join(member):
    print('+') #this works perfectly
    ch = client.get_channel(84319995256905728)
    await ch.send(f"{member.name} has joined")

But error was occur. This is the output:
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 30, in on_member_join
    await ch.send(f"{member.name} has joined")
AttributeError: 'NoneType' object has no attribute 'send'

I had enabled server member intents in dev portal.
intents = nextcord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='=',intents=intents)

May I know how to fix it?

A: Make sure your bot has the ability to send a message in that channel, otherwise it will say it can't send it, if it does make sure that channel Id exists.
for an example:
@client.event
async def on_member_join(member):
  channel = client.get_channel(900247143351210004)
    await channel.send(f"{member.mention} has arrived!, check out our announcments channel for server and bot announcements!")

A: Thanks all for your inputs. Above issue has been taken care. Issue was the channel with id 84319995256905728 did not exist, and I fixed it accordingly.


text:
Q: TextView is not working in relative layout I am facing Problem In Relative layout. I set several textviews in my XML layout but after running the program, it will not show the text on emulator/phone. Before I was thinking, this is the problem of the updated version of android studio. But I had also checked in another computer system with an older android version. I am sharing the XML code with you all. Please Help me.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/transition_profile"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@android:color/white">

        <ImageView
        android:id="@+id/imgv_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/round_arrow_back_ios_24_px"
        android:layout_marginTop="54dp"
        android:layout_marginLeft="28dp"
        android:layout_alignParentLeft="true"/>

        <ImageView
        android:id="@+id/imgv_help"
        android:layout_width="34dp"
        android:layout_height="34dp"
        android:src="@drawable/round_help_outline_24_px"
        android:layout_alignParentRight="true"
        android:layout_marginTop="54dp"
        android:layout_marginRight="28dp"/>

        <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/imgv_boss"
        android:layout_width="126dp"
        android:layout_height="126dp"
        android:src="@drawable/boss"
        android:layout_centerInParent="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="71dp"/>

        <TextView
        android:id="@+id/tv_emp_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="#262d3d"
        android:letterSpacing="0.02"
        tools:text="Ramesh Singha"
        android:fontFamily="@font/roboto_slab_bold"
        android:layout_below="@id/imgv_boss"
        android:layout_centerInParent="true"
        android:layout_marginTop="26dp"/>

        <TextView
        android:id="@+id/tv_boss_profile_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#6c7383"
        android:letterSpacing="0.02"
        android:layout_below="@id/tv_emp_name"
        tools:hint="Field Manager"
        android:fontFamily="@font/roboto_slab_regular"
        android:layout_centerInParent="true"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"/>

        <LinearLayout
            android:id="@+id/ll_tabslides"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="#fff"
            android:layout_below="@id/tv_boss_profile_name">

            <com.google.android.material.tabs.TabLayout
             android:id="@+id/tblyt_profile"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:background="@color/white"
             android:elevation="6dp"
             android:minHeight="?attr/actionBarSize"
             app:tabIndicatorColor="#0091ea"
             app:tabSelectedTextColor="#0091ea"
             app:tabTextColor="#6c7383"
             tools:targetApi="lollipop"/>

            <androidx.viewpager.widget.ViewPager
             android:id="@+id/vpgr_profile"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>

        </LinearLayout>

</RelativeLayout>

A: You are using tools:text="Ramesh Singha" in textView and that is used for testing purpose. You should use following options if you want to set text

*

*android:text="Ramesh Singha"

*Add in code
<TextView
     android:id="@+id/tv_emp_name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textSize="24sp"
     android:textColor="#262d3d"
     android:letterSpacing="0.02"
     tools:text="Ramesh Singha"
     android:fontFamily="@font/roboto_slab_bold"
     android:layout_below="@id/imgv_boss"
     android:layout_centerInParent="true"
     android:layout_marginTop="26dp" />

TextView userName=(TextView)findViewById(R.id.tv_emp_name)
userName.setText("Ramesh Singha")

A: For Static text,use

android:text="Ramesh Singha"

instead of

tools:text="Ramesh Singha"

For dynamic text,use

.xml File

<TextView
    android:id="@+id/tv_boss_profile_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="14sp"
    android:textColor="#6c7383"
    android:letterSpacing="0.02"
    android:layout_below="@id/tv_emp_name"
    tools:hint="Field Manager"
    android:fontFamily="@font/roboto_slab_regular"
    android:layout_centerInParent="true"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"/>

.Java File

TextView employeeName=(TextView)findViewById(R.id.tv_emp_name);
employeeName.setText("Ramesh Singha");


text:
Q: Evaluate Polynomial Function Not sure where I'm going wrong in this, and it has to be in my polyEvaluate function, but any help would be appreciated. The problem is coming in the final calculation. I've tried modifying the function but that doesn't seem to fix the issue.
#include <stdio.h>
#include <math.h>

double polyEvaluate(double coefficients[], int order, double x)
{
    int i, j;
    double polyExp[order], polyProd[order];
    double sum;
    double constant = coefficients[order];
    double temp;

    for(i=order-1; i>0; i--){
        polyExp[i]=pow(x, i);
    }

    j=order;
    i=0;

    while (i<j){
        temp=polyExp[i];
        polyExp[i]=polyExp[j];
        polyExp[j]=temp;
        i++;
        j--;
    }

    for(i=0; i<order; i++){
        polyProd[i]=coefficients[i] * polyExp[i];
    }

    for(i=0; i<order; i++) {
        sum+=polyProd[i];
    }

    sum+=constant;

    return(sum);
}

int main(void)
{
    int order, i;
    double input;
    double coefficients[order+1];

    printf("Enter the order of the polynomial: ");
    scanf("%d", &order);

    printf("\nEnter the coefficients: \n");

    for(i=0; i<=order; i++)
    {
        printf(" >> ");
        scanf("%lf", &coefficients[i]);
    }

    printf("\nEnter the value of x: ");
    scanf("%lf", &input);

    printf("\nThe value of the function is: %lf", polyEvaluate(coefficients, order, input));

    return(0);
}

A: Your function to evaluate the polynom is way to complicated. A mathematical representation of the polynom could look like this:
    f(x) = ∑ c[i]∙xⁱ

There's no need to make the constant a special case, it is c[0]∙x⁰. This formula is represented in C as:
    double polyEvaluate(double coeff[], int order, double x)
    {
        double res = 0.0;

        for (int i = 0; i <= order; i++) {
            res += coeff[i] * pow(x, i);
        }

        return res;
    }

This simple code requires that the index of the coefficient refers to the exponent, which is a more natural representation for the evaluation function. If you want the user to enter the coefficients with the large exponents first, this should in my opinion be handled once during the input.
(You reverse of the auxiliary array polyExp, but that's not really needed; it would be enough to access the coefficient with order - i when you sum the terms. Still, it is better to choose a representation that represents your code well in code. With your current code, you create an auxiliary array and reverse it for every evaluation.)
You can evaluate the polynom without the pow function and hence without the math library, just calculate the power of x as you go:
    double polyEvaluate(double coeff[], int order, double x)
    {
        double fact = 1.0;
        double res = 0.0;
        int i;

        for (i = 0; i <= order; i++) {
            res += coeff[i] * fact;
            fact *= x;
        }

        return res;
    }

A: Your main problem is probably the variable length array you have defined as length order + 1 while order doesn't have a value assigned at that point in time.
I'd advise to stick with fixed-length arrays for the time being (just make them long enough).


text:
Q: how to replace when drop and drag continer Js or Jquery
I have  10 containers. for example ;
when I drag the first container and drop  onto eight container that replaces to eight to one
1.container -> drag drop -> 8.container then call function automatic 8.container -> drag drop -> 1.container . ' replacement contents of container

A:

             1

             2

             3

             4

            5

        6

            7

            8

            9

            10


text:
Q: How can I get items that their names start with a number in Linq To Sql? How can I get a list of Products that, for example, theirs productName starts with a number?
Thanks!!

A: List<string> digits = Enumerable.Range(0, 10).Select(i => i.ToString()).ToList();
var query = from p in db.Products
            where digits.Contains(p.productName.Substring(0, 1))
            select p;

Alternatively, add the following to your DBML mapping file:
<Function Name="ISNUMERIC" IsComposable="true">
    <Parameter Name="Expression" Parameter="Expression" Type="System.String" DbType="NVarChar(4000)" />
    <Return Type="System.Boolean" DbType="BIT NOT NULL"/>
</Function>

Then you can say:
var query = from p in db.Products
            where db.ISNUMERIC(p.productName.Substring(0, 1))
            select p;

You can do this in an XML mapping file too but I can't remember the syntax off the top of my head for the necessary code in your manually defined DataContext. Let me know if you need this.
I strongly prefer the first method but can see using the SQL built-in ISNUMERIC if profiling told me the pure LINQ version is a performance bottleneck.

A: One way to do it:

Products.Where(n => n.ProductName.SubString(0,1) >= "0" && n.ProductName.SubString(0,1) <= "9")

A: Try this one.
List<string> searchProducts = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
dbContext.Products.Where(x=> searchProducts.Any(y=> x.ProductName.StartsWith(y))).ToList();


text:
Q: PHP How to Catch DeadlineExceededError on SendMail to continue Script execution I have set up a script that runs daily on Google App Engine. It gets data from a database, and in a loop checks that data, and if certain conditions are met, it will send an email to a defined email address which it gets when it gets the other data. On rare occasion, this deadline error occurs:
PHP Fatal error:  Uncaught exception 'google\appengine\runtime\DeadlineExceededError' with message 'The API call
mail.Send() took too long to respond and was cancelled.' in /base/data/home/runtimes/php/sdk/google/appengine/runtime/RealApiProxy.php:74

What i am looking for is simply this: how do i catch this exception so that i can continue with the execution of the script? Since it is defined as an Exception, i presume using
foreach ($data as $key => $value)
    //code to check if email needs to be sent
    try {
        //send mail code
    } catch (Exception $e) {
        // handling code
    }
}

Would allow me to deal with it, but being this is a AppEngine exception related to Timing out, it does not sound to me like one a Try block can handle. so, is it just a regular exception and the above code would guarantee execution of the full loop when this error occurs?

A: The DeadlineExceededError class extends Error rather than Exception. You'll want to use set_error_handler to set the function to put your handling code in.

A: As it turns out, There is no way to directly deal with this Error. It is a Fatal error after all, and so the script will always stop once this occurs. There is however a workaround specific to App Engine, which is what i was looking for, Push Queues. They allow the Email to be sent out in a separate script asynchronously with no reply (fire-and-forget style). By doing so, the Fatal error occurs in an isolated instance of a secondary script, so that even if it Fatal errors out, only that single instance is affected, which means that only the one email is not sent out.
If 100 emails are supposed to send, and one Fatally errors out, now 99 are sent out instead of only 20-50 because it was in the middle.


text:
Q: Typescript (tsc) not picking up my .ts file
tsc --version Version 2.8.3

In my firebase project, at root I have tsconfig.json as below;
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",
    "module": "commonjs",
    "outDir": "./",
    "types": ["mocha"],
    "sourceMap": true,
    "project": "/**/*.ts",
    "watch": true,
    "strict": true
  },
  "exclude": ["node_modules", "typings/browser.d.ts", "typings/browser"]
}

And under following folder I have test.ts file like below;
app-firebase\functions\Repositories\test.ts

Code:
abstract class AnimalAbstract {
  abstract makeSound(): void;
  move(): void {
    console.log("roaming the earth...");
  }
}

If I run tsc at root folder, it does not compile file into .js. But if I navigate to folder and run tsc test.ts it compiles.
I also tried to remove project parameter in config file, but did not work as well.
How can I make it watch entire project folder?

A: OK I had to add rootDir in config.
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",
    "module": "commonjs",
    "outDir": "./",
    "types": ["mocha"],
    "sourceMap": true,
    "rootDir": "./",
    "watch": true,
    "strict": true
  },
  "exclude": ["node_modules", "typings/browser.d.ts", "typings/browser"]
}


text:
Q: simulate errors to differentiate between include and require in PHP I've read about how require and include differ
In short, one gives a warning an other quits process execution.
I'd like to simulate the behaviour to see the difference live in a non production environment. I've created two classes in separate files:
namespace includeTest;
class IncludeError{
    public static function errorTrigger(){
        throw new \Exception();
    }
}

and
namespace requireTest;
class RequireError{
    public static function errorTrigger(){
        throw new \Exception();
    }
}

When I test the IncludeError::errorTrigger() with this code
namespace index;
include "includeTest.php";
\includeTest\IncludeError::errorTrigger();
print "done in index.php";

I am getting the usual Fatal error: Uncaught Exception and the "done in index.php" line never prints, indicating that even though the error (actually Exception) happened in "includeTest.php", it was terminating the caller script as well. Clearly exceptions are not the type of errors that give warnings when included. What kind of error would trigger just a warning?
I am using php 7.3.8.
An excerpt from the book I am reading:

The only difference between the include() and require() statements lies in their handling of errors. A file invoked using require() will bring down your entire process when you meet an error. The same error encountered via a call to include() will merely generate a warning and end execution of the included file, leaving the calling code to continue. This makes require() and require_once() the safe choice for including library files, and include() and include_ once() useful for operations like templating.


text:
Q: MYSQL, Have AE be equal to Æ on search I want to be able to search for "ae" and have both "ae" and "Æ" as result. I just can't figure out how to do it.
I tried collating as utf8_german2_ci and utf8_general_ci. Both should be able to do just what I want from what I read. But it's just not working.
Thanks in advance.

A: From your comment ("Just tried. Yes to both."), I gather that there's nothing wrong with your database or connection. Your only problem is the LIKE. LIKE does a "per-character" comparison, and the MySQL manual http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html has an illustration very similar to your case (using "SELECT 'ä' LIKE 'ae' COLLATE latin1_german2_ci;"). So you're looking at expected behaviour, but can say "select s1, hex(s1) from tj where s1 like '%ae%' or s1 like '%æ%';".


text:
Q: Error creating webservice client I am trying to create a new Web Service client through STS IDE using the wsdl URL. I get error "WSDL file has validation errors. Code generation may fail." during wsdl validation phase.
Message: A problem occured while running WS-I WSDL conformance check:
org.eclipse.wst.wsi.internal.analyzser.WSIAnalyzerException:
The WS-I Test Assertion Document (TAD) document was either
not found or could not be processed.
The WSDLAnalyzer was unable to validate the given WSDL file.

Is there a problem in the service itself or am i making any mistake in creating the client ? Any help is appreciated.


text:
Q: Read And Modify On Same Transaction - Bigtable I am building a coupon system and I am using Bigtable.
My schema has two columns - Customer ID and Coupon code.
I would like to query the table to check if the customer already exists and if it is true, return the code and if it is false, modify the Customer ID cell with the ID and return back the code.
I saw there is an option to do it in Bigtable ReadModifyWriteRow operator or with CheckAndMutateRow but I have not found any references.

A: Google has API documentation for Bigtable and Python available here. This shows you all the available methods and the source code that they refer to, so you can easily and more effectively use and understand the usage.
ReadModifyWriteRow appends as bytes or increments data in an existing cell in a row.
CheckAndMutateRow checks if a filter matched and then applies 2 sets of mutations. These are "true mutations" and "false mutations".
You can use if statements in order to achieve the usage that you wish.
You can read about CheckAndMutateRow conditional requests, and there are also code samples available.


text:
Q: Planning to sell iPad 2 - need to know how to securely erase data I did a Google search and I have followed instructions from this link: http://www.macworld.co.uk/how-to/iosapps/how-wipe-all-personal-data-from-iphone-ipad-3498379/
Is that all I must do? Are there any other things I need to check before selling it?

A: I think you are good to go. If you are concerned about recovering data, it is almost impossible to recover the data after the encryption key has been deleted (that's what Erase all content and settings does). You can check at http://support.apple.com/kb/ht5661 to make sure everything is good.
TL;DR: Good to go. Nothing else needs to be done.


text:
Q: setbase(8) and std::cout<Whats the difference between std::cout<<std::setbase(8)<<32; and std::cout<<std::oct<<32; Are they equivalent?
And also, what is the purpose of std::cout.oct??

A: std::oct    Sets the basefield format flag for the str stream to oct.
std::setbase Sets the basefield format flag to one of its possible values: hex, dec or oct depending on the value of the base parameter.
I think the big difference is that setbase takes an argument so you could pass it a variable containing the numerical base you want.  Instead of having a bunch of if statements to check the variable and use dec, oct or hex.
I'm not sure about std::cout.oct though.


text:
Q: Ajax loader div in zend framework through my application I use common Ajax loader Div, i show it always when i make an ajax request
submitHandler: function(form) {

                $('#loader').show();
                $(form).ajaxSubmit({
                    type: 'POST',
                    url: "/exampleactions/example",
                    data:{
                    },
                    success: function(response_data){
                        $('#loader').hide();

where is the best place to put this div to use it every where ?
shall i put it layout.php ?

A: IMO

*

*There is not going to be a 100% correct answer for this.

*Its totally up to the design of the application.

But, if the same loader is used through out the site, and nothing is loaded outside AJAX, then its probably a good idea to keep the div in the layout and keep it hidden until needed.


text:
Q: HaxeFlixel Игнорирование прозрачных пикселей на спрайте Мне нужно, чтобы спрайт увеличивался, когда я наводил курсор мыши на спрайт. Но проблема в том, что спрайт имеет необычную форму, которая оставляет много прозрачного пространства. И мышь реагирует на это прозрачное пространство. Как мне сделать так, чтобы игра не реагировала на прозрачные пиксели, а только на сам спрайт?
Вот мой код:
override public function create()
{
    image = new FlxSprite(100, 100).loadGraphic("assets/images/freeplay.png");
    add(image);
}

override public function update(elapsed:Float)
{

    image.scale.set(1, 1);

    if (FlxG.mouse.overlaps(image))
    {
       image.scale.set(1.1, 1.1);
    }

super.update(elapsed);
}

A: Можно добавить проверку альфа-канала в точке где находится мышь
override public function update(elapsed:Float)
{
    image.scale.set(1, 1);

    if (FlxG.mouse.overlaps(image))
    {
        var val = image.getPixelAt(FlxPoint.get(FlxG.mouse.screenX, FlxG.mouse.screenY));
        if (val.alpha > 0)
        {
            image.scale.set(1.1, 1.1);
        }
    }
    super.update(elapsed);
}


text:
Q: selecting element which refer to other elements in the same table I am trying to build a very simple CMS. For that I have create a table called categories. As the name suggests it will be the categories for my articles in the CMS.
My table looks like follows with the sample data:

As you can see, a category node has a parent node. now, How can I write a query which selects all the parent nodes of a particular node. Example, if I choose, the node Important, how can I write a query which will return me the following nodes: News, Users, General
I hope I was clear enough

A: I can't say that I really love this method, but the following appears to work in MySQL:
select t.id, t.parent, @parent := parent
from (select @parent := 7) const join
     t
     on t.id = @parent;

You can see it in this SQL Fiddle.
I don't believe this is guaranteed to work, but it seems to work in practice.  If you need to store hierarchical data, you should really change the data structure or switch to a database that supports recursive queries (Postgres, SQL Server, and Oracle, for instance).


text:
Q: Can not use HttpClient from Asp MVC 6 Web Api I try to write simple code:
 public async Task<string> GetData(String labelName)
    {
        using (var client = new HttpClient())
        {
            var uri = new Uri(@"https://example.com/over/search_field?=search_label=" + labelName);

            var response = await client.GetAsync(uri).ConfigureAwait(false);
            var textResult = await response.Content.ReadAsStringAsync();
            return textResult;
        }
    }

At project.json:
 {
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
  "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
 "Microsoft.AspNet.Mvc": "6.0.0-beta8",
 "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
 "Microsoft.AspNet.StaticFiles": "1.0.0-beta8",

 "Microsoft.Framework.Logging": "1.0.0-beta8",
 "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
 "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
 "Microsoft.Net.Http": "2.2.22"
  },
 "frameworks": {
  "dnx451": {
    "dependencies": {
       "Microsoft.AspNet.WebApi.Client": "5.2.3",
      "Microsoft.AspNet.WebApi.Owin": "5.2.3",
      "System.Net.Http": "4.0.1-beta-23409"

   },
   "frameworkAssemblies": {
     "System.Net": "4.0.0.0",
     "System.Net.Http": "4.0.0.0"
   }
 },
 "dnxcore50": { }
},

But, when i try to build code i get error:

Error CS0246  The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?)

Can you help me? How to fix this error?
I use VS 2015 and ASP MVC 6 Web API.
Thank you!

A: This worked for me. I added System.Net.Http to the dependencies section and built the project (thus restored this new dependency in both DNX 4.5.1 and DNX Core 5.0)
"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    // Removed some dependencies for saving space:)
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "System.Net.Http": "4.0.1-beta-23409"
},
"frameworks": {
    "dnx451": { },
    "dnxcore50": {}
},

Verified in the below runtimes and it works fine.

*

*coreclr - X86 - 1.0.0-rc1-update1

*coreclr - X64 - 1.0.0-rc1-update1

*clr - X86 - 1.0.0-rc1-update1

*clr - X64 - 1.0.0-rc1-update1

Also, you need to make sure that you have the using directive which imports the System.Net.Http namespace in the class file where you have your GetData method.
using System.Net.Http;


text:
Q: Prevent access to inherited members This question might be a bit odd. The scenario is as follows:

*

*There is an interface for plugins called IPlugin

*There is an abstract base class for plugins (which implements the interface) called PluginBase

*These are stored inside a class library

Now everyone should be able to create their own plugins by creating a new class library and a plugin class which derives from PluginBase.
The PluginBase class will provide many public properties which are used from the base tool to communicate with the plugin interface. This is done by reflection; the tool searches for a class which is based on the interface IPlugin and creates an instance of that class.
Now the problem is that these public properties are necessary for the plugin mechanism but should not be accessed or changed from the derived plugin class. In short: the user-defined plugin class should not be able to access several public members of its base class PluginBase.
Is this possible somehow? I know that I normally should use private for those properties (so the derived class can't access them) but as the base class also acts as a plugin interface, this is not possible.
Solution (based on answers of Fabjan and Luaan):
// basic plugin interface (IPlugin.dll)
public interface IPlugin
{
    // plugin communication interface
    string SomeProperty { get; set; }
    void SomeMethod();

    // public interface
    string Name { get; }
    void Run();
}

// plugin base class (IPlugin.dll)
public class PluginBase : IPlugin
{
    string IPlugin.SomeProperty
    {
        get { return "Something"; }
        set { /* ... */ }
    }

    void IPlugin.SomeMethod()
    {
        Console.WriteLine("Something");
    }

    public string Name
    {
        get { return "MyName"; }
    }

    public void Run()
    {
        // ...
    }
}

// user-defined plugin (MyPlugin.dll)
public class MyPlugin : PluginBase
{
    public MyPlugin()
    {
        // will not work
        this.SomeProperty ...
    }
}

// main assembly
static void Main(string[] args)
{
    Assembly asm = Assembly.LoadFrom(@"path\to\assembly");

    var type = asm.GetTypes().FirstOrDefault(t => t.GetInterface("NamespaceOfIPlugin.IPlugin", true) != null);

    NamespaceOfIPlugin.IPlugin plugin = (NamespaceOfIPlugin.IPlugin)Activator.CreateInstance(type);

    // works as expected
    plugin.SomeMethod();
}

A: If you don't want the properties to be public, don't make them public.
The architecture of your solution seems to be wonky at best. You expect (require even) all plugins to implement PluginBase, yet you search for plugins based on the IPlugin interface. Why? Pick one, and roll with it. There's no rule in the framework that plugins must be searched for based on some interface.
To prevent a derived class from accessing the members of its parents, you use the private access modifier. If your plugin manager needs to have access to those values, you must make sure it actually does - for example, you could make the part responsible for working with this data a sealed nested class of PluginBase.
But in the end, the question is - why? There's little point in trying to force the derived classes to avoid accessing those members (why have those members in the first place?). Perhaps it would be enough to have those properties in an interface that would be implemented explicitly? That way you could still use e.g. ((IPluginBase)plugin).SomeProperty, but not plugin.SomeProperty. It's not like they couldn't get to the data using reflection anyway.

A:
Now the problem is that these public properties are necessary for the
  plugin mechanism but should not be accessed or changed from the
  derived plugin class.

What you try to do isn't really possible because if class implements abstract class - it must know all its members. What you can do is you can do something like this:
1) Add internal keyword for your interface
internal interface IPlugin
{
   int MyProperty1 {get; set;}
   int MyProperty2 {get; set;}
   int MyProperty3 {get; set;}
   void HiddenMethod();
}

2) Implement properties/methods that you want to hide explicitly :
abstract class PluginBase : IPlugin
{
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    int IPlugin.MyProperty3 { get; set; }
    void IPlugin.HiddenMethod() {}
}

Now you can use all your hidden methods and properties in your main solution via IPlugin interface by casting to it:
IPlugin instance = new MyConcretePlugin();

instance.MyProperty3 = 10;
instance.HiddenMethod();

IPlugin interface now is not accessible from any other solution (except one that holds it) and therefore same are for all hidden members.

A: you could use internal on the methods and properties that only should be available from within the assembly
public class PluginBase : IPlugin
{
    // Only accessible within the same assembly
    internal static int x = 0;
}

A: You can use InternalsVisibleToAttribute.enter link description here


text:
Q: Obtener credenciales en AWS CLI estoy tratando de obtener las credenciales de AWS CLI pero me genera un error, al ingresar el siguiente comando: serverless config credentials --provider aws --key BxxxxxxxxkeyxxxxxG --secret nxxxxxxxxxxxxxxxxxxxxxxxxx8 con sus respectivas llaves, me genera el siguiente mensaje:

Serverless: Setting up AWS...
Serverless: Failed! ~/.aws/credentials already has a "default" profile. Use the overwrite flag ("-o" or "--overwrite") to force the update
ya realicé la respectiva configuración con aws configure, le ingresé las llaves del usuario y su región, pero cuando realizo el serverless config... me sale el mismo error, entonces le agregue al comando el --overwrite y --profile nombre_usuario, me aparece el siguiente mensaje:
Serverless: Setting up AWS...
Gracias por su tiempo, y por la respuesta oportuna, feliz día.

A: el último mensaje lo que quiere decir es que efectivamente sobrescribió el perfil "Default" con las credenciales que usted proporcionó.
Puede chequearlo en el archivo ubicado en tu carpeta de usuario en la siguiente ruta .aws/credentials.
Otra alternativas es que ejecute el comando aws configure list y de esta manera listar todos los perfiles configurados en su máquina, sólo podrá ver las última 4 letras de las credenciales.
Por otro lado para tener mayor autonomía en cada proyecto serverless si desarrollas para diferentes cuentas, puedes agregar el parametro '--profile NUEVO_NOMBRE_PROFILE' de esta manera tendrá un profile para cada cuenta con sus repectiva credenciales, sólo debe asegurarse que en cada ejecución del comando 'serverless' agregue al final el parametro '--profile NUEVO_NOMBRE_PROFILE'.

A: Tranquilo, ya lo tienes configurado. Si lo que quieres es desplegar con el perfil que ya tienes seteado por default, cuando ejecutes sls deploy se utilizara el perfil por defecto. Si quieres crear otro perfil los puedes hacer como lo estas haciendo pero añadiendo la opcion profile para indicarle el nombre del nuevo perfil, si el perfil ya existe tendras que añadir la opcion de -o para sobreescribirlo. Para usarlo cuando hacer el sls deploy puedes hacerlo cuando ejecute el comando, solo tienes que añadir sls deploy --aws-profil <NOMBRE_PERFIL> y tambien puedes seleccionar el perfil desde el serverless.yml.


text:
Q: Get HTML5 custom data attributes from dragged element I have two lists: one just for getting elements (store list) and drag them into the other list (shopping cart).
The shopping cart list stores one elemenet of each type dropped there, and if more than one elemenet of the same type is dragged there, I want the Twitter Bootstrap badge to be incremented, and avoid a new duplicate entry to be stored.
HTML:

Fruit store

Apple

Pear

Banana

Watermellon

Shopping cart

Banana

                    5

Pear

                    2

JS:
// Create fruit store list
var list_element = document.getElementById("fruit-list");
var fruit_list = new Sortable(list_element, {
    group: {
        name: "fruit_group",
        pull: 'clone',
        put: false
    },
    sort: false,
    ghostClass: "droppable-area",
});

// Create shopping cart list

    var cart_list_element = document.getElementById("cart-list");
    var cart_list = new Sortable(cart_list_element, {
        group: {
            name: "fruit_group",
            pull: true,
            put: true
        },
        // Element is dropped into the list from another list
        onAdd: function (event) {
            console.log(event.item)
            // First check if there is an equal fruit at the list already. In that case, increment badge number
            var draggedElement = event.item;
            var type = draggedElement.data('type');

            // Iterate existing elements
            $("#cart-list li").each(function () {
                var existingType = $(this).data('type');

                if (existingType == type){
                    var numberOfFruits = event.item.closest('span').innerHTML;
                    console.log(numberOfFruits + ' ' + type + ' already at the list, updating badges');
                    // Increment number of this fruit
                    (event.item.closest('span').innerHTML)++;
                    return false; //break statement
                } else {
                    console.log('New fruit inserted to cart list');
                }
            });
        },
    });

It is not working, and the problem according to Firebug is the read of the HTML5 custom data field data-type. I need to compare this data-type field to those already at the list to detect duplicates (this is a small executable example of a bigger application, where I need to compare more than one custom data field, so comparing the text of the list entry is not enough for me; it has to be the custom data field).
As you can see, I'm trying to read the dropped item getting if from the onAdd function event (and according to FireBug, the item contained into event is the dropped item with its custom data field, so this has to be ok), and I'm trying to retrieve the data field with .data(). I have read that .data() does create a copy of the value, so it is a better idea to use .attr() when modifing the value, but this example is quite dummy and does not require to modify the custom data field, so it should be enough.
Here is my JsFiddle. Any idea what's wrong?

A: I found the answer: I was using a Jquery where I should have been using plain JavaScript:
var type = event.item.getAttribute("data-type");


text:
Q: Look behind regex in one-liner perl I'm trying to make a one-liner script that prints when github is not behind golang.
For example, java is a language used in github should match, but golang is a language used in github shouldn't match.
I've tried the expression /(?<!golang).*github/, but it doesn't work.
echo "golang is a language used in github" |
    perl -nle'print /(?<!golang).*github/ ? "match" : "no match"'

This prints match instead of no match.
How can I do that using "negative look-behind" in Perl?
(Using Perl v5.28.1)

A: Your expression matches all strings with the word "github" in them. Let's see why:
/(?<!golang).*github/

will match as long as Perl can adjust the .* to match just enough characters to not run into a situation where it's immediately preceded by golang. Regexes being greedy, the .* will match as much as it can while still having the rest of the pattern match.
So if your string is
golang is a language used in github

The regex can match by assigning string to different parts:

*

*(?<!golang) matches at the beginning of the string

*.* gets "golang is a language used in"

*github gets "github"

A potentially costly way to accomplish what you wanted is:
/^(?:(?!golang).)*github/

It works by making sure none of the characters preceding "github" begin the sequence "golang".
So
echo "java is a language used in github" | perl -ne 'print q!Not golang: !, /^(?:(?!golang).)*github/ ? q!true! : q!false!'

will print out Not golang: true while
echo "golang is a language used in github" | perl -ne 'print q!Not golang: !, /^(?:(?!golang).)*github/ ? q!true! : q!false!'

will print out Not golang: false.

Another (less obfuscated) way is to do two consecutive tests:
/^(.*)github/  and  $1 !~ /golang/

If you're doing tens or hundreds of thousands of lines, maybe test both ways to find which is faster?

A: improving Bohemian's,
/^(?!.*golang.*github).*github/

A: Just use a negative look ahead anchored to start:
^(?!.*golang).*github


text:
Q: React Native Webview shows white blank screen I'm trying to use react-native-webview (Android app) and I'm getting a white screen when I try to load my website:
https://lostlaowai.app:4432/?ID=1105T140W4iUserAgentAllow3
I've also noticed that the WebView loads https://www.google.com/ but not google.com without the https:// and ending /
Could this be related?
When you run it in your browser is works fine. But I can't get it to load in the WebView. I've spent the past few days reading all sorts of posts describing similar issues of WebView white screens but none of the potential solutions work... here's my code:
import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
    Dimensions,
    Alert
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { WebView } from 'react-native-webview';

const App: () => React$Node = () => {
    const deviceHeight = Dimensions.get('window').height;
    const deviceWidth = Dimensions.get('window').width;
  return (
        <View style={{flex: 1}}>
            <WebView
                source={{ uri: 'https://lostlaowai.app:4432/?ID=1105T140W4iUserAgentAllow3' }}
                onError={syntheticEvent => {
                    const { nativeEvent } = syntheticEvent;
                    Alert.alert('WebView error: ', "" + nativeEvent);
                }}
                onHttpError={syntheticEvent => {
                    const { nativeEvent } = syntheticEvent;
                    console.warn(
                        'WebView received error status code: ',
                        nativeEvent.statusCode,
                    );
                }}
                mixedContentMode={'always'}
                geolocationEnabled={true}
                ignoreSslError={true}
                javaScriptEnabled={true}
                domStorageEnabled={true}
                scalesPageToFit={true}
                startInLoadingState={false}
                style={{flex: 1, width: deviceWidth, height: deviceHeight}}
            />
        </View>
  );
};

export default App;

My specs:
react-native-cli: 2.0.1
react-native: 0.61.2
node: v10.16.3
Device: Xiaomi Note
Any help would be appreciated!


text:
Q: One fancybox window position on the top Is there any chance to set position of Fancybox but only one window (to search). Beacase on page I am using Fancybox to show for example photos, map and windows for them and they are in the middle center of page, but I wanna just have this one - for searching on the top...
I have code:

 <form role="search" title="Searching" method="get" id="searchform" class="searchform" action="<?php bloginfo("url"); ?>">
 Search <input type="text" value="Write search fraze" name="s" id="s" onFocus="this.value='';" />
 </form>


text:
Q: Steam won't launch my games...Ubuntu 15.04 x64 After I press Play for War thunder this is what I get in the terminal.
WarThunder Updater version 1.0.7
Looking for a new version...
Checking game version...
Checking files... 100%
Running /home/sean/.local/share/Steam/steamapps/common/War Thunder/aces
ERROR: ld.so: object '/home/sean/.local/share/Steam/ubuntu12_32/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
Setting breakpad minidump AppID = 236390
Steam_SetMinidumpSteamID:  Caching Steam ID:  76561198131518133 [API loaded no]
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
ERROR: ld.so: object '/home/sean/.local/share/Steam/ubuntu12_32/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
Critical error

Videomode initialization error. [8111000B]

Visit <a href=https://support.gaijin.net/hc/en-us/search?utf8=%E2%9C%93
ERROR: ld.so: object '/home/sean/.local/share/Steam/ubuntu12_32/gameoverlayrenderer.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.

I also press Play on Besiege and a small window says preparing to launch Besiege and nothing happens after that.  Please help.

A: Had an issue similar to this not so long ago on another system. The only way we could get the thing to work was to delete most of the files in the Steam folder and then download them again. If you do try this, make sure you do a backup first though.

A: I had Steam issues with an older Ubuntu build and disabling the Steam overlay resolved them. That bug very well may have been resolved since then as it was some time ago.
Not that it helps, but I think it was running through WINE when I experienced that.