text:
Q: LUA: trying to remove a value from a table when it is found in another table I'm trying to delete a key and value from a table when it is found in another table. I've been using this so far but although it recognizes the duplicate, it always removes the last item in the table...
function get_key_for_value( t, value )
 for k,v in pairs(t) do
 if v==value then return k
 end
 return nil
 end
 end

 for k,v in pairs (Iranian_Protected_Groups) do
 v[6] = 0
 if Springfield_3_Target_Name == v[2] then
 v[6] = v[6] + 1
 if v[6] > 0 then
 local Key_To_Remove = get_key_for_value (Iranian_Protected_Groups, v)
 MESSAGE:New( "Shared target is "..v[2], 40):ToBlue()
 table.remove (Iranian_Protected_Groups, Key_To_Remove)
 end
 end
 end

any help would be appreciated!

A: First, you should format your code using standard indentation to make it easier to parse as a human reading the code:
function get_key_for_value(t, value)
    for k, v in pairs(t) do
        if v == value then
            return k
        end
        return nil
    end
end

Look carefully at the for loop. You will never get past the first iteration, because every iteration returns.
Your function is fixed if you move your return nil statement outside the loop. (Though for most purposes, is redundant, because generally no value is equivalent to returning nil).
Before, Key_To_Remove was nil. When passing nil as the index to remove in table.remove, Lua removes the last element. This is convenient when treating a list like a stack, but hid a bug for you in this case.


text:
Q: Incorrect syntax near 'Ordertb' I want to refresh and update gridview so I use showData() like this:
protected void ShowData()
{
    con.Open();
    string qu = string.Format("SELECT * Ordertb", con);
    SqlDataAdapter da = new SqlDataAdapter(qu, con);
    DataSet ds = new DataSet();
    da.Fill(ds, "ordertbl");
    if (ds.Tables["ordertbl"].Rows.Count > 0)
    {
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataSourceID = null;
        GridView1.DataBind();
    }
    con.Close();
}

but I get this error:
Incorrect syntax near 'Ordertb'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'Ordertb'.

A: Try this SQL query:
Select * From Ordertb

In your code:
string qu = string.Format("Select * From Ordertb", con);

A: It looks like you're missing the keyword 'from' before Ordertb.
string qu = string.Format("SELECT * FROM Ordertb", con);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Real_escape_string prevents INSERT statement from working MYSQL PHP So I'm making my own blog scripts using MYSQL and PHP.
I had the whole 'writing the blog to a database' thing working perfectly, until I realised that if you tried to write a blog with speech marks, this would prevent the INSERT statement from working (obviously - the speechmarks were ending the SQL statement).
So I tried to use real_escape_string, and now the INSERT doesn't work even if you exclude quotes.
I tried using:
sqlstate

in order to find out the issue, and it returned "42000" - which, after googling for a little bit, refers to a syntax error, which doesn't make much sense as there is no syntax error before the use of real_escape_string.
Also, I'm now getting this error:
 Call to a member function close() on a non-object in /postarticle.php on line 37

Which refers to the close() call in the ELSE statement.
Please may you help? Been going round in circles for a while. Here is my code:
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'CENSORED';

$connection = new mysqli($host,$user,$pass,$db);

$_SESSION["article"] = $_POST["article"];
$date_of_blog = getdate();

$article = ($_SESSION["article"]);

$sql1 = "SELECT * FROM `Blogs`";
$res1 = $connection->query($sql1);
$newrows = $res1->num_rows + 1;

$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES ('$newrows','$article','$date_of_blog')";
$sql2 = $connection->real_escape_string($sql2);
$res2 = $connection->query($sql2);

if ($res2->num_rows == $newrows)
{
    $res->close();
    $connection->close();
    header( 'Location: adminpanel.php' );

}
else
{

echo ($connection->sqlstate);
$connection->close();
$res->close();
}

exit();

?>

Also, on a side note, the getdate() call that I've got has never worked. In the database every blog post comes up as:
    0000:00:00 00:00:00
EDIT:
Issue is now solved. Find the functional code below:
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'CENSORED';

$connection = new mysqli($host,$user,$pass,$db);

$_SESSION["article"] = $_POST["article"];

$article = ($_SESSION["article"]);

$article = $connection->real_escape_string($article);

$sql1 = "SELECT * FROM `Blogs`";
$res1 = $connection->query($sql1);
$newrows = $res1->num_rows + 1;

$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES (\"$newrows\",\"$article\",CURDATE())";
$res2 = $connection->query($sql2);

if ($res2 != false)
{
    header( 'Location: adminpanel.php' );
}
else
{
    echo ($connection->sqlstate);
}
$connection->close();
$res->close();

exit();

?>

I'm very sorry if these questions are basic and annoy the professionals around here; I've tried to follow the guidelines and I've googled for a while etc. I just haven't found any solutions that match my issue(s).
Thankyou for your time.

A: There are a number issues with the code as originally posted. Chiefly, the cause of the two issues you initially identified is a misuse of mysqli::real_escape_string().  It needs to be called on each variable individually which appears in the code.  So instead of calling it on the whole statement, it must be called multiple times for multiple variables like:
$article = $connection->real_escape_string($connection);

The failure of the query due to incorrect quoting (due to real_escape_string()) is the reason for the error message calling close().
As ascertained in the comments, you are using num_rows + 1 to validate that one new row has been inserted based on the previous number of rows returned. This is problematic for a few reasons. Mainly, it exposes a race condition wherein a row may be inserted from two sessions at once and one or both will fail because the expected value for $newrows doesn't match.  Really BlogID should be an auto_increment column in your database. That eliminates the need for any logic around it whatsoever. You don't even need to include it in the INSERT because it will be automatically incremented.
That also completely eliminates the need for the first SELECT statement.
Substituting MySQL's native NOW() function for the date value, you can simplify the statement to:
INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())

To test success or failure of the insert, you just need to verify that its variable is not false.
Putting this together, your code can be reduced as:
if (!isset($_POST['article'])) {
   // exit or handle an empty post somehow...
}
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];

// Escape $article for later use
$article = $connection->real_escape_string($_SESSION["article"]);

// Only an INSERT is needed. $article is already escaped
$sql = "INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())";
// Run the query
$res = $connection->query($sql);

// Test for failure by checking for a false value
if ($res) {
  // The connection & resource closure can be omitted
  // PHP will handle that automatically and implicitly.
  header( 'Location: adminpanel.php' );
  // Explictly exit as good practice after redirection
  exit();
}
else {
  // The INSERT failed. Check the error message
  echo $connection->error;
}

This should bring your current code into working order. However, since you're learning this it is an excellent time to begin learning to use prepared statements via prepare()/bind_param()/execute() in MySQLi.  This is a recommended best practice to prevent SQL injection, although using real_escape_string() works as long as you use it correctly and never forget.
See How can I prevent SQL injection in PHP for examples.
But it would look like:
// connection already established, etc...
// Prepare the statement using a ? placeholder for article
$stmt = $connection->prepare("INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES (?, NOW())");
if ($stmt) {
  // bind in the variable and execute
  // Note that real_escape_string() is not needed when using
  // the ? placeholder for article
  $stmt->bind_param('s', $_SESSION['article']);
  $stmt->execute();

  // Redirect
  header( 'Location: adminpanel.php' );
  exit();
}
else {
  echo $connection->error;
}

A: You need to apply the real_escape_string function to the variables not the entire SQL string.
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES ('".$connection->real_escape_string($newrows)."','".$connection->real_escape_string($article)."','".$connection->real_escape_string($date_of_blog)."')";

The purpose is to remove anything that might be misinterpreted as query functions by MySQL, but there are parts of the query that you obviously want to be interpreted as such.


text:
Q: ES6: fire React function This is the code:
class Seismo extends Component {

  constructor(props) {
    super(props);
    this.state = {
      news: ""
    }
    this.updateNews = this.updateNews.bind(this)
  }

  updateNews = () => {
    console.log('test')
  }

What I am trying to do is to fire the updateNews code from render:
render() {
    return (
      <Button
          type="primary"
          onClick={async () => {
              this.updateNews // This is what I am trying to fire!
          }
      >TEST</Button>

But keep getting this error:

Uncaught Error: this.updateNews is not a function

A: You were not calling the functuion
      <Button
          type="primary"
          onClick={async () => {
              this.updateNews() // This is what I am trying to fire!
          }
      >TEST</Button>

Note:
You do need to bind because you use arrow function.


text:
Q: Several apps which draw view over other apps with help Accessibility service doesn't work at the same time I have two Accessibility services in two different apps on a device. Each of them draws some view over other apps. I faced with the following problem: when 2 Accessibility services are enabled, only one draws view, another one doesn't get any events.
Configuration for events is following:
 @Override
 protected void onServiceConnected() {
    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
    info.feedbackType = AccessibilityEvent.TYPES_ALL_MASK;
    info.notificationTimeout = TIMEOUT_IN_MS;
    setServiceInfo(info);
    super.onServiceConnected();
 }

I can reproduce it on pre-Lollipop Android version, also on Android M. Whilst on Android O and N, all services work fine.
Could somebody please explain to me how it can happen, maybe there are some improvements starting from Android N?
If there is a way to make them work at the same time, could you please provide me an implementation of this?

A: You actually simply can't run two accessibility services at a time Pre Android N. One will always crash, and create a stale/daemon service that runs in the background, preventing you from restarting the service that crashed. This independent of how the service functions and what it does. In fact, even the fake UIAutomation service that runs with Android Instrumentation tests will cause a running service to crash. There is no way around this limitation.


text:
Q: How can I get the last element of each line in perl? I have to get the last element in each line. I am using perl..
 1.25.56.524.2
 2.56.25.254.3
 2.54.28.264.2

A: Just split each line on a dot, last element has the index -1:
print +(split /\./)[-1] while <>;

A: I assume by last element you mean the last value separated by .. Have a look at this code:
use strict;
my @last_values;                        # UPDATE: initialize array
for my $line (<DATA>) {                 # read line by line
    chomp $line;                        # remove newline at the end
    my @fields = split '\.', $line;     # split to fields
    my $last = pop @fields;             # get last field
    print $last."\n";
    push @last_values, $last;           # UPDATE: store last field in array
}

__DATA__
1.25.56.524.2
2.56.25.254.3
2.54.28.264.2

Output:
2
3
2

A: One possibility would be:
use strict;
use warnings;

my @Result;                 # Array holding the results

while (<DATA>)              # whatever you use to provide the lines...
{
  chomp;                    # good practice, usually necessary for STDIN
  my @Tokens = split(/\./); # assuming that "." is the separator
  push( @Result , $Tokens[-1] );
}

__DATA__
1.25.56.524.2
2.56.25.254.3
2.54.28.264.2


text:
Q: Use require.js with angular.js I am new in require.js, I am implementing requier.js with angular.js, but i got error. Here is my code:
config file:
require.config({
    paths: {
        angular: 'https://code.angularjs.org/1.5.5/angular.min',
        angularRoute: '//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.min',
        angularAnimate: '//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min',

    },
    shim: {
        'angular' : {'exports' : 'angular'},
        'angularRoute': ['angular'],
        'angularAnimate': ['angular']
    },
    priority: [
        "angular"
    ],
});

require([
    'angular',
    'app',
    'controllers/first-controller',
        'controllers/second-controller',
        'controllers/third-controller',
        'services/services',
        'directives/directives'
    ], function(angular, app) {
        var $html = angular.element(document.getElementsByTagName('html')[0]);
        angular.element().ready(function() {
            // bootstrap the app manually
            angular.bootstrap(document, ['WalletHubApp']);
        });
    }
);

This is my app file:
define(['angular'], function (angular) {
    var app = angular.module('app', ['ui.router','ngAnimate']);

WalletHubApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/walletHub/1/');

    $stateProvider

        .state('test', {
            url: '/walletHub/:id/{folderPath:[a-zA-Z0-9/]*}',
           templateUrl: function ($stateParams){
                return  "templates/"+$stateParams.id + '.html';
                },
            controllerProvider: function($stateParams) {
                console.log($stateParams)
              var ctrlName = $stateParams.id + "Controller";
              return ctrlName;
          }
        });

    });
 return app;
});

This is Controller File:
define(['app'], function(app) {
    WalletHubApp.controller('1Controller', function ($scope,$stateParams,$stateParams,$state,$http) {
 $http.get('sample.json')
       .then(function(res){
         $scope.persons = res.data
        });

    var parts = $stateParams.folderPath.split('/')
    $scope.params = false;
    if(parts[0] != "")
    {
        $scope.parts = parts;
        $scope.params = true;

    }
  })
return;
});

I dont know what is wrong in this code.Please help me to sort out this

A: According to official document

It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names.

// in app.js file, remove module name :

    define(["angular", "angularRoute","angularAnimate"], function(angular) {
        var WalletHubApp = angular.module('WalletHubApp', ['ui.router','ngAnimate']);

        WalletHubApp.config(function($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise('/walletHub/1/');

        $stateProvider

            .state('test', {
                url: '/walletHub/:id/{folderPath:[a-zA-Z0-9/]*}',
               templateUrl: function ($stateParams){
                    return  "templates/"+$stateParams.id + '.html';
                    },
                controllerProvider: function($stateParams) {
                    console.log($stateParams)
                  var ctrlName = $stateParams.id + "Controller";
                  return ctrlName;
              }
            });

        });
     return WalletHubApp;
    });

// in controller file change WalletHubApp to app

define(['app'], function(WalletHubApp) {
    WalletHubApp.controller('1Controller', function ($scope,$stateParams,$stateParams,$state,$http) {
 $http.get('sample.json')
       .then(function(res){
         $scope.persons = res.data
        });

    var parts = $stateParams.folderPath.split('/')
    $scope.params = false;
    if(parts[0] != "")
    {
        $scope.parts = parts;
        $scope.params = true;

    }
  })
return;
});


text:
Q: Would you say "She had nothing to do except spending money"? From two sentences I've written below, the first one is positively correct as it's cited from Longman dictionary. The grammatical validity of the second one, however, seems rather dubious knowing the other sentence already proved valid (if I didn't know that the first sentence is correct, I would say that the second one makes more sense to me and so it'd be the only correct version). Please let me know if the second sentence is correct.

She had nothing to do except spend money.
She had nothing to do except spending money.

A: The second sentence is not correct.
You could say "She wasn't doing anything except spending money".
The verbs should match, I believe.

A: I guess you would be aware with parallelism. Note the following sentences:

Incorrect- She visits the stores and spending money.
Correct- She visits the stores and spends money.
Correct- She is visiting the stores and spending money.

So, your 1st sentence is correct. To make your 2nd sentence correct, we would reframe it like-'She had been doing nothing except spending money.'


text:
Q: Book Series identification, late 80s, early 90s I read a series of 5 novels that began with a space pirate kidnapping a woman from Earth, using her horribly, selling her or perhaps losing her to anothe pirate and her tale grew more awful... Each time you thought her plight could not get worse, the author twisted it more. The protagonist also went through many trials by the end of the series. The protagonist's name was Nick and I don't recall her name. She did eventually triumph.
Anyone know? TIA if so!

A: That would be The Gap Cycle by Stephen Donaldson. Summary of the first book:

On her first mission, Morn Hyland, an ensign in the United Mining Companies Police (UMCP), discovers that she suffers a rare psychosis called "gap sickness." Whenever her ship comes out of an FTL jump through "the Gap," she falls into a trance and feels compelled to activate any self-destruct or other sabotage within her reach. The first time her ship jumps, she destroys the police ship, killing the entire crew, including her own family. She survives the wreck only because a vicious pirate named Angus Thermopylae finds her when he boards looking for salvage. In order to neutralize her gap sickness and exploit her for his own ends, Angus places a "zone implant" in her brain -- a remotely controlled electrode which allows Angus to control Morn's every feeling and action. Angus uses the zone implant to repeatedly rape and abuse her. Misuse of a zone implant is a capital crime, Angus risks execution if he is discovered, but hopes the zone implant itself will prevent Morn from exposing him. When they arrive at Com-Mine, the nearest space station, Morn makes contact with another pirate — Nick Succorso, captain and owner of the ship Captain's Fancy, who she sees as a potential rescuer. Morn and Nick collude to frame Angus for stealing station supplies. However, before he is arrested, Angus asks Morn to smuggle the implant's remote control off the station. During her captivity, Morn has become addicted to the artificial stimuli only the implant can provide; because of her addiction, she is unable to turn down Angus' offer. Rather than turn herself in to the police for treatment, she conceals the existence of her implant. With her own controls in her possession, Morn is effectively a superwoman and is able to disregard fear, pain, or fatigue; however, by continuing to use the zone implant on herself, she, like Angus, breaks the law against unauthorized use. Morn joins Nick's pirate crew to escape from police oversight, even concealing her implant from Nick himself. Because she left no evidence of Angus' real crimes, he is imprisoned for the theft of which he was framed, but is not executed for what he did to Morn. Although the series has at least one chapter each from over a dozen narrators, Morn, Angus, and their son Davies are main protagonists of the entire series.

One of the covers:


text:
Q: How do I get the effect of GNU tar's --strip-components with git-archive? In broad terms, what I'd like is a direct tar-to-tar transformation where the result's root contains only a particular directory-subtree of the original.
To illustrate with an example, say I want only the gitweb directory from git's repository. Running
$ git archive --prefix=git-gitweb/ master gitweb | tar tf -
gives
git-gitweb/
git-gitweb/gitweb/
git-gitweb/gitweb/INSTALL
git-gitweb/gitweb/Makefile
git-gitweb/gitweb/README
git-gitweb/gitweb/gitweb.perl
git-gitweb/gitweb/static/
git-gitweb/gitweb/static/git-favicon.png
git-gitweb/gitweb/static/git-logo.png
git-gitweb/gitweb/static/gitweb.css
git-gitweb/gitweb/static/gitweb.js
but I want
git-gitweb/
git-gitweb/INSTALL
git-gitweb/Makefile
git-gitweb/...
The manual provides for extra backend-specific options, but attempting to pass --strip-components produces an error:
$ git archive --prefix=git-gitweb/ --strip-components=1 master gitweb | \
  tar tf -
error: unknown option `strip-components=1'
usage: git archive [options]  [...] ...
The tar backend isn't GNU tar anyway.
Someone in freenode's #gnu channel suggested Tardy, but it doesn't understand the output of git-archive:
$ git archive master > old.tar
$ tardy old.tar new.tar
tardy: old.tar: file type ``g'' unknown
Yes, I could extract the output of git-archive with --strip-components and create a new archive of the result, but I'm trying to avoid using the filesystem as a temporary variable.

A: Archive that directory as the CWD and you won't have the extra path component:
(cd gitweb; git archive --prefix=git-gitweb/ master .) | tar tf -

Or use this syntax as suggested by the git-archive man page:
git archive --prefix=git-gitweb/ master:gitweb | tar tf -


text:
Q: Given that you added a new field to a 1-d slice of a structured array, why can you not set the entry of the new field to a list? The title may be a little bit confusing, so I hope I can make it clearer with the help of an example. Image I have a little helper function that adds new fields to already existing structured arrays:
import numpy as np

def add_field(a, *descr):
    b = np.empty(a.shape, dtype=a.dtype.descr + [*descr])
    for name in a.dtype.names:
        b[name] = a[name]
    return b

Given a structured array, I can simply use it to add new fields:
a = np.array(
    [(1, False), (2, False), (3, False), (4, True)],
    dtype=[('id', 'i4'), ('used', '?')]
)
print(a)
b = add_field(a, ('new', 'O'))
print(b)

I can then set an entry of the newly created field to an (empty) list without a problem:
b[0]['new'] = []

I can also create a new array which is only a slice of the original one and then add a new field to this new array:
c = a[0]
print(c)
d = add_field(c, ('newer', 'O'))
print(d)

BUT if I now try to set the new field to an (empty) list, it doesn't work:
d['newer'] = []

ValueError: assignment to 0-d array

Why is that? According to add_field, d is an entirely new array that happens to share the same fields and entries just like b did. Interestingly, the shape of b[0] is (), while the shape of d is (1,) (and also type(b) is np.void while type(d) is np.array). Maybe that has something to do with it? Also interestingly, all of this works:
d['newer'] = 1.34
d['newer'] = False
d['newer'] = None
d['newer'] = add_field
d['newer'] = set()
d['newer'] = {}
d['newer'] = {'test': []}

However, accessing the vaues in the last dict using the key 'test' does not:
>>> d['newer'] = {'test': []}
>>> d['newer']
>>> array({'test': []}, dtype=object)
>>> d['newer']['test']
>>> IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
>>> d['newer'][0]
>>> IndexError: too many indices for array

This is very confusing.
EDIT
Okay, I just tried to modify the add_field function like this:
def add_field(a, *descr):
    shape = a.shape if len(a.shape) else (1,)
    b = np.empty(shape, dtype=a.dtype.descr + [*descr])
    for name in a.dtype.names:
        b[name] = a[name]
    return b

But this didn't help:
>>> d = add_field(a[0], ('newer', 'O'))
>>> d
>>> array([(1, False, None)], dtype=[('id', '<i4'), ('used', '?'), ('test', 'O')])
>>> d.shape
>>> (1,)
>>> d['newer'] = []
>>> ValueError: cannot copy sequence with size 0 to array axis with dimension 1

So this was not it I guess. However this now works:
>>> d['newer'][0] = []

But I don't like this workaround. I would expect it to work the same as for b[0].
EDIT 2
If I modify the add_field function a little bit further, I can force the wanted behaviour, although I don't 100% like it:
def add_field(a, *descr):
    shape = a.shape if len(a.shape) else (1,)
    b = np.empty(shape, dtype=a.dtype.descr + [*descr])
    for name in a.dtype.names:
        b[name] = a[name]
    return b if len(a.shape) else b[0]

d = add_field(a[0], ('newer', 'O'))
d['newer'] = []

A: To summarize the comments:
The issue in the original question appears to be the shape of the returned object - when you do e.g.
c = a[0]

with a having shape (n,) you are not taking a slice from the array but a single element. c.shape then is (). When you pass an array of shape () into add_field then the new array created by
b = np.empty(a.shape, dtype=a.dtype.descr + [*descr])

will also have shape (). However, it is necessary for a structured array to have shape (n,) (though it is not outlined in the documentation).
As in the first edit to the question, the correct modification would be
def add_field(a, *descr):
    shape = a.shape if len(a.shape) else (1,)
    b = np.empty(shape, dtype=a.dtype.descr + [*descr])
    b[list(a.dtype.names)] = a
    return b

The returned object will then share the properties of a shape (n,) structured array in that:

*

*If you index the array at an integer position you get a structure (e.g. d[0])

*You can access and modify individual fields of a structured array by indexing with the field name (e.g. d['newer'])

With the above modification the behavior of d in the question is the same as b e.g.
d[0]['newer'] = []

is valid, as is
b[0]['new'] = []

This brings us to the real crux of the question:

Why can't we assign an empty list to each element of a field using the d['newer']=[] syntax?
    When you assign an iterable instead of a scalar using this syntax, numpy attempts an element-wise assignment (or a broadcast depending on the iterable). This differs from the assignment of a scalar wherein the scalar is assigned to every element of that field. The documentation is not clear on this point, but we can get a much more helpful error by using
b['new'] = np.array([])

Traceback (most recent call last):
  File "structuredArray.py", line 20, in <module>
    b['new'] = np.array([])
ValueError: could not broadcast input array from shape (0) into shape (4)

So the issue here isn't how the field is being added, but how you are attempting to assign an empty list to each element of that field. The correct way to do this would be something like
b['new'] = [[]*b.shape[0]]

which works as expected for structured arrays of both (1,) and (4,) shape:
import numpy as np

def add_field(a, *descr):
    shape = a.shape if len(a.shape) else (1,)
    b = np.empty(shape, dtype=a.dtype.descr + [*descr])
    for name in a.dtype.names:
        b[name] = a[name]
    return b

a = np.array(
    [(1, False), (2, False), (3, False), (4, True)],
    dtype=[('id', 'i4'), ('used', '?')]
)

b = add_field(a, ('new', 'O'))
b['new'] = [[]*b.shape[0]]
print(b)

c = a[0]
d = add_field(c, ('newer', 'O'))
d['newer'] = [[]*d.shape[0]]
print(d)

[(1, False, list([])) (2, False, list([])) (3, False, list([])) (4,  True, list([]))]
[(1, False, list([]))]


text:
Q: Select query from json format data I just want a select query where it can Select all user uid who have born after 1986 Year.
I tried this query but it only selects the matching number LIKE search.
SELECT uid FROM {profile_values} WHERE  value LIKE  '%1986%'

Here is the SQL query
CREATE TABLE IF NOT EXISTS `profile_values` (
  `fid` int(10) unsigned NOT NULL DEFAULT '0',
  `uid` int(10) unsigned NOT NULL DEFAULT '0',
  `value` text,
  PRIMARY KEY (`uid`,`fid`),
  KEY `fid` (`fid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `profile_values` (`fid`, `uid`, `value`) VALUES
(5, 1, 'a:3:{s:3:"day";s:2:"27";s:5:"month";s:1:"6";s:4:"year";s:4:"1986";}'),
(5, 3, 'a:3:{s:3:"day";s:2:"15";s:5:"month";s:1:"9";s:4:"year";s:4:"1910";}'),
(5, 4, 'a:3:{s:3:"day";s:2:"26";s:5:"month";s:1:"6";s:4:"year";s:4:"1986";}'),
(5, 5, 'a:3:{s:5:"month";s:1:"4";s:3:"day";s:2:"26";s:4:"year";s:4:"2014";}'),
(5, 6, 'a:3:{s:3:"day";s:2:"26";s:5:"month";s:1:"4";s:4:"year";s:4:"2014";}'),
(5, 7, 'a:3:{s:5:"month";s:1:"4";s:3:"day";s:2:"26";s:4:"year";s:4:"2014";}'),
(5, 8, 'a:3:{s:3:"day";s:2:"26";s:5:"month";s:1:"4";s:4:"year";s:4:"1987";}'),
(5, 17, 'N;'),
(5, 18, 'N;'),

A: You can try REGEXP. The REGEXP matching condition is similar to the LIKE but LIKE only performs simple pattern matching using the wildcards "%" and "_", REGEXP performs complex regular expression pattern matching allowing it to match a much greater range of string patterns than LIKE.
SELECT uid FROM {profile_values}
WHERE value REGEXP '[1][9][8][6-9]|[1][9][9][0-9]|[2-9][0-9][0-9][0-9]';

Well here we make sure that our expression considers only 4 digit number and moreover number should be greater than 1986
so [1][9][8][6-9] -->> makes sure number is between 1986 to 1989
next [1][9][9][0-9] -->> makes sure number is between 1990 to 1999
last [2-9][0-9][0-9][0-9] -->> makes sure number is between 2000 to 9999

please refer http://www.tutorialspoint.com/mysql/mysql-regexps.htm for more


text:
Q: Accessing "valueField" property of layer's symbology using ArcPy? This has been really hard to debug, as I had no idea where to look at first, but I have made an attempt to access the "valueField" property of a layer file.
This layer file is of the UNIQUE_VALUES symbology type (although I knew it, also successfully tested with code), and thus must have a read/write valueField property associated with it according to the Help (http://resources.arcgis.com/en/help/main/10.2/index.html#//00s30000005s000000).
However, as soon as I try to access it like:
valField = lyr.symbology.valueField

the script stops dead in its track. Not knowing exactly how to access it (there is only a write example in the Help), I also tried:
valField = lyr.symbology.valueField()

to no avail.
I then noticed in PyScripter, after further configuration of Pyscripter to allow auto-completion with arcpy, that there is no valueField property / method shown... See the first screenshot (no, it's not down the scrollable list). The second screenshot shows I have configured PyScripter properly, as you can see the arcpy auto-completion at work.
What am I missing? I am able to successfully access other properties like labelClasses.
ArcGIS 10.2.0 by the way...

A: This way it worked fine for me:

Try to get symbology in a separate line?

A: I could manage to do this by the help of: ArcPy (ArcMap): Modify Layer Symbology, Expanded.
But I'm still interested about the normal approach
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")

lyr =arcpy.mapping.ListLayers(mxd, "LayerName")[0] # Layer object, typically
from arcpy.mapping.ListLayers (arcpy._mapping.Layer)

# Example 1a: Modifying single-field renderer using undocumented _arc_object.renderer
old_field = "JOINEDTABLENAME.GRAFIKA" # New field name for
symbolizing layer
new_field = "FeatureClassname.GRAFIKA" # Old field name for symbolizing layer

sym_xml = lyr._arc_object.renderer
lyr._arc_object.renderer = sym_xml.replace(old_field, new_field)
arcpy.RefreshActiveView()


text:
Q: Memory allocation of interface I know interface cannot be instantiated, but if we assign it to an object, could anyone please explain how the memory gets allocated to it. For ex:
ITest obj = (ITest) new TestClass1();  //TestClass1 is a class which implements ITest
obj.MethodsDefinedInInterface();

Does ITest converts to object to save properties and methods of TestClass1.

A: I'm not sure exactly what you mean by 'allocation'.  The following statement makes two seperate 'allocations':
TestClass1 test = new TestClass1();

First is the new TestClass1() statement which allocates sizeof(TestClass1) on the heap.  Second, the assignment of the address of the heap allocation is stored in the variable test, which is allocated on the stack as sizeof(object *) (i.e. IntPtr.Size, or 32/64 bits based on the hardware+OS+software running).
The following statement is EXACTLY the same in 'allocations':
ITest test = new TestClass1();

The only difference between the two is the methods available to be called on the variable test.
Note: This is NOT true with a structure that implements an interface.  Interfaces must be a reference type, and as you know, structs are not.  This is called boxing in .NET and allows a struct to be referenced as if it were a reference type by first placing a copy of the struct on the heap.
So we now re-evaluate the statement:
TestSTRUCT1 test2 = new TestSTRUCT1();

This 'allocates' sizeof(TestSTRUCT1) on the stack at the named variable test2.  (Not sure what the impact of the assignment to new TestSTRUCT1() is, it may create an additional stack copy but that should be removed immediately after the assignment.
If we then assign this value to an interface:
ITest test3 = test2;

We have now made two more allocations.  First the structure is copied to the heap.  Then the address of that heap-resident structure is placed in a newly 'allocated' variable test3 (on the stack).

A: It should be similar to:
TestClass1 test = new TestClass1();
ITest obj = (ITest) test;
obj.MethodsDefinedInInterface();

Which, I think, answers your question.

A: Memory gets allocated for the object that impliments interface like any other object.  whether or not it impliments an interface is just a property of the object

A: Memory is allocated only for TestClass1 instance. Interface ITest is only a type of reference, which points to that allocated memory.

A:
Does ITest converts to object to save properties and methods of TestClass1

ITest is a type. TestClass1 properties and methods are still there just you cannot access it via obj variable.

A: Its quite simple acutally. You allocate for TestClass1 and then cast it back to the interface. Note that you're not instantiating a interface, you're instantiating a class that implements the interface and then calling the interface method which is implemented (obligatorily) in the concrete class!
another way to put it is:
TestClass1 test = new TestClass1();
ITest obj = (ITest) test;
obj.MethodsDefinedInInterface();

note that the allocated area is for TestClass1! it not grow or shrink because of the cast!

A: interfaces simply make sure that objects meet a cerain criteria both tecnically and logically at compile time.
When executing the code and using an interface memory will be allocated as if you would just instantiate the object using the class.
So there's no difference (in terms of memory allocaton) between
ITest obj = (ITest) new TestClass1();  //TestClass1 is a class which implements ITest
obj.MethodsDefinedInInterface();

and
TestClass1 obj = new TestClass1();  //TestClass1 is a class which implements ITest
obj.MethodsDefinedInInterface();

A: So, first, when you enter this method space will be allocated on the stack for all parameters, if applicable, the return value, if applicable, and all local variables for that method.  For what we've shown here the only local variable that needs to be allocated is obj.  obj is an interface, and so requires enough space for a single reference (32 bits on 32 bit systems, 64 bits on 64 bit systems).  Since there are no other local variables, return values, or parameters, we will only take up that one word on the stack.
Because we're allocating a single object (new TestClass1()) and assuming that object is a class (and not a struct, because naming a struct TestClass1 would be very mean) enough space will be allocated on the heap to account for a single instance of TestClass.  That space will be enough space for every single field (regardless of accessibility) plus a little extra for some object overhead.  A reference to this newly allocated object will go in the spot on the stack that is allocated for our local variable.
This is all ignoring the registers utilized by the processor at runtime; due to the complex transformations and optimizations of compilers, jitters, operating systems, processor hardware, etc. I couldn't begin to try to predict what that would take.  Fortunately, thanks to all of those abstractions, I don't really need to care.


text:
Q: NodeJS - Run seperate functions depending on OS (Closed) How do we run seperate functions based on the users Operating System?
I have two functions for returning relative paths to given files by searching for them recursively within subdirectories of given working directory's.
I have one for Windows, see below..
WINDOWS variant
console.log("Locating File...");
exec('set-location ' + folder + ';' + ' gci -path ' + folder + ' -recurse -filter ' +
file + ' -file | resolve-path -relative', { 'shell':'powershell.exe' }, (error, stdout, stderr) => {
      var filePath = stdout.substring(stdout.indexOf(".\\") + 2).trim("\n");
      if (error !== null) {
          console.log("Cannot Locate the file...");
          return;
      }

And one for Linux & macOS, see below...
LINUX/OSX variant
console.log("Locating File...")
console.log();
exec('find -name "' + file + '"', { cwd: folder }, (error, stdout, stderr) => {
      var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");
      if (error !== null) {
          console.log("Cannot Locate the file...");
          return;
      }

I want to execute these functions based on the users Operating System if that's possible?
I've had a look at the StackOverflow question..
How do I determine the current operating system with Node.js
which is how I found out how to detect the current user OS, as well as the StackOverflow Question..
python: use different function depending on os.
Aside from the 2nd issue referenced being for python, I am basically trying to achieve the same thing from the 2nd issue but with nodeJS, by using the solution from the 1st issue.
My latest attempt was the following below, but for some reason it doesn't return anything but a blank console.
const fs = require("fs");
const platform = require("process");
const path = require("path");
var exec = require("child_process").exec

var folder = "just/some/folder/location"
var file = "file.txt"

// Windows process
if (platform === "win32") {
  console.log("Locating File...");
  exec('set-location ' + folder + ';' + ' gci -path ' + folder + ' -recurse -filter ' +
  file + ' -file | resolve-path -relative', { 'shell':'powershell.exe' }, (error, stdout, stderr) => {

        // relative path output for Windows
        var filePath = stdout.substring(stdout.indexOf(".\\") + 2).trim("\n");
        if (error !== null) {
            console.log("Cannot Locate the file...");
            return;

        } else if (process.platform === "linux" + "darwin") {

            // Linux & Unix process
            console.log("Locating File...")
            console.log();
            exec('find -name "' + file + '"', { cwd: folder }, (error, stdout, stderr) => {

                  // relative path output for Linux & macOS
                  var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");
                  if (error !== null) {
                      console.log("Cannot Locate file... \n\n" + error);
                      return;
                  };

                      console.log("found file: " + filePath);

                      // Read the file and show it's output to confirm everything ran correctly.
                      fs.readFile(path.join(folder, file), (error, data) => {
                          if (error) {
                              console.log("error reading file \n\n" + error);
                              return;
                          }
                      });

             });
        };
   });
};

A: Problem solved, after doing a bit of research, I was using if else else if statements & process.platform wrong...
First, when I was declaring process.platform I was using...
const platform = require("process");

when according to process.platform documentation for CJS it should be...
const { platform } = require("node:process");

Second, I was using if else else if statements wrong!
In my issue stated above I was using if else else if statements with process.platform like so..
} else if (process.platform === "linux" || "darwin") {
    // Linux & macOS code to execute
}

which was completely wrong!
I should have been using if else else if statements with process.platform like so...
if (process.platform === "win32") {

    // Windows code to be executed!

} else if (process.platform === "linux") {

    // Linux Code to be executed!

} else {
    process.platform === "darwin";

    // macOS Code to be executed!

}

I've managed to produce the following code which works on Windows, Linux and macOS closest to the way I need it to.
Hopefully this helps anyone new to JS like me.
const fs = require("fs");
const { platform } = require("node:process");
const path = require("path");
var exec = require("child_process").exec

var folder = "just/some/folder/location"
var file = "file.txt"

// Windows Process
if (process.platform === "win32") {

    // executes Powershell's "set-location" & "gci" commands...
    //...to locate a given file recursively...
    //...and returns its relative path from inside the given...
    //...working directory's subdirectories.
    exec('set-location "' + '"' + folder + '"'
    + ';' + ' gci -path ' + '"' +  folder  + '"'
    + ' -recurse -filter ' + '"' + file + '"' +
    ' -file | resolve-path -relative', (error, stderr, stdout) => {

        // sets the relative file path from ".\this\way\to\the\file.txt",
        // to "this\way\to\the\file.txt".
        var filePath = stdout.substring(stdout.indexOf(".\\") + 2).trim("\n");

        // throw an error if the file isnt found at all!
        if (error !== null) {
            console.log("Cannot locate the given file... \n" + error);
            return;
        };

        // read the file after it's been found.
        fs.readFile(path.join(folder, filePath), 'utf8', (error, data) => {
            if (error) {
                console.log("There was a problem reading the given file... \n" + error);
                return;
            };

            // Then print the data from fs.readFile...
            //...to confirm everthing ran correctly.
            console.log(data);

        });

    });

} else if (process.platform === "linux") {

        // executes findUtil's "find" command...
        //...to locate a given file recursively...
        //...and return its relative path from inside the given...
        //...working directory's subdirectories.
        exec('find -name "' + file + '"', { cwd: folder }, (error, stderr, stdout) => {

        // sets the relative file path from "./this/way/to/the/file.txt",
        // to "this/way/to/the/file.txt".
        var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");

        // throw an error if the file isnt found at all!
        if (error !== null) {
            console.log("Cannot locate the given file... \n" + error);
            return;
        };

        // read the file after it's been found.
        fs.readFile(path.join(folder, filePath), 'utf8', (error, data) => {
            if (error) {
                console.log("There was a problem reading the given file... \n" + error);
                return;
            };

            // Then print the data from fs.readFile...
            //...to confirm everthing ran correctly.
            console.log(data);

        });

    });

} else {

    // Uses APPLES built BSD findUtils 'find' command to locate the file inside the folder and subdirectories
    exec('find ' + '"' + apkFolder + '"' + ' -name ' + '"' + file + '"', (error, stderr, stdout) => {

        // sets the relative file path from "./this/way/to/the/file.txt",
        // to "this/way/to/the/file.txt".
        var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");

        // throw an error if the file isnt found at all!
        if (error !== null) {
            console.log("Cannot locate the given file... \n" + error);
            return;
        };

        // read the file after it's been found.
        fs.readFile(path.join(folder, filePath), 'utf8', (error, data) => {
            if (error) {
                console.log("There was a problem reading the given file... \n" + error);
                return;
            };

            // Then print the data from fs.readFile...
            //...to confirm everthing ran correctly.
            console.log(data);

        });

    });
}


text:
Q: How to sort an Access DB Table, via VBA, displayed in order when opened by using the Navigation Pane As an end of some inserts, via VBA script, I have been doing in an ACCESS table. I have as a requirement to order the table by a field. So a third person would open it via the ACCESS Navigation Pane and it would be shown in the specified order.
EDIT: I also need that table to be writable by this third person.
I can think about creating a new table, using an SQL sentence to order it. But it seems like a very ugly option.
Is there any way to archive it using a DAO object or other VBA approach?

A: A query which sorts the table is the cleanest solution.
If you don't want to create an extra object for that, you can set the table sorting with DAO properties like this:
Sub DoIt()

    Call TableSetSort("myTable", "myField")

End Sub

' Set a table to be sorted by <sFieldname>
Public Sub TableSetSort(sTable As String, sFieldname As String)

    Dim DB As Database
    Dim tdf As TableDef
    Dim prop As DAO.Property

    Set DB = CurrentDb
    Set tdf = DB.TableDefs(sTable)

    ' Set field to order by
    Call TableAddProperty(tdf, "OrderBy", dbText, sFieldname)
    ' These two may be true by default, but better safe than sorry
    Call TableAddProperty(tdf, "OrderByOn", dbBoolean, True)
    Call TableAddProperty(tdf, "OrderByOnLoad", dbBoolean, True)

    ' if you want to debug
    For Each prop In tdf.Properties
        Debug.Print prop.Name, prop.Value
    Next prop

End Sub

' Set or add a property in a TableDef
Public Sub TableAddProperty(tdf As DAO.TableDef, sName As String, iType As DAO.DataTypeEnum, vValue As Variant)

    Dim prop As DAO.Property

    ' Try to set the property value, this will fail with Runtime Error 3270 if the property doesn't exist
    On Error Resume Next
    tdf.Properties(sName) = vValue

    If Err.Number = 3270 Then
        ' Property doesn't exist yet - create and append it
        On Error GoTo 0
        Set prop = tdf.CreateProperty(sName, iType, vValue)
        tdf.Properties.Append prop
    End If
    ' Note: error handling here is quite minimal!

End Sub


text:
Q: Quake 3 BSP Renderer Drawing Random Vertices Recently I've been writing a game engine in OpenGL and have a question. When I generate my BSP file (Quake 3), it generates very odd vertices!! I've checked the vertex vector, heres a screenshot of what it contains (it repeats itself)

I've checked glGetError, and it returns nothing (zero)! I'm really stumped here, and I have no idea what to do.
Here is my code:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/vec3.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include "map.h"
#include <fstream>
#include <memory>
#include "game_manager.h"

std::vector<BSPVerts> vertexes;

bool KikoBSP::load_map(std::string file_name)
{
    this->file.open(file_name.c_str(), std::ios::in | std::ios::binary);

    if (this->file.is_open())
    {
        this->file.read(reinterpret_cast<char*>(&this->header), sizeof(this->header));

        BSPEntities* ents = new BSPEntities;
        ents->ents_array = new char[this->header.lumps[BSPLUMPS::ENTITIES].length];

        this->num_textures = this->header.lumps[BSPLUMPS::TEXTURES].length / sizeof(BSPTexture);
        this->num_planes = this->header.lumps[BSPLUMPS::PLANES].length / sizeof(BSPPlane);
        this->num_textures = this->header.lumps[BSPLUMPS::TEXTURES].length / sizeof(BSPTexture);
        this->num_nodes = this->header.lumps[BSPLUMPS::NODES].length / sizeof(BSPNode);
        this->num_leafs = this->header.lumps[BSPLUMPS::LEAFS].length / sizeof(BSPLeaf);
        this->num_leaf_faces = this->header.lumps[BSPLUMPS::LEAF_FACES].length / sizeof(BSPLeafFace);
        this->num_leaf_brushes = this->header.lumps[BSPLUMPS::LEAF_BRUSHES].length / sizeof(BSPLeafBrush);
        this->num_models = this->header.lumps[BSPLUMPS::MODELS].length / sizeof(BSPModel);
        this->num_brushes = this->header.lumps[BSPLUMPS::BRUSHES].length / sizeof(BSPBrush);
        this->num_brush_sides = this->header.lumps[BSPLUMPS::BRUSHSIDES].length / sizeof(BSPBrushSides);
        this->num_vertexes = this->header.lumps[BSPLUMPS::VERTEXES].length / sizeof(BSPVerts);
        this->num_meshverts = this->header.lumps[BSPLUMPS::MESHVERTS].length / sizeof(BSPMeshVerts);
        this->num_effects = this->header.lumps[BSPLUMPS::EFFECTS].length / sizeof(BSPEffects);
        this->num_faces = this->header.lumps[BSPLUMPS::FACES].length / sizeof(BSPFaces);

        for (int32_t x = 0; x < this->num_vertexes; x++)
        {
            vertexes.push_back(*reinterpret_cast<BSPVerts*>(&x));
        }

        for (int32_t x = 0; x < this->num_textures; x++)
        {
            this->textures.push_back(*reinterpret_cast<BSPTexture*>(&x));
        }

        for (int32_t x = 0; x < this->num_meshverts; x++)
        {
            this->mesh_verts.push_back(*reinterpret_cast<BSPMeshVerts*>(&x));
        }

        for (int32_t x = 0; x < this->num_planes; x++)
        {
            this->planes.push_back(*reinterpret_cast<BSPPlane*>(&x));
        }

        for (int32_t x = 0; x < this->num_nodes; x++)
        {
            this->nodes.push_back(*reinterpret_cast<BSPNode*>(&x));
        }

        for (int32_t x = 0; x < this->num_leafs; x++)
        {
            this->leaf.push_back(*reinterpret_cast<BSPLeaf*>(&x));
        }

        for (int32_t x = 0; x < this->num_faces; x++)
        {
            this->faces.push_back(*reinterpret_cast<BSPFaces*>(&x));
        }

        for (int32_t x = 0; x < this->num_leaf_faces; x++)
        {
            this->leaf_faces.push_back(*reinterpret_cast<BSPLeafFace*>(&x));
        }

        for (int32_t x = 0; x < this->num_leaf_brushes; x++)
        {
            this->leaf_brush.push_back(*reinterpret_cast<BSPLeafBrush*>(&x));
        }

        for (int32_t x = 0; x < this->num_models; x++)
        {
            this->model.push_back(*reinterpret_cast<BSPModel*>(&x));
        }

        for (int32_t x = 0; x < this->num_brushes; x++)
        {
            this->brushes.push_back(*reinterpret_cast<BSPBrush*>(&x));
        }

        for (int32_t x = 0; x < this->num_brush_sides; x++)
        {
            this->brush_sides.push_back(*reinterpret_cast<BSPBrushSides*>(&x));
        }

        for (int32_t x = 0; x < this->num_effects; x++)
        {
            this->effect.push_back(*reinterpret_cast<BSPEffects*>(&x));
        }

        this->file.seekg(this->header.lumps[BSPLUMPS::ENTITIES].offset);
        this->file.read(reinterpret_cast<char*>(ents->ents_array), this->header.lumps[BSPLUMPS::ENTITIES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::TEXTURES].offset);
        this->file.read(reinterpret_cast<char*>(textures.data()), this->header.lumps[BSPLUMPS::TEXTURES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::PLANES].offset);
        this->file.read(reinterpret_cast<char*>(this->planes.data()), this->header.lumps[BSPLUMPS::PLANES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::NODES].offset);
        this->file.read(reinterpret_cast<char*>(this->nodes.data()), this->header.lumps[BSPLUMPS::NODES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::LEAFS].offset);
        this->file.read(reinterpret_cast<char*>(this->leaf.data()), this->header.lumps[BSPLUMPS::LEAFS].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::LEAF_FACES].offset);
        this->file.read(reinterpret_cast<char*>(this->leaf_faces.data()), this->header.lumps[BSPLUMPS::LEAF_FACES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::LEAF_BRUSHES].offset);
        this->file.read(reinterpret_cast<char*>(this->leaf_brush.data()), this->header.lumps[BSPLUMPS::LEAF_BRUSHES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::MODELS].offset);
        this->file.read(reinterpret_cast<char*>(this->model.data()), this->header.lumps[BSPLUMPS::MODELS].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::BRUSHES].offset);
        this->file.read(reinterpret_cast<char*>(this->brushes.data()), this->header.lumps[BSPLUMPS::BRUSHES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::BRUSHSIDES].offset);
        this->file.read(reinterpret_cast<char*>(this->brush_sides.data()), this->header.lumps[BSPLUMPS::BRUSHSIDES].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::VERTEXES].offset);

        for (int32_t x = 0; x < this->num_vertexes; x++)
        {
            this->file.read(reinterpret_cast<char*>(&vertexes.data()[x]), this->header.lumps[BSPLUMPS::VERTEXES].length);
        }

        this->file.seekg(this->header.lumps[BSPLUMPS::MESHVERTS].offset);
        this->file.read(reinterpret_cast<char*>(this->mesh_verts.data()), this->header.lumps[BSPLUMPS::MESHVERTS].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::EFFECTS].offset);
        this->file.read(reinterpret_cast<char*>(this->effect.data()), this->header.lumps[BSPLUMPS::EFFECTS].length);

        this->file.seekg(this->header.lumps[BSPLUMPS::FACES].offset);
        this->file.read(reinterpret_cast<char*>(this->faces.data()), this->header.lumps[BSPLUMPS::FACES].length);

        std::printf("BSP VERSION: '%s'\n", this->header.magic);

        if (std::strncmp(this->header.magic, "IBSP", 4) == 0)
        {
            std::printf("SUCCESS: VALID BSP FORMAT!\n");
        }
        else
        {
            std::printf("ERROR: INVALID BSP FORMAT!\n");

            return false;
        }

        this->shader.load_shader("shaders/bsp.vs", "shaders/bsp.fs");

        /* heres where I try to store the data for the faces vertices */
        for (int32_t x = 0; x < this->num_faces; x++)
        {
            BSPFaces& face = this->faces[x];

            for (int32_t vertices = 0; vertices < this->num_vertexes; vertices++)
            {
                BSPVerts* vert = reinterpret_cast<BSPVerts*>(&vertexes[x]);

                this->vertices_vector.push_back(vert[x].position.x);
                this->vertices_vector.push_back(vert[x].position.y);
                this->vertices_vector.push_back(vert[x].position.z);

                this->colors.push_back(vert[x].position.x / 0xFF);
                this->colors.push_back(vert[x].position.y / 0xFF);
                this->colors.push_back(vert[x].position.z / 0xFF);

                this->indices.push_back(vert[x].position.x);
                this->indices.push_back(vert[x].position.y);
                this->indices.push_back(vert[x].position.z);
            }
        }

        glGenVertexArrays(1, &this->vao);

        glBindVertexArray(this->vao);

        glGenBuffers(1, &this->vbo);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, this->vertices_vector.size() * sizeof(float), &this->vertices_vector.front(), GL_STATIC_DRAW);

        glGenBuffers(1, &this->color_vbo);
        glBindBuffer(GL_ARRAY_BUFFER, this->color_vbo);
        glBufferData(GL_ARRAY_BUFFER, this->colors.size() * sizeof(float), &this->colors.front(), GL_STATIC_DRAW);

        this->coord3d = glGetAttribLocation(this->shader.program, "coord3d");
        this->mvp = glGetUniformLocation(this->shader.program, "mvp");
        this->attrib_color = glGetAttribLocation(this->shader.program, "v_color");

        glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
        glVertexAttribPointer(this->coord3d, // attribute
            3,                 // number of elements per vertex, here (R,G,B)
            GL_FLOAT,          // the currentBlock of each element
            GL_FALSE,          // take our values as-is
            0,                 // no extra data between each position
            nullptr               // offset of first element
        );

        glBindBuffer(GL_ARRAY_BUFFER, this->color_vbo);
        glVertexAttribPointer(this->attrib_color,
            3,
            GL_FLOAT,
            GL_FALSE,
            0,
            nullptr
        );

        glBindVertexArray(0);

        glVertexAttrib3fv(this->attrib_color, reinterpret_cast<float*>(this->colors.data()));

        return true;
    }
    else
    {
        std::printf("ERROR: COULDN'T OPEN FILE!\n");

        return false;
    }

    return false;
}

void KikoBSP::render(glm::vec3 position)
{
    glBindVertexArray(this->vao);
    glEnableVertexAttribArray(this->coord3d);
    glEnableVertexAttribArray(this->attrib_color);

    glm::mat4 model = glm::translate(glm::mat4(1.0), glm::vec3(position.x, position.y, position.z));
    glm::mat4 mvp = game_manager->projection * game_manager->view * model;
    glUniformMatrix4fv(this->mvp, 1, GL_FALSE, glm::value_ptr(mvp));

    glLineWidth(3.0);
    glDrawArrays(GL_LINES, 0, this->vertices_vector.size());

    glDisableVertexAttribArray(this->coord3d);
    glDisableVertexAttribArray(this->attrib_color);
    glBindVertexArray(0);
}

void KikoBSP::cleanup_map()
{
    /* delete[] textures;
    delete[] planes;
    delete[] this->leafs;
    delete[] this->nodes;
    delete[] this->leaf_this->faces;
    delete[] this->models;
    delete[] this->brushes;
    delete[] this->brush_sides;
    delete[] this->vertexes;
    delete[] this->mesh_verts;
    delete[] this->effects;
    delete[] this->this->faces;
    (use maybe later?) */
    this->file.close();
}

There are no errors in the code, it just draws this:

Which is obviously not the map!
Also, heres my header file if you need that to:
#pragma once
#pragma pack(2)

#include <iostream>
#include <cstdint>
#include <string>
#include <vector>
#include <glm/vec3.hpp>
#include <fstream>
#include "shader.h"
#include <memory>
#include <array>

#define FACE_POLYGON 1

enum BSPLUMPS
{
    ENTITIES,
    TEXTURES,
    PLANES,
    NODES,
    LEAFS,
    LEAF_FACES,
    LEAF_BRUSHES,
    MODELS,
    BRUSHES,
    BRUSHSIDES,
    VERTEXES,
    MESHVERTS,
    EFFECTS,
    FACES,
    LIGHTMAPS,
    LIGHTVOLS,
    VISDATA,
    MAX_LUMPS
};

struct BSPLump
{
    int32_t offset; /* offset to start of lump */
    int32_t length; /* length of lump, always multiple of 4 */
};

struct BSPHeader
{
    char magic[4]; /* ALWAYS IBSP */
    int32_t version; /* 0x2E for Quake 3 */
    BSPLump lumps[BSPLUMPS::MAX_LUMPS]; /* direntries */
};

struct BSPEntities
{
    char* ents_array;
};

struct BSPTexture
{
    char name[64];
    int32_t flags;
    int32_t contents;
};

struct BSPPlane
{
    glm::vec3 normal;
    float distance;
};

struct BSPNode
{
    int32_t plane;
    glm::ivec2 children;
    glm::ivec3 mins;
    glm::ivec3 maxs;
};

struct BSPLeaf
{
    int32_t cluster;
    int32_t area;
    glm::ivec3 mins;
    glm::ivec3 maxs;
    int32_t leafface;
    int32_t num_leaffaces;
    int32_t leaf_brush;
    int32_t num_leaf_brushes;
};

struct BSPLeafFace
{
    int32_t face;
};

struct BSPLeafBrush
{
    int32_t brush;
};

struct BSPModel
{
    glm::fvec3 mins;
    glm::fvec3 maxs;
    int32_t face;
    int32_t num_faces;
    int32_t brush;
    int32_t num_brushes;
};

struct BSPBrush
{
    int32_t brush_side;
    int32_t num_brush_sides;
    int32_t texture;
};

struct BSPBrushSides
{
    int32_t plane;
    int32_t texture;
};

struct BSPVerts
{
    glm::vec3 position;
    glm::vec2 tex_coord; /* same as float tex_coord[2][2] */
    glm::vec2 lm_coord; /* same as float tex_coord[2][2] */
    glm::vec3 normal;
    char color[4];
};

struct BSPMeshVerts
{
    int32_t offset;
};

struct BSPEffects
{
    char name[64];
    int32_t brush;
    int32_t unk; /* unknown */
};

struct BSPFaces
{
    int32_t texture;
    int32_t effect;
    int32_t type;
    int32_t vertex;
    int32_t num_vertexes;
    int32_t meshvert; /* start */
    int32_t num_of_meshverts;
    int32_t lm_index;
    glm::ivec2 lm_start;
    glm::ivec2 lm_size;
    glm::vec3 lm_origin;
    float lm_vecs[2][3];
    glm::fvec3 normal;
    glm::ivec2 size;
};

class KikoBSP
{
public:
    bool load_map(std::string);
    void render(glm::vec3);
    void draw_level();
    int32_t get_max();
    int32_t get_min();
    void get_vert();

    void cleanup_map();

    Shader shader;
    BSPHeader header;

    int32_t num_vertexes;

private:
    std::ifstream file;
    uint32_t vbo;
    uint32_t vao;
    uint32_t color_vbo;
    uint32_t ebo;

    int32_t coord3d;
    int32_t mvp;
    int32_t attrib_color;
    BSPFaces* cur_face;

    std::vector<float> vertices_vector;
    std::vector<float> colors;
    std::vector<float> indices;
    std::vector<BSPFaces> faces;
    std::vector<BSPTexture> textures;
    std::vector<BSPPlane> planes;
    std::vector<BSPNode> nodes;
    std::vector<BSPMeshVerts> mesh_verts;
    std::vector<BSPLeaf> leaf;
    std::vector<BSPLeafFace> leaf_faces;
    std::vector<BSPLeafBrush> leaf_brush;
    std::vector<BSPModel> model;
    std::vector<BSPBrush> brushes;
    std::vector<BSPBrushSides> brush_sides;
    std::vector<BSPEffects> effect;

    int32_t num_textures;
    int32_t num_planes;
    int32_t num_nodes;
    int32_t num_leafs;
    int32_t num_leaf_faces;
    int32_t num_leaf_brushes;
    int32_t num_models;
    int32_t num_brushes;
    int32_t num_brush_sides;
    int32_t num_meshverts;
    int32_t num_effects;
    int32_t num_faces;
    int32_t num_lightmaps;
    int32_t num_lightvols;
};

I think the problem is the indices or vertices. I believe the problem lies with how I STORE the data for the vertices. Its really buggy.
Thanks! All helps appreciated! :)

A: Whenever someone says "There are no errors in the code", you know something has already gone terribly wrong!
For example, what is this supposed to be doing?
for (int32_t x = 0; x < this->num_vertexes; x++)
{
    vertexes.push_back(*reinterpret_cast<BSPVerts*>(&x));
}

It looks like it's invoking some undefined behavior here. If all you want to do is fill the array up, just do this:
vertexes.resize(num_vertices);

Secondly, the code that reads in the vertexes from the file looks like it has a logic error:
for (int32_t x = 0; x < this->num_vertexes; x++)
{
    this->file.read(reinterpret_cast<char*>(&vertexes.data()[x]), this->header.lumps[BSPLUMPS::VERTEXES].length);
}

This looks like it's going to read in the entirety of the vertex lump for each vertex, probably resulting in bizarre behavior. You probably just want to do this:
file.read(reinterpret_cast<char*>(vertexes.data()), header.lumps[BSPLUMPS::VERTEXES].length);

Also, a note on your code that's unrelated to your problem: using this-> everywhere hurts readability and adds nothing to the code, remove it.
I did the same BSP renderer a while back, I can't remember what state I left it in, but you can have a look at the code here.


text:
Q: how to measure the read and write time on hdfs using job spark? I just started the work on the qualification of a big data platform, and I would like to have proposals on how to test the performance of reading and writing on hdfs.

A: If you are running the spark jobs for read and write operation then you can see the job time on application manager (localhost:50070) and if you are using spark-shell then you have to measure time manually or you can use time function.


text:
Q: Outlier detection for multi column data frame in R I have a data frame with 18 columns and about 12000 rows. I want to find the outliers for the first 17 columns and compare the results with the column 18. The column 18 is a factor and contains data which can be used as indicator of outlier.
My data frame is ufo and I remove the column 18 as follow:
ufo2 <- ufo[,1:17]

and then convert 3 non0numeric columns to numeric values:
ufo2$Weight <- as.numeric(ufo2$Weight)
ufo2$InvoiceValue <- as.numeric(ufo2$InvoiceValue)
ufo2$Score <- as.numeric(ufo2$Score)

and then use the following command for outlier detection:
outlier.scores <- lofactor(ufo2, k=5)

But all of the elements of the outlier.scores are NA!!!
Do I have any mistake in this code?
Is there another way to find outlier for such a data frame?
All of my code:
setwd(datadirectory)
library(doMC)
registerDoMC(cores=8)

library(DMwR)

# load data
load("data_9802-f2.RData")

ufo2 <- ufo[,2:17]

ufo2$Weight <- as.numeric(ufo2$Weight)
ufo2$InvoiceValue <- as.numeric(ufo2$InvoiceValue)
ufo2$Score <- as.numeric(ufo2$Score)

outlier.scores <- lofactor(ufo2, k=5)

The output of the dput(head(ufo2)) is:
structure(list(Origin = c(2L, 2L, 2L, 2L, 2L, 2L), IO = c(2L,
2L, 2L, 2L, 2L, 2L), Lot = c(1003L, 1003L, 1003L, 1012L, 1012L,
1013L), DocNumber = c(10069L, 10069L, 10087L, 10355L, 10355L,
10382L), OperatorID = c(5698L, 5698L, 2015L, 246L, 246L, 4135L
), Month = c(1L, 1L, 1L, 1L, 1L, 1L), LineNo = c(1L, 2L, 1L,
1L, 2L, 1L), Country = c(1L, 1L, 1L, 1L, 11L, 1L), ProduceCode = c(63456227L,
63455714L, 33687427L, 32686627L, 32686627L, 791614L), Weight = c(900,
850, 483, 110000, 5900, 1000), InvoiceValue = c(637, 775, 2896,
48812, 1459, 77), InvoiceValueWeight = c(707L, 912L, 5995L, 444L,
247L, 77L), AvgWeightMonth = c(1194.53, 1175.53, 7607.17, 311.667,
311.667, 363.526), SDWeightMonth = c(864.931, 780.247, 3442.93,
93.5818, 93.5818, 326.238), Score = c(0.56366535234262, 0.33775439984787,
0.46825476121676, 1.414092583904, 0.69101737288291, 0.87827342721894
), TransactionNo = c(47L, 47L, 6L, 3L, 3L, 57L)), .Names = c("Origin",
"IO", "Lot", "DocNumber", "OperatorID", "Month", "LineNo", "Country",
"ProduceCode", "Weight", "InvoiceValue", "InvoiceValueWeight",
"AvgWeightMonth", "SDWeightMonth", "Score", "TransactionNo"), row.names = c(NA,
6L), class = "data.frame")

A: First of all, you need to spend a lot more time preprocessing your data.
Your axes have completely different meaning and scale. Without care, the outlier detection results will be meaningless, because they are based on a meaningless distance.
For example produceCode. Are you sure, this should be part of your similarity?
Also note that I found the lofactor implementation of the R DMwR package to be really slow. Plus, it seems to be hard-wired to Euclidean distance!
Instead, I recommend using ELKI for outlier detection. First of all, it comes with a much wider choice of algorithms, secondly it is much faster than R, and third, it is very modular and flexible. For your use case, you may need to implement a custom distance function instead of using Euclidean distance.
Here's the link to the ELKI tutorial on implementing a custom distance function.


text:
Q: Pull only a JSON serializable part of a DateTimeField into a queryset? What is the most efficient way to get a JSON serializable part of the DateTimeField into a Django queryset?
Bigger picture is that I'm saving energy meter readings (IntegerField) + datetimes for multiple users and would like to show a logged in user's data in a django-graphos visualization. Ideally keeping the flexibility to switch graphs between day, week, month views.
I've got the graph to work nicely for a logged in user with the user_kwh integer and the user_id using the below in my view:
def graph(request):
        queryset = MeterReading.objects.filter(user=request.user)
        data_source = (ModelDataSource(queryset, fields=["user_id", "user_kwh"]))
        chart = gchart.LineChart(data_source)
        context = {'chart': chart}
        return render(request, 'dashboard/index.html', context)

But when I change user_id to user_kwh_timestamp (my name of the datetime field) it throws the TypeError: "datetime.datetime(2013, 12, 1, 21, 58, 2, tzinfo=) is not JSON serializable"
Stuff I've tried so far

*

*I've tried serializing the values in the queryset before passing them
to the template with: data_source = serializers.serialize('json', MeterReading.objects.all(), fields=('user_kwh_timestamp',))
but that
gives an AttributeError saying 'unicode' object has no attribute
'get_header'.

*I've tried defining the queryset narrower with .values_list but that
says "'datetime.datetime' object has no attribute 'user_kwh_timestamp'"

*I've found this Django documentation on updating multiple objects in a queryset, but it only shows how to update all with 1 string: https://docs.djangoproject.com/en/1.7/topics/db/queries/#updating-multiple-objects-at-once
From the Python datetime documentation it seems that strftime() and %b or %x could be a part of the solution, but at this point I'm confused on how/where to implement those https://docs.python.org/2/library/datetime.html#datetime-objects
I'm using Django 1.7.1 and Python 2.7.6 via ide.c9.io.
First coding project and first question here so excuse any ignorance in contents, style or approach :)

A: Let json lib serialize the result values (from queryset), specifying a JSON encoder, in this case DjangoJSONEncoder. You must turn queryset into a list before serialize, or you may get some exception.
import json
from django.core.serializers.json import DjangoJSONEncoder

...

def graph(request):
    queryset = MeterReading.objects.filter(user=request.user).values()
    data = json.dumps(list(queryset), cls=DjangoJSONEncoder)
    ...


text:
Q: What happens when you shake a can of soda? Of course the CO2 comes out of the liquid, and it will even build up a lot of pressure if needed. The question is what happens at a molecular level to cause it to leave the liquid?

A: The tangy taste of sodas comes from an acid in them.  In most sodas, it's carbonic acid:  ${\rm H}_2{\rm CO}_3$.  Under pressure, like in a sealed can of soda at room temperature and usual pressure, the equilibrium reached keeps this molecule together.  Once you open the can of soda, the lowered pressure inside the can "allows" this molecule to break apart into ${\rm H}_2{\rm O}$ and ${\rm CO}_2$.  This is where the carbon dioxide bubbles come from.  When you open a can, there is still the issue of how fast this reaction happens.  If you've shaken it, you move some of the gas at the top of the can into little bubbles stuck to the sides.  This primes the process for the carbonic acid to break down once the pressure is released.  Essentially, it's already begun the formation of the bubbles, and that makes it easier for them to grow enough that they can detach and rise to the surface.  This isn't always easy.  If you've ever watched a simmer pot of water, you'll notice sometimes bubbles form at the bottom and then shrink and go away again.  The opposite can happen too.  Soda bubbles tend to get bigger as they rise as they pick up more ${\rm CO}_2$ from the carbonic acid in the surrounding liquid.  So the rate depends on a number of things, but shaking helps the bubbles form.


text:
Q: How to fix toggleComplete for Todo React When you click on a list item in the to-do list, it should strikethrough, indicating you are finished with the task, however, when I click on the list item, nothing happens. Below is my toggleComplete function and where I want to call the function:
class TodoForm extends Component {
  state = {
    item: ''
  };

  handleChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.onSubmit({
      id: Math.floor(Math.random() * 1000),
      item: this.state.item,
      complete: false
    });
    this.setState({
      item: ''
    });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          name="item"
          value={this.state.item}
          onChange={this.handleChange}
        />
        <button onClick={this.handleSubmit}>Add Todo</button>
      </form>
    );
  }
}

export default class TodoList extends Component {
  state = {
    item: {
      todo: "todo",
      complete: false
    },
    items: [],
    complete: true
  };

  addTodo = todo => {
    this.setState(state => ({
      items: [todo, ...state.items]
    }));
  };

  toggleComplete = id => {.    //<---- toggleComplete function not working
    this.setState(state => ({
      items: state.items.map(todo => {
        if (todo.id === id) {
          return {
            ...todo,
            complete: !todo.complete
          };
        } else {
          return todo;
        }
      })
    }));
  };

  render() {
    let items = this.state.items;
    return (

          <TodoForm onSubmit={this.addTodo} />
          {items.map(todo => (

 this.toggleComplete(todo.id)}
              todo={todo}
            >

 //<--- where I am trying to call the function
                {todo.item}

          ))}

            {this.state.items.filter(todo => !todo.complete).length} remaining out of {this.state.items.length}

    );
  }
}

Also, when you click on the item and the text strikes through, the tasks left to do also decrements. I would appreciate help with this problem

A: Its happening because you are passing two event handlers.

*

*On Li so it pass id as event

*On ul since toggleComplete is not browser property so its not invoking because of that. If its onClick it will invoke because of bubbling.

Fix for this is:

*

*remove toggleComplete from ul

*Pass onClick={() => this.toggleComplete(todo.id)} in li
Here is complete code and demo:https://codesandbox.io/s/great-blackburn-ti0d1?file=/src/App.js:1762-1821


text:
Q: PostgreSQL COPY FROM csv - csv formating issues I have a csv file that I'm trying to import into my PostgreSQL database (v.10). I'm using the following basic SQL syntax:
COPY table (col_1, col_2, col_3)
FROM '/filename.csv'
DELIMITER ',' CSV HEADER
QUOTE '"'
ESCAPE '\';

First 30,000 lines or so are imported without any problem. But then I start bumping into formatting issues in the csv file that break the import:

*

*Double quotes in double quotes: "value_1",""value_2"","value_3" or "value_1","val"ue_2","value_3"

The typical error I get is
ERROR: extra data after last expected column

So I started editing the csv file manually using Vim (the csv file has close to 7 million lines so can't really think of another desktop tool to use)

*

*Is there anything I can do with my SQL syntax to handle those malformed strings? Using alternative ESCAPE clauses? Using regex?

*Can you think of a way to handle those formatting issues in Vim or using another tool or function?

Thanks a lot!

A: Note that the file does not meet the CSV specification:

*If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote.

You should specify a quote sign other than double-quote, for example '|':
create table test(a text, b text, c text);

copy test from '/data/example.csv' (format csv, quote '|');

select * from test;

     a     |      b      |     c
-----------+-------------+-----------
 "value_1" | ""value_2"" | "value_3"
 "value_1" | "val"ue_2"  | "value_3"
(2 rows)

You can get rid of the unwanted double-quotes using the trim() or replace() functions, e.g.:
update test
set a = trim(a, '"'), b = trim(b, '"'), c = trim(c, '"');

select * from test;

    a    |    b     |    c
---------+----------+---------
 value_1 | value_2  | value_3
 value_1 | val"ue_2 | value_3
(2 rows)


text:
Q: the framework does not load the DLL from the correct path My .Net 4.0 project consists in several projects.
My starting project is the one on the screenshot.
It displays Default.aspx .
Into this project properties, it is set to build into "bin\Debug\" (default behaviour) and it does build the dll there as intended.
However, for any reason, when I run the app, the framework looks for the DLL into "/bin" instead of "bin\Debug\"!!!
I tried to change the build path to "bin\Debug2\" as a test and the same happens. The DLL is created into the correct directory that I set but when I run the app, it tries to load into  "/bin/".
I suppose one of my files is mis-setupped but I have no idea which one.
Any help appreciated.


text:
Q: paired t-test with ordinal data Can I do a paired samples t-test when my data are ordinal? My data are
reading levels at time 1 and time 2, but the data levels are A, 1 2,3,4,6,8,10, 12, 14, 20, 24, 28, 30, 34, 38, 40, 50, 60, 70, 80. They
appear to be continuous but they are not. Can I still use a paired t-test? These are the reading levels from k - 8th grade. I was able to run a paired t-test on the continuous data, which was a standardized test with grade level equivalency, but I am not sure if I can also do it for the reading level data.

A: Because this is ordinal data, the assumptions that the data follow a normal distribution will be violated. Given that the assumption of normality is violated, a typical paired t-test in this situation would at best lack sensitivity, and at worst provide spurious estimates.
Fortunately there are non-parametric versions of the t-test which do not depend on the assumption of normality, and so are quite suitable for ordinal data.
For this data, I would suggest the signed-rank test. It is designed for paired comparisons on non-normal data.
Here is an example in r:
## first construct our samples to test
# pool of possible ordinal values
# not continuous, however numerical order assumed valid
pool = c(1, 2,3,4,6,8,10, 12, 14, 20, 24, 28, 30, 34, 38, 40, 50, 60, 70, 80)

# sample 1, randomly chosen from pool values
test1 = sample(pool, 100, replace = TRUE)

# sample 2, randomly chosen from pool values
test2 = sample(pool, 100, replace = TRUE)

# sample 3, pool values, weighted towards higher values (those at end of pool)
prob_vec = 1:length(pool)/sum(1:length(pool))
test3_weighted = sample(pool, 100, replace = TRUE, prob = prob_vec)

## run the sign rank test
# test1 vs test2 should not have significant difference, they are both chosen at random
wilcox.test(test1, test2, paired = TRUE)
# V = 1849.5, p-value = 0.1985

# test1 (or test2) vs test 3 should be significant, test 3 is weighted towards
#  higher values
wilcox.test(test1, test3_weighted, paired = TRUE)
# V = 1221, p-value = 8.495e-05


text:
Q: can`t encode or decode to see "ç" on my string I'm taking a body from an email and trying to make some comparisons and print.
I'm not getting it because my string has special characters, python is returning me = E7 instead of ç. There are some strange codes too, I believe it's from html:
'\r\n________________________________\r\nDe: Transfer=EAncia de Cliente\r\nEnviado'

'BATIST=\r\nA'

'solicita=E7=E3o'

I've tried everything, the last thing I used was:
bytes.fromhex("E7").decode("ISO-8859-1")

which returns "ç" correctly but when trying to use the other string it gives me an error:
a = '\r\n________________________________\r\nDe: Transfer=EAncia de Cliente\r\nEnviado: segunda-feira'

bytes.fromhex(a).decode("ISO-8859-1")

ValueError: non-hexadecimal number found in fromhex() arg at position 2

can you help me?
my language is: pt br

A: The reason your second fromhex is failing is because you didn't give it hex data.  Hex data can only contain the characters A-F and 0-9 and there must be an even number of them.  See how you correctly used fromhex the first time with "E7".
I think your data is in "quoted-printable" format and you should try https://docs.python.org/3.8/library/quopri.html
To install it, use python -m pip install quopri


text:
Q: PresentViewController without fullscreen Quick question again. When I use presentViewController to present a new viewcontroller on top of my current one it is full screen. How do I get it to present a specific size? Or should I use another method.
Code:
- (IBAction)showProfile:(id)sender {
ProfileView *profileTop = [[ProfileView alloc] init];
profileTop.delegate = self;

[self presentViewController:profileTop animated:YES completion:nil];
}

A: I'd suggest doing a little more research, specifically in Apple's reference. Of note, there is this quote from the View Controller Programming Guide (http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ModalViewControllers/ModalViewControllers.html):

Presentation Styles for Modal Views
For iPad apps, you can present content using several different styles. In iPhone apps, presented views always cover the visible portion of the window, but when running on an iPad, view controllers use the value in their modalPresentationStyle property to determine their appearance when presented. Different options for this property allow you to present the view controller so that it fills all or only part of the screen.

And specifically, on the API reference page for presentViewController (http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/presentViewController:animated:completion:):

On iPhone and iPod touch, the presented view is always full screen. On iPad, the presentation depends on the value in the modalPresentationStyle property.

Only the iPad appears to have any support for non-fullscreen modals.

A: On iPad you can just use:
[viewcontroller setModalPresentationStyle:UIModalPresentationFormSheet];

example:
LoginDialogViewController * login_dialog = [[LoginDialogViewController alloc] init];
[login_dialog setModalPresentationStyle:UIModalPresentationFormSheet];
[self presentViewController:login_dialog animated:true completion:nil];

A: If you are developing an app for iPad then you can make use of viewController's modalPresentationStyle property, You need to set for presenting viewController.
It has 4 values for that variable.
UIModalPresentationFullScreen = 0,
UIModalPresentationPageSheet,
UIModalPresentationFormSheet,
UIModalPresentationCurrentContext

You can select which one suites you the best.

A: You can use the same code. Then adjust the view size in the xib file. See the below figure


text:
Q: How to fetch Google Places data in SwiftUI? I'm new to SwiftUI. Currently struggling with fetching and presenting photos and places names to my List from Google Places (Maps) API. I do know that they provide explanation of how to do it, but since I'm not that experienced yet, i cannot get the code provided just for Swift (not Swift UI). Tried to use the method below:
struct Response: Codable {
    var results: [Place]
}

struct Place: Codable {
    var placeId: Int
    var placeName: String
    var placePic: String
    var placeTime: String
    var placePhone: String
    var placeLocation: String
}

    @State var results = [Place] ()

    var body: some View {

        List(results, id: \.placeId) { item in
            VStack{
                Text(item.placeName)
            }
        }.onAppear(perform: loadData)
    }
    func loadData(){
        guard let url = URL(string: "https://maps.googleapis.com/maps/api/place/photo?parameters") else{

            print("Invalid URL")

            return
        }
        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request){data, responce, error in

            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {

                    DispatchQueue.main.async {

                        self.results = decodedResponse.results
                    }

                    return
                }
            }
            print("fetch failed: \(error?.localizedDescription ?? "Unknown  error")")

        }.resume()
    }
}

Question:
Is there any ideas of what i do wrong? Because I tried to search for some tutorials on the web, using SwiftUI, but haven't found any.


text:
Q: I can develop web application and run it as desktop application by using python-django framework? I want to build a web application by using python (django) framework for an e-government application
but I want to run this web application like a desktop application not inside brwoser, I can for doing this by python and django?
I am new to  django can you please help me out
Thanks in Advance

A: No. Django is designed to run as a web server, like flask, and respond to HTTP requests with a valid response that would be rendered by a browser.
As mentioned by Fynn Becker there is a system (electron) that is designed to take a node server environment and make it work for desktop apps.
And there have been experiments where python code was executed from electron with python-shell: https://www.techiediaries.com/python-electron-tutorial/
But I think it would be difficult to get django to work properly in electron.
If you want to write a desktop app with python then I'd recommend using one of the several libraries that are available: PyQt, PySide, Kivy, Tkinter, etc.
Here's a post with a brief overview: http://takluyver.github.io/posts/so-you-want-to-write-a-desktop-app-in-python.html


text:
Q: Importing Bazel Build Tensorflow I'm trying to import the tensorflow project into the CLion IDE (on Linux) so that I can run various cc tests for example this.
I've built tensorflow from source using Bazel following the instructions from here . Now, I'm trying to import the bazel project into the CLion IDE by following the steps listed here.
I'm not able to select an initial project view file of .bazelproject type since it does not exist in my tensorflow directory.
Am I missing something or is there another way so that I can run tensorflow test files on my ide?

A: Importing the Tensorflow project is no different than any other Bazel Project. It works fine for me when I try the following:

*

*Install the Bazel plugin by going to configure -> Plugins -> and searching for Bazel. Install the following plugin:

*Once installed restart CLion

*Once restarted click on the open project option in the load screen:

*This will open and import the tensorflow project with build settings. You can see from this image that the bazel configuration and settings are imported correctly:

Note: Bazel builds the entire tensorflow project into an installable python package. If you are purely interested in compiling it for C/C++ then I suggest you look at how to build and use the C++ API as building the entire project for every edit you make will age you very quickly.
Recommendation: If you just want to run the test files then install Tensorflow and simply execute the test files like you would run any program with cpp source files.


text:
Q: Get user from request with Graphql in Nest.js I want to make a normal Graphql request handler. If the user is authorized - send one set of data, if not - others.
When I make a request I see the following in the console:
user User {
  id: '11850582-b10c-4c3e-aa94-6de6db2c8588',
  created_at: 2021-12-21T20:05:18.585Z,
  updated_at: 2021-12-21T20:38:30.207Z,
  username: 'test_admin',
  role: 'ADMIN',
  email: 'test_admin@example.com',
  password: '$2b$10$s/1jSCK3AdM1t01I/PDLA.8NxtVmKmnO5CJZZzi68M4wycPH4K86S',
  currentHashedRefreshToken: '$2b$10$/KkuH80Oql1gArlsJf352eyVYhpMEkcDkGza/xS2YlxzFXtab7oEq'
}
user undefined
userCtx undefined

And I don't understand next:
Why I see in the console output 2 times? I guess it's because the interceptor works both ways - when the request comes and when it goes. But then I do not understand why in my resolver user is undefined, if it is at the entrance.
// article.resolver.ts

@Query((_) => ArticleWithBookmarkedModel)
@UseInterceptors(GraphqlUserInterceptor)
async articleBySlugs(
    @GraphqlAuthUser() user: User
): Promise<ArticleWithBookmarkedModel> {
    console.log('userCtx', user);

    if (!user) {
        return ...
    }

    return ...
}

// graphql-user-interceptor.service.ts

export class GraphqlUserInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const ctx = GqlExecutionContext.create(context);
        const request = ctx.getContext().req;

        console.log('user', request.user);

        return next.handle();
    }
}

// graphql-auth.user.ts

export const GraphqlAuthUser = createParamDecorator(
    (data: unknown, context: ExecutionContext) => {
        const ctx = GqlExecutionContext.create(context);
        const request = ctx.getContext().req;

        return request.user;
    },
);


text:
Q: How to get a good response from saving a model With backbone.js I'm saving a model. A PUT is send to the server and the response is returned. The first time I do it, it returns success, the following times an error is return, because after the first time the response is added to the model.
Save function in Backbone.js:
saveCountry: function() {
    this.model.save({},{
        success: function(model, response) {
            console.log('success! ' + response);
        },
        error: function(model, response) {
            console.log('error! ' + response);
        }
    });
    this.render();

    return false;
},

PHP returns a JSON-string:
{"response": "Model saved!"}

Following PUT's get an error as response, because 'response' is added to the model:
Unknown column 'response' in 'field list'

Why is the response added to the model and how do I prevent it?

A: From Backbone's documentation on model save:

Set a hash of model attributes, and sync the model to the server. If
  the server returns an attributes hash that differs, the model's state
  will be set again.
  http://documentcloud.github.com/backbone/docs/backbone.html#section-41

What to do to make it work: don't return {"response": "Model saved!"} from the server. Just return a success (status 200) with no content.
If the save did not work, return a JSON with the errors, and Backbone will trigger an error event on your model, with the JSON you provided (see http://documentcloud.github.com/backbone/docs/backbone.html#section-41 and http://documentcloud.github.com/backbone/docs/backbone.html#section-145).

A: Just to resurrect an ancient thread...
It isn't always possible/desirable to change the response you get back from the server.
Another solution is to override parse in the model to take care of this. For your situation, where the response is inappropriate for ALL of your models, you could do it in a superclass.
MyModel = Backbone.Model.extend({
    parse: function(data) {
        delete data["success"];
        return data;
    }
});

Address = MyModel.extend({
    saveCountry: function() {
        this.model.save({},{
            success: function(model, response) {
                console.log('success! ' + response);
            },
            error: function(model, response) {
                console.log('error! ' + response);
            }
        });
        this.render();

        return false;
    },

    ...

});


text:
Q: How do I properly extend CountDownTimer class? I'm trying to extend CountDownTimer, but I have "there is no default constructor in countdown timer" problem.
public class CustomTimer extends CountDownTimer {
    // fields I need to use my original timer
    boolean still_down;
    View v;
    MotionEvent e;

    public ErjanTimer(View v, MotionEvent e,boolean still_down, long duration, long interval){
        // my original constructor
        this.still_down = still_down;
        this.e = e;
        this.v = v;
    }

    public ErjanTimer(long duration, long interval){
        super(duration, interval);
    }

    @Override
    public void onTick(long millisUntilFinished) {
    }

    @Override
    public void onFinish() {
    }
}

A:
"there is no default constructor in countdown timer"

As you know constructor have same name as class name. but in current code class name is  CustomTimer and as you are saying ErjanTimer is constructor which is not valid. currently methods with ErjanTimer names behave like methods with same names but different params
So, just use CustomTimer instead of ErjanTimer for constructor :
public CustomTimer(long duration, long interval){
    super(duration, interval);
}

A: If the class name problem which has already been suggested by ρяσѕρєя K were just typo, I would suggest an alternative answer.
So your class has below structure:
public class ErjanTimer extends CountDownTimer {
    ...
    public ErjanTimer(View v, MotionEvent e,boolean still_down, long duration, long interval){
        ...
    }

    public ErjanTimer(long duration, long interval){
        super(duration, interval);
    }
    ...
}

And having "there is no default constructor in countdown timer" error.
In this case, you must have calling to super also in your original constructor.
public ErjanTimer(View v, MotionEvent e,boolean still_down, long duration, long interval){
    super(duration, interval);
    ...
}


text:
Q: How to check if a radio button has been selected, if it has assign a value to variable I am writing a distance calculator for an assignment and for one of the requirements is to have the user select which units they want the distance is displayed. I'm using the haversine equation to work out the distance. The code what I have to check if the button has been selected is
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    if (MilesButton.Checked == true)
    {
        radius = 3956;
    }
}

It gives me the error  "The event can only appear on the left hand side of += or -=".
Is there a better way to check if the button has been selected? Also if i use the method MilesButton.IsChecked is gives another error "cannot implicitly convert type 'bool?' to 'bool' an explicit conversion exists(are you missing a cast?)"

A: Instead of Checked use IsChecked property:
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    if (MilesButton.IsChecked ?? false)
    {
            radius = 3956;
    }
}

Also you can use GetValueOrDefault method like this:
if (MilesButton.IsChecked.GetValueOrDefault())

A: This code should work for you
In the XAML file:
    <Grid>
        <RadioButton x:Name="MilesButton" Content="MilesButton" HorizontalAlignment="Left" Margin="66,39,0,0" VerticalAlignment="Top" GroupName="distance" Checked="RadioButton_Checked"/>
        <RadioButton Content="KilometreButton" HorizontalAlignment="Left" Margin="66,59,0,0" VerticalAlignment="Top" GroupName="distance" Checked="RadioButton_Checked"/>
    </Grid>

And the code behind
        private int radius = 0;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            if (MilesButton.IsChecked == true)
            {
                radius = 3956;
            }
        }


text:
Q: How to add a toc to the upper of each Beamer frame? I use a Beamer template I found here for presentations and it's very nice to see, but I would like to have a table of contents in the upper of each frame as for some beamer templates such as Warsaw. How could I do that ? This is my mwe :
% compile with lualatex or xelatex:
\documentclass[svgnames, 14pt]{beamer}
\usepackage{booktabs,etoolbox,fontspec,microtype,ragged2e}
\usefonttheme{professionalfonts,serif,structuresmallcapsserif}
 \setmainfont[Numbers=OldStyle,SmallCapsFeatures={Kerning=Uppercase}]{Minion Pro}
 \usepackage{fontspec}
 \usepackage[applemac]{inputenc}
 \usepackage[frenchb]{babel}
 \linespread{1.0344}
 \usepackage{graphicx}
 \usepackage{caption}
 \usecolortheme[named=Maroon]{structure}
 \beamertemplatesolidbackgroundcolor{Snow}
 \setbeamertemplate{navigation symbols}{}
 \setbeamertemplate{itemize items}[circle]
 \apptocmd{\frame}{\justifying}{}{}
 \addtobeamertemplate{block begin}{}{\justifying}
 \definecolor{alert}{HTML}{347941}
  \setbeamercolor{alerted text}{fg=alert}
 \setbeamercovered{transparent=2}
 \title{My title}
 \author{My name}
 \institute{My institution}
 \date{}
 \setbeamertemplate{caption}[numbered]

 \begin{document}

\begin{frame}
\titlepage
 \end{frame}

 \end{document}

A: You can use the split outer theme, with \useoutertheme in your preamble:
\useoutertheme{split}

This outer theme will add a header bar, split in two parts: on the left, this list of sections is shown, with the current section highlighted; on the right, le list of subsections of the current section is shown, with the current subsection highlighted.
This will also add a footer bar with the author name and the presentation title, which you can remove by adding to your preamble:
\setbeamertemplate{footline}{}

As you asked how to left-align the section list, you can do it by adding the following to your preamble:
\usesectionheadtemplate{\insertsectionhead\hfill}{\color{fg!50!bg}\insertsectionhead\hfill}

You can also try the tree outer theme, which shows the current section and subsection in a tree structure.


text:
Q: You may need an appropriate loader to handle this file type for dependencies I am upgrading my Angular 11/Webpac 4 project to Angular 14 and Webpack 5.
The issue in this post has been reported many times, but I haven't found a solution that matches the problem that I am having.
Usually, a loader in the webpack configuration is incomplete or missing for certain file types. But as you can see below, the build command complains about the import statement.
Why does it complain about an import? Shouldn't webpack use the build code (.js) created by tsc?
./src/app/app.module.ts:29:18 - Error: Module parse failed: Unexpected token (29:18)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import { NgxPopperjsModule, NgxPopperjsPlacements, NgxPopperjsTriggers } from 'ngx-popperjs';
|
> function initApp(): () => Promise<void> {
|   return () => {
|     const p = [];