text:
Q: Changing the selected timestamp (with weekday) to Fr, Mo etc I have the following code:
$meetings= $db->query("SELECT title, DATE_FORMAT(meetings.time, '%W, %d.%c.%Y - %H:%i') AS time2 FROM meetings");
while ($row = $meetings->fetch_object()) {
    echo'

        '.$row ->title.'
        '.$row ->time2.'

    ';
}

And I want to get an output which shows me the time of that meeting, but the time has to be output like this:
Fr, 06.07.2015 - 20:52 (with Mo, Fr etc...)
How can I solve this?

A: try this query:
SELECT CONCAT(LEFT(DATE_FORMAT(meetings.time, '%W'),2), DATE_FORMAT(meetings.time, ', %d.%c.%Y - %H:%i')) AS time FROM meetings


text:
Q: preg_match_all issue i am fighting with this small php issue, i am trying to read the url parts from a page.
php code is this:
preg_match_all('!(.*?)!',$content,$ergebnisse);

my problem is that preg_match_all() is returning 0 and if i var_dump the $ergebnisse, i am getting empty array like this:
array(3) { [0]=> array(0) { } [1]=> array(0) { } [2]=> array(0) { } }

the page code where i am reading from is this:
NAME

i need somelink.html and NAME, but obviously, it cannot match them, can someone help me please?
BTW: i am reading the content successfully.
thanks

A: Works just fine:
   <?php $content='NAME1

    NAME2

    NAME3';

    preg_match_all('!(.*?)!',$content,$ergebnisse);

    print_r($ergebnisse);

A: I have tested your code
<?php
$content='
NAME
';
echo preg_match_all('!(.*?)!',$content,$ergebnisse);
echo "\n";
var_dump($ergebnisse);

And it totally works:
$ php test.php
1
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(73) "NAME"
  }
  [1]=>
  array(1) {
    [0]=>
    string(13) "somelink.html"
  }
  [2]=>
  array(1) {
    [0]=>
    string(4) "NAME"
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Am I implementing this buffer using a C# Timer correctly? I have a service that subscribes to updates to a repository.
When an update message is received, the service needs to reload some data from the repository.
However many update messages can be received in a short period of time. So I want to create a buffer / time window, that will mean only one reload will happen for that period were many update messages arrived.
I've created a very rough outline:
class TestService
{
    private Timer scheduledReloadTimer;

    public void AttemptReload()
    {
        if (scheduledReloadTimer == null)
        {
            Console.WriteLine("Scheduling reload...");

            scheduledReloadTimer = new Timer(Reload, null, 10000, Timeout.Infinite);
        }
        else
        {
            Console.WriteLine("Reload already scheduled for this period...");
        }
    }

    private void Reload(object stateInfo)
    {
        scheduledReloadTimer.Dispose();
        scheduledReloadTimer = null;

        Console.WriteLine("Doing reload..");
    }
}

Is using the null check on the Timer good enough to see if a reload has already been scheduled?
Am I disposing the Timer correctly?
Is there anything else I am missing here, especially around thread safety?
I've seen another stackoverflow answer that suggests using the Reactive Extensions to achieve this: https://stackoverflow.com/a/42887221/67357 but is that overkill?

A: You do have a potential thread-safety issue here. A quick fix would be to create a thread lock scope around the critical parts of your code, to ensure that while you're inspecting/creating and setting the timer variable, no other thread can get in there and start the same process in parallel:
class TestService
{
    private Timer scheduledReloadTimer;
    private object timerLock = new object();

    public void AttemptReload()
    {
        lock (timerLock)
        {
            if (scheduledReloadTimer == null)
            {
                Console.WriteLine("Scheduling reload...");

                scheduledReloadTimer = new Timer(Reload, null, 10000, Timeout.Infinite);
            }
            else
            {
                Console.WriteLine("Reload already scheduled for this period...");
            }
        }
    }

    private void Reload(object stateInfo)
    {
        lock (timerLock)
        {
            scheduledReloadTimer.Dispose();
            scheduledReloadTimer = null;
        }

        Console.WriteLine("Doing reload..");
    }
}

Reactive Extensions are a good way to deal with this throttling issue - as the code is already written for you.
Another approach might be to modify the AttemptReload call to simply reset the interval on the timer (if the reloadTimer != null), essentially pushing back the invocation of the timer event with each subsequent call to AttemptReload.
That way, the timer will definitely not fire until after the last call to AttemptReload +  10,000 milliseconds.


text:
Q: Should I public method and test it instead of testing a caller I have a method called GetValueA() and GetValueB() which return string that in formatted
 public string GetValueA(){
     string a = service1.GetA();
     return Format(a);
 }

 public string GetValueB(){
     string b = service2.GetB();
     return Format(b)
 }

 private Format(string unformatted){
     return unformatted.ReplaceSpace().PaddingZero()  // for example " 123" will be "00123"
 }

when I create unit test I create
 GivenA_WhenGetA_ReturnFormattedA() // with test data "123", " 123", " 12 3"
 GivenB_WhenGetB_ReturnFormattedB() // with test data "123", " 123", " 12 3"

from above it seems the same so if I public private Format()
 public class Formatter : IFormatter
 {
      public string Format(string data);
 }

and create unit test
 GivenDataHaveSpace_WhenFormatString_ReturnDataWithNoSpace();
 GivenDataLessThanFiveDigits_WhenFormatString_ReturnDataWithPaddingZero();

and use it in GetValueA and GetValueB
 public string GetValueA(){
     string a = service1.GetA();
     return IFormatter.Format(a);
 }

 public string GetValueB(){
     string b = service2.GetB();
     return IFormatter.Format(b)
 }

the question are

*

*if I use IFormatter instead of private it looks like all responsibility is rely on IFormatter and testing
GivenA_WhenGetA_ReturnFormattedA() // with test data "123", " 123", " 12 3"
GivenB_WhenGetB_ReturnFormattedB() // with test data "123", " 123", " 12 3"

will rely on mock of IFormatter which is act as the same as I set up.
1.1 Should I keep this, to say these methods need two format data after get from service?
1.2 or just remove them because when I have something the same with GetValueD, GetValueE, GetValueF, GetValueG will make this redundant.

*Is it make sense if I go with private Format() method instead?

A: Your code looks fine.
I'll assume .ReplaceSpace() and .PaddingZero() are extensions methods that have their own unit tests. This is exactly what extension methods are for, simple behaviour that has no side effects.
If the formatting is specific to this service and the result is not parsed by another service in your domain, a private method is good enough. Only if you actually need both sides (for example this is a format that needs to be parsed by another of your services later) then I would consider writing a serializer/deserializer service pair and interface, so the responsibility for the format is in one place and not scattered across your project.
There is no point in having an extra formatter interface and service, if it's not used across other services and won't be switched out for another implementation.
In case your format becomes complicated, but still free of side effects, you could put it into it's own extension method and unit test that. Then use that extension method instead of your private method.
There are two schools of thought. One says something is good if it's as simple as it can be and still fulfils the requirements. Another says that it's good when it's as complicated as it can be and fulfil the requirements. I'm a believer in the first one. Don't add an interface, service and injection configuration if all you need is a simple, side-effect free method. Just add one. Done.

A: I generally try and isolate the "interesting" stuff from the "boring" stuff and focus on testing the interesting stuff. In your example (without any additional context), Format seems like the interesting stuff so it makes sense to pull out the Formatter and test that separately. Testing it through GetValueA and GetValueB means you will end up with duplicate tests for the things that the formatter does.
Whether or not you keep the other methods around depends on what they mean in the context of your system. If they represent meaningful concepts, you will probably want to write a higher-level (perhaps acceptance) test around them, but if they're just internal details, you can either keep them around as helper methods or choose to inline them.

A:  public string GetValueA(){
     string a = service1.GetA();
     return Format(a);
 }

 private Format(string unformatted){
     return unformatted.ReplaceSpace().PaddingZero()  // for example " 123" will be "00123"
 }

This looks to me like a parser - we're taking some general purpose representation of a message from service1 and creating our own local representation of that information.
Parsers, as a general pattern, have enough complexity that I prefer designs that allow you to test them without extra ceremony.  Here, the extra ceremony includes providing a service1, or some reasonable substitute for it.  It's not hard to imagine GetValueA changing in ways that would require even more ceremony, so I would extract the formatting code into its own testable model soon.
That done, does the Format need to be mockable?  My guess is that it really doesn't.  Your parser is a self contained, in memory only thing; using the "real" parser doesn't add significant overhead.  James Shore's Testing Without Mocks might be a useful reference.
The edge where I might start thinking about mocks/substitutes is the point where we discover that we want to be able to re-use the code in GetValueA with different Format functions.  Until then, YAGNI.

A: Basic mode:
Test all of the public methods on everything.
Advanced mode:
Test the application, or top most level of your code. Other tests are optional


text:
Q: How to get the first column from a json array using jquery I have a json array in the below format:
[
  {
     "id":"01",
     "language": "Java",
     "edition": "third",
     "author": "Herbert Schildt"
  },
  {
     "id":"07",
     "language": "C++",
     "edition": "second"
     "author": "E.Balagurusamy"
  }
]

I want a result consisting only the first column from this array in the form:
[ "01", "07" ]

I tried many codes but wouldn't succeed, is there a way to achieve this using jquery.

A: You can do it like following using map() function.
var input = [
    {
        "id": "01",
        "language": "Java",
        "edition": "third",
        "author": "Herbert Schildt"
    },
    {
        "id": "07",
        "language": "C++",
        "edition": "second",
        "author": "E.Balagurusamy"
    }
];

var result = $(input).map(function() {
    return this.id;
}).get()

console.log(result);

A: For anyone looking for the same thing in plain javascript (adapted from acepted answer)...
var input = [
    {
        "id": "01",
        "language": "Java",
        "edition": "third",
        "author": "Herbert Schildt"
    },
    {
        "id": "07",
        "language": "C++",
        "edition": "second",
        "author": "E.Balagurusamy"
    }
];

var result = input.map(function(item)
{
    return item.id;
});

console.log(result);

Or in fancy ES6...
var result = input.map(item => item.id);


text:
Q: Metabase multi filter - "Incorrect syntax near '='" error I have a problem with metabase, I want to count total employee absence from multi table.
I want the result can count based on date I put in the filter.
When I run the query the result show "Incorrect syntax near '='."
Here is my query
SELECT COUNT(*)
FROM Name_tbl p, period_tbl epr, Data_tbl e
LEFT JOIN Name_tbl ps ON e.person_id = ps.person_id
LEFT JOIN absence_tbl ec ON e.company_id = ec.company_id
                         AND e.id = ec.id
                         AND ec.absence_date = [[{{validdate}}]]
LEFT JOIN absence_detail_tbl ect ON ec.company_id = ect.company_id
                                 AND ec.id = ect.id
                                 AND ect.absence_date = [[{{validdate}}]]
WHERE e.person_id = p.person_id
  AND e.company_id = epr.company_id
  AND e.id = epr.id
  AND epr.valid_to >= [[{{validdate}}]]

Can you guys help me to fix it??
thank you


text:
Q: Access denied on vsftps while writing a file I installed vsftpd on ubuntu 13.04 server
write is enabled
im able to login as authenticated user - i own /home/luby directory and it's chmod 7777, when trying to write to it i get 550 Access is denied. why?

A: Did you enable writes in your /etc/vsftpd.conf ? Writes are disabled by default, so if you just installed the package then you need to edit your config file and restart the service. You can refer to the link below, the information for enabling writes is located in the "User Authenticated FTP Configuration" section.
Ubuntu FTP Server Guide


text:
Q: Updating complex objects in database with AutoMapper - how to ignore nested objects for one time map? Let me explain a bit. Here are my classes:
// ClassOne
int ID
string Name
ClassTwo ClassTwoExample

// ClassTwo
int ID
string Name
ClassThree ClassThreeExample
ClassFour ClassFourExample

// ClassThree
int ID
string Name

// ClassFour
int ID
string Name

So you get the general gist of it. ClassOne is my main / parent class and holds ClassTwo. ClassTwo holds a ton of information and references to even more classes. ClassThree and ClassFour are just reference classes which I do not need to modify.
My goal is to update the properties in ClassOne and the basic properties in ClassTwo (ignoring ClassThree and ClassFour). However, when I go to update using AutoMapper (_mapper.Map(..,..)), it's also trying to map ClassThree and ClassFour which end up being null and the database tries saving them.
Here is my mapping method:
// Mapping snippet
function (ClassOne model) {
    var oldClassOne = _repos.GetClassOne(model.ID);
    _mapper.Map(model, oldClassOne)
    await _repos.SaveAllAsync();
}

Is there anywhere in that piece of code where I can tell AutoMapper to ignore specific properties and just specifically map what I want it to?

A: Initialize your Mapper like this
public class AutoMapperConfig
{
    public static void RegisterMappings()
    {
        Mapper.Initialize(m =>
        {
            m.CreateMap<ClassOne, ClassOne>().ForMember(d => d.ClassTwoExample.ClassThreeExample, s => s.Ignore())
                                             .ForMember(d => d.ClassTwoExample.ClassFourExample, s => s.Ignore());
        });
    }

}


text:
Q: Issues when add cordova to my existing ios project: cordovaSettingForKey:]: unrecognized selector sent to instance I tried to add cordova project into my existing ios project. I can successful compile the app.   But when I run it, I got this exceptions for cordovaSettingForKey.
-[__NSDictionaryM cordovaSettingForKey:]: unrecognized selector sent to instance 0x147052a30
EXCEPTION THROW: -[__NSDictionaryM cordovaSettingForKey:]: unrecognized selector sent to instance 0x147052a30
Anyone knows how to resolve the problem
Here is the header file
#import <Cordova/CDVViewController.h>
#import <Cordova/CDVCommandDelegateImpl.h>
#import <Cordova/CDVCommandQueue.h>

@interface MainViewController : CDVViewController

@end

@interface MainCommandDelegate : CDVCommandDelegateImpl
@end

@interface MainCommandQueue : CDVCommandQueue
@end

Here is the .m file
#import "MainViewController.h"

@implementation MainViewController

- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    // View defaults to full size.  If you want to customize the view's size, or its subviews (e.g. webView),
    // you can do so here.

    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return [super shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}

/* Comment out the block below to over-ride */

/*
- (UIWebView*) newCordovaViewWithFrame:(CGRect)bounds
{
    return[super newCordovaViewWithFrame:bounds];
}
*/

@end

@implementation MainCommandDelegate

/* To override the methods, uncomment the line in the init function(s)
   in MainViewController.m
 */

#pragma mark CDVCommandDelegate implementation

- (id)getCommandInstance:(NSString*)className
{
    return [super getCommandInstance:className];
}

- (NSString*)pathForResource:(NSString*)resourcepath
{
    return [super pathForResource:resourcepath];
}

@end

@implementation MainCommandQueue

/* To override, uncomment the line in the init function(s)
   in MainViewController.m
 */
- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

@end

Here is how I call it
MainViewController * layer = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];

Thanks
-Emmy

A: try adding -ObjC to your target's "Other Linker Flags".   Note: the cordova docs say it is the "-Obj-C" flag, which will not resolve the issue.
https://cordova.apache.org/docs/en/latest/guide/platforms/ios/webview.html


text:
Q: Django-Guardian Permissions - Set permissions for objects in a on-to-many relationship I have the following models:
Project:
class Project(models.Model):
    project_name = models.CharField(max_length=100, unique=True)

SearchCodes:
class SearchCode(models.Model):
   project = models.ForeignKey(Project, on_delete=models.CASCADE)
   search_code = models.CharField(max_length=3)
   search_code_modifier = models.CharField(max_length=1)

   class Meta:
     unique_together = ('project', 'search_code', 'search_code_modifier',)

From the Django-Guardian docs I am able to set permissions in the Django admin. Then for a Project I can check/restrict users in a view like so:
def project_edit(request, pk_project):

   project = get_object_or_404(Project, pk=pk_project)
   project_name = project.project_name

   user = request.user

   # Check user permission at the object level by passing in this specific project
   if user.has_perm('myApp.change_project', project):
      ...do something

Now here is where I am stuck. How do I set permissions on ANY SearchCodes that are related to a Project in the Django-Admin? I don't want to set object-level permissions on the SearchCodes - That would just be every instance of SearchCode. Rather I need to be able to set in the Admin:
You can view every SearchCode that is related to this Project BUT not any other SearchCodes.
Please let me know if I need to be more specific - I have tried to keep this as generic as possible.
Thank you - any help or pointers would be greatly appreciated.
EDIT:
I used the Admin-Integration example to set up the Project object-level permissions in Django-Guardian.
It feels like at this point there must be some way to set the permissions for all SearchCodes that are related to this particular instance of Project while I am in the Object-Permissions page for this Project.

A: Django-guardian is object level permission application, so assign permission on object which carry permission and check on that object for permission. In you particular example you have to write something like that to check permissions for code through project (permission carry object):
def code_edit(request, pk):

   code = get_object_or_404(SearchCode.objects.select_related('project'), pk=pk)
   project = code.project
   project_name = project.project_name

   user = request.user

   # Check user permission at the object level by passing in this specific project
   if user.has_perm('myApp.change_project', project):
      ...do something


text:
Q: Plotting bar plots with R Am trying to create an R dodged geom bar with this data but am not getting a plot that i need
  Department              Male Female
  <chr>                  <int>  <int>
1 "Admin Offices"            3      6
2 "Executive Office"         0      1
3 "IT/IS"                   28     22
4 "Production       "       83    126
5 "Sales"                   16     15
6 "Software Engineering"     5      6

What i tried seems pretty wrong so anyone can help

A: I can only guess what you need actually. However The result could be this:
library(dplyr)
library(tidyr)
library(ggplot2)
df<-data.frame(Department = c("Admin Offices",
                              "Executive Office" ,
                              "IT/IS",
                              "Production",
                              "Sales",
                              "Software Engineering" ),
               Male = c(3, 0, 28, 83, 16, 5),
               Female = c(6, 1, 22, 126, 15, 6))

df %>% pivot_longer(cols = c("Male", "Female")) %>%
  transmute(Department, Gender = as.factor(name), Value = value) %>%
  ggplot() +
  geom_bar(aes(x = Department, y = Value, fill = Gender), stat = "identity", position = position_dodge(0.9))

A: And the same with barplot from base R:
df<-data.frame(Department = c("Admin Offices",
                              "Executive Office" ,
                              "IT/IS",
                              "Production",
                              "Sales",
                              "Software Engineering" ),
               Male = c(3, 0, 28, 83, 16, 5),
               Female = c(6, 1, 22, 126, 15, 6))
barplot(t(df[,-1]), beside=T,
        names.arg=df$Department,
        legend.text=names(df[,-1]))


text:
Q: Why "unique" field in creating a schema does't work? I have a schema and i want the username field to be unique but it's not working (The "required" works normally). What i did try: restart mongodb, drop database. May i know what i am missing ?
Here is my schema:
import mongoose, { HookNextFunction, model } from 'mongoose';
import bcrypt from 'bcrypt';
import { AdminDocument } from '../interfaces';

const AdminSchema = new mongoose.Schema(
  {
    username: { type: String, unique: true, required: true },
    email: { type: String, unique: true, required: true },
    password: { type: String, required: true },
    role: { type: Number, enum: [0, 1], required: true },
    address: { type: String },
    phone: { type: String, required: true },
    photo: { type: String, default: null },
    name: { type: String, required: true },
    gender: { type: Number, enum: [0, 1, 2], required: true },
    refreshToken: { type: String, default: null },
  },
  { timestamps: true }
);

AdminSchema.pre('save', async function (next: HookNextFunction) {
  let user = this as AdminDocument;

  if (!user.isModified('password')) {
    return next();
  }
  const salt = await bcrypt.genSalt(Number(process.env.SALT_WORK_FACTOR));
  const hashedPassword = await bcrypt.hash(user.password, salt);

  user.password = hashedPassword;

  return next();
});

AdminSchema.methods.comparePassword = async function (
  candidatePassword: string
) {
  const user = this as AdminDocument;
  const isValid = await bcrypt.compare(candidatePassword, user.password);
  return isValid;
};

export default model<AdminDocument>('Admin', AdminSchema);

A: In Mongoose connection script enable these options useCreateIndex and autoIndex to become true.
mongoose
    .connect('connection url', {
        useUnifiedTopology: true,
        useNewUrlParser: true,
        useCreateIndex: true, //make this true
        autoIndex: true, //make this also true
    })
    .then(() => {
        console.log('Connected to mongoDB');
    });

then drop the schemas from your db.

A: I have solved this by creating an index using mongodb compass. But the problem is that i can not use the schema.index() method to createIndex for username field and i have also tried set the index: true and unique: true in username property, both are not working. Why is that ?
Here is what i have tried on mongoose schema index method:
AdminSchema.index({ username: 1 }, { unique: true });
console.log(AdminSchema.indexes());


text:
Q: Elements of $\sigma(T)$ if $T^m = T^n$ for $m>n$
Suppose we have a complex Hilbert space $H$ and a $T \in B(H)$ such that $T^m = T^n$ for some integers $m > n \geq 1$. If $\lambda \in \sigma(T)$, then $\lambda = 0$ or $\lambda^{m-n} = 1$.

I think the way to prove this is by using $\sigma(T^{m-n}) = \sigma(T)^{m-n}$. Because if $\lambda \in \sigma(T)$, then $\lambda^{m-n} \in \sigma(T^{m-n})$, so $T^{m-n} - \lambda^{m-n}I$ is not invertible. Therefore $T^n(T^{m-n} - \lambda^{m-n}I) = T^m - \lambda^{m-n}I$ is not invertible, and using $T^m = T^n$ we see that $T^n(1-\lambda^{m-n})$ is not invertible. This means that either $T^n$ is not invertible or $\lambda^{m-n} = 1$. If $T^n$ is not invertible, then $T$ is not invertible, so $0 \in \sigma(T)$. However, we can't conclude that $\lambda = 0$.
Is this the right way or is there a better method?

A: by the Spectral Mapping Theorem, $\{0\} = \sigma(T^m - T^n) = \{\lambda^m - \lambda^n : \lambda \in \sigma(T)\}$.  If $\lambda^m - \lambda^n = 0$, then either $\lambda = 0$ or $\lambda^{m-n} = 1$.


text:
Q: Need help pinpointing cause of nil reference error in middleware test (Golang) I've run up against an "invalid memory address or nil pointer dereference" error while writing unit tests for my http handlers--specifically, authentication middleware.
Here is the function to be tested:
func Authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    var err error
    ck, err := req.Cookie("session")
    if err != nil {
        w.Header().Add("Authorization", "expired/invalid")
        next.ServeHTTP(w, req)
        return
    }

    r, err := env.Db.VerifySession(ck.Value)
    if err != nil {
        http.Error(w, http.StatusText(500), http.StatusInternalServerError)
        return
    }
    if r == "expired/invalid" {
        ck.MaxAge = -1
        http.SetCookie(w, ck)
        w.Header().Add("Authorization", r)
        next.ServeHTTP(w, req)
        return
    }

    w.Header().Add("Authorization", r)
    next.ServeHTTP(w, req)
})
}

The specific test case on which the error is thrown:
rec = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/", nil)
c := &http.Cookie{
    Name:  "session",
    Value: "success",
}
req.AddCookie(c)
routes.Authenticate(http.NotFoundHandler()).ServeHTTP(rec, req)
assert.Equal("admin", rec.Header().Get("Authorization"))

The mocked version of env.DB.VerifySession used for testing:
func (mdb *mockdb) VerifySession(val string) (string, error) {
switch val {
case "success":
    return "admin", nil
case "failure":
    return "expired/invalid", nil
default:
    return "", errors.New("500")
}
}

I have written a passing test for the the first part of Authenticate(): if no "session" cookie is found, the test confirms that the response header's been appropriately updated. However, when I pass in a "session" cookie, as with the test case above, Authenticate() will run up tor, err := env.Db.VerifySession(ck.Value). Attempting to step over or into that function call in debug mode results in the nil pointer error being thrown.
I don't think the problem is the env.Db variable, as I've successfully run a suite of tests on my non-middleware handlers using the same variable without issue.
I can also confirm through debugging that the "session" cookie does actually exist.
Any guidance on what's going on here would be greatly appreciated.

A: Nevermind, I realized what the issue is. For my other routes I pass the env variable in as an argument. I need to find a way to provide the middleware with access to it as well.
I suppose I'll define the middleware as a method on env.


text:
Q: Driver to split audio to 2 different devices? I recently bought one of these USB headsets against my own better judgement, and it's really costing my sanity at this point.  Previously when using a standard jack, I just used a splitter so I could split off the things I was doing with my TV or headset, I could just turn the TV off or the headset volume down should I want to use one at a time.
Now, along comes this USB headset and I find that I can't choose for the sound of 1 application to pipe to 2 different devices on Windows; How can I solve this?  Does any software out there exist for this purpose?

A: Unfortunately, Windows processes sound through either one device or the other. My experience is that if you need usb sound for some reason, you're better off with something like this that let's you plug in anything you want (including a splitter, and at <$4 the price is right, too).


text:
Q: How does convolution work in stats::filter I read few answers that deal with stats:filter they've made it clear partially how convolution works (the part to do with coefficients arrangement), but there are other bits to it.
example:
# convolution with 3 coefficients in filter
filter(1:5,c(f1,f2,f3),method="convolution")
[1] NA  6  9 12 NA

#equivalent to:
 NA  * f3 + x[1] * f2 + x[2] * f1  #x[0] = doesn't exist/NA
x[1] * f3 + x[2] * f2 + x[3] * f1
x[2] * f3 + x[3] * f2 + x[4] * f1
x[3] * f3 + x[4] * f2 + x[5] * f1
x[4] * f3 + x[5] * f2 + x[6] * f1 #x[6] also doesn't exist

I don't understand where's that X[0] come from; I thought we'd start from x[1]. I suspect this may be to do with the offset mentioned in help document for stats::filter.

The convolution filter is
y[i] = f[1]*x[i+o] + … + f[p]*x[i+o-(p-1)]
where o is the offset: see sides for how it is determined.
sides: for convolution filters only. If sides = 1 the filter
  coefficients are for past values only; if sides = 2 they are centred
  around lag 0. In this case the length of the filter should be odd, but
  if it is even, more of the filter is forward in time than backward.

I am still as confused as it gets. I don't see how sides explain the offset and not sure that the x[0]' was due to offset.
how does convolution really works in stats::filter?

A: Probably you should learn on what convolution is. Start from the simplest. ie convolving two signals. I will just describe the details. But you could search the WHY onnline.
So filter(1:5,c(f1,f2,f3),method="convolution"), uses the default of 2 sides. That is the filter the filter will be centered and if not possible, then the larger end will be into the data. The computation begins where the center of the filter coincides with the first value of the signal. Recall that since the filter is being rolled over the signal, it must be less or equal to the length of the signal. Here is an example.
if the filter is c(1,2,3) for example then we will center it at 2.
thus to convolve c(1,2,3,4,5) with c(1,2,3), we first reverse the filter then rollapply it throughout the signal:

step 1

    1  2  3  4  5
 3  2  1
  We see that 3 is not multiplied by anything! Thus `3*NA + 2*1+1*2 = NA`

We then move the filter one step and do the math again

     1  2  3  4  5
     3  2  1
   Here all the values are present: 3*1+2*2+1*3 = 10

The third step:

  1  2  3  4  5
     3  2  1
  3*2+2*3+1*4 = 16

We repeat this until the centered value ie 2 coincides with the last value.
If you choose side = 1 then it will not center but rather start by coinciding the last value of the filter with the first value of the signal and finish  by coinciding the last value of the filter with the last value of the signal.


text:
Q: How can I make sure I fully secured my AWS S3 Bucket? I am trying to make sure I have my S3 bucket secure. I need to allow some sort of public access due to my website displays the images that are uploaded to my S3 bucket.
My Public Access settings look sleek this:

I then set up my Cross-origin resource sharing (CORS) to look like this:
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST"
        ],
        "AllowedOrigins": [
            "https://example.com",
            "https://www.example.com"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

And my S3 ACLs look like this:

After doing this my images are still visible on my website hosted on AWS. My question here is am I missing anything?
I don't think I fully understand the Cross-origin resource sharing (CORS) of this. I assumed the AllowedOrigins tag would only allow the images to be viewed on my domain? So I took the address to one of my images and threw it in my web browser and it loaded. Is this correct behavior or am I misunderstanding this?
Any more suggestions on how to secure my S3 bucket? I basically just want user on my website to be able to view my images and upload images from only my site. Thanks!
Updates
For a more full view, my bucket policy is:
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::example.com.storage/*"
        }
    ]
}

My ACLs in S3 are configured as:

A: You asked "how to secure my S3 bucket?"
Buckets in Amazon S3 are private by default, so they are automatically 'secure'. However, you want to make the objects (eg images) accessible to users on your website, so you need to open sufficient access to permit this (as you have successfully done!).
In fact, the only elements you actually needed were:

*

*On "Block Public Access", allow Bucket Polices (Done!)

*Create a Bucket Policy that grants GetObject to anyone (Done!)

You only need the CORS settings if you are experiencing a particular problem, and there is no need to change the Bucket ACLs from their default values.
The bucket policy is only allowing people to download objects, and only if they know the name of the object. They are not permitted to upload objects, delete objects or even list the objects in the bucket. That's pretty secure!
Your settings are fine for publicly-accessible content that you are happy for anyone to access. If you have any personal or confidential content (eg documents, or items requiring login) then you would need an alternate way of granting access only to appropriately authorized people. However, this doesn't seem to be a requirement in your situation.
Bottom line: You are correctly configured for granting public read-only access to anyone, without providing any additional access. Looks good!

A: Amazon CloudFront (CF) is often used for serving content from S3 buckets without needing the buckets to be public. This way your website would server your images from CF, rather than directly from the bucket. CF would fetch and cache the images from the bucket privately.
The way it works is that in your bucket, you would setup a special bucket policy which would allow a CF user, called origin access identity (OAI), to access your bucket.
The use of CF and OAI to serve your images from your bucket not only keeps your bucket fully private, but also reduces load times as CF caches the images in its edge locations.
More details on this are in:

*

*Restricting Access to Amazon S3 Content by Using an Origin Access Identity

*Amazon S3 + Amazon CloudFront: A Match Made in the Cloud

*How do I use CloudFront to serve HTTPS requests for my Amazon S3 bucket?


text:
Q: Can we install multiple Domino servers in single Domain? Can we install 2 Domino server in a single domain?
Can we install a Domino and a MS Exchange server in a single domain?

A: lets answer this at the same detail level as the question: Yes you can...


text:
Q: MOSFET off state at certain voltage? I'm new to electronics and today I've discovered MOSFET transistors. It lets the current flow between source and drain terminals, when the voltage, applied to gate terminal, reaches a certain level. But I want a MOSFET (if it's still a MOSFET) that is normally letting the current flow between S and D, and is cutting the flow when the voltage applied to the gate terminal reaches a certain level.
So what kind of a device do I need?

A: You can invert the input of the mosfet with 2 resistors and a regular NPN transistor. R1 will pull the Gate of the mosfet high when the input is Low. When you put a High on the input the NPN transistor will pull the voltage on the Gate back to ground

simulate this circuit – Schematic created using CircuitLab

A: You can go for any of the following:

*

*Depletion channel MOSFET (\$De\$-MOSFET), eg: LN150

*Junction Field Transistor (JFET), eg: 2N5457
These devices (n-channel) are normally ON ans you need a negative voltage at gate with respect to source to turn it OFF.

A: "...I want a MOSFET that is normally letting the current flow between S and D, and is cutting the flow when the voltage applied to the gate terminal reaches a certain level...."
I suppose you mean that the control voltage will vary in analog way. Thus, the OFF - ON (or ON - OFF) transition fot the drain current will not be exactly "digital". In other words, reach \$Vgs_{th}\$ just causes the beginning of the mosfet conduction - enlarging the channel width. Maybe you need an analog comparator instead.


text:
Q: Moving 3D charracter - I don't want any physics, expected of collisions, and gravity I am working on a game. I constructed my player as here: (I am using a gravity on my world)
private ArrayMap<String, GameObject.Constructor> constructors = new ArrayMap<String, GameObject.Constructor>(String.class, GameObject.Constructor.class);

private ArrayList<GameObject> instances = new ArrayList<GameObject>();

assets.load("hand.obj", Model.class);
...
    model = assets.get("hand.obj", Model.class);
        constructors.put("hand", new GameObject.Constructor(model, new btBoxShape(new Vector3(2.5f, 7.5f, 2.5f)), 1f));
...
    hand = constructors.get("hand").construct(); // that construct method returns me model, shape and constructions.. the GameObject extends ModelInstance, so i can use it like a modelinstance
        hand.transform.setToTranslation(x, y, z);
        hand.body.proceedToTransform(hand.transform);
        hand.body.setUserValue(instances.size());
        hand.body.setCollisionFlags(hand.body.getCollisionFlags()| btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK);
           world.addRigidBody(hand.body);
           hand.body.setContactCallbackFlag(OBJECT_FLAG);
           hand.body.setContactCallbackFilter(OBJECT_FLAG);

Then, in render method I am moving it:
if (!hand.body.isActive()) hand.body.activate();
        if (Gdx.input.isKeyPressed(Keys.W)){
        hand.body.translate(new Vector3(0,0,-1));
        }
        else if (Gdx.input.isKeyPressed(Keys.S))    {
            hand.body.translate(new Vector3(0,0,+1));
        }

That's nice! The moving now works good, when I am moving at the flat ground. Whenever there is an object before me, it is not as expected. Because my player shape is biger than
 object shape (which is 2.5f, 2.5f, 2.5f), it kind of falls on it. So I would like to set the rotation to be still the same, so the object will not be rotating (so it will not "fall" on the object before). And so I tried to do it, and I failed. Because there are functions like rotate, and I want to something like setRotation
 . And so, there is a setToRotation, but you can not pass there a Quaternion.
I need help. I tried to use a btKinematicCharacterController but it was bad. The ghostObject every time falled through object, but the objects got a collision from him.
and so I want to create a player movment, like in games like Wow, minecraft, and so on.

I looked at the btKinematicCharacterController again. The reason why my ghostobject falled through the ground was. Generally, I don't know the reason: D probably I was using another broadphase for ghost, that for world. This line fixes it: characterController.setUseGhostSweepTest(false);
and I am getting another problem, when I am walking on my ground (a lot of objects), the character is getting to lesser Y position. I don't know why.
Here is my construction:
    btPairCachingGhostObject ghostObject;
    btConvexShape ghostShape;
    btKinematicCharacterController characterController;
    Vector3 characterDirection = new Vector3();
    Vector3 walkDirection = new Vector3();
...

       ghostObject = new btPairCachingGhostObject();
               ghostObject.setWorldTransform(hand.transform);
               ghostShape = new btCapsuleShape(5f, 0.5f);
               ghostObject.setCollisionShape(ghostShape);
               ghostObject.setCollisionFlags(btCollisionObject.CollisionFlags.CF_CHARACTER_OBJECT);
               characterController = new btKinematicCharacterController(ghostObject, ghostShape, .00001f);
               // And add it to the physics world
               characterController.setUseGhostSweepTest(false);
               world.addCollisionObject(ghostObject,
               (short)btBroadphaseProxy.CollisionFilterGroups.CharacterFilter,
               (short)(btBroadphaseProxy.CollisionFilterGroups.StaticFilter | btBroadphaseProxy.CollisionFilterGroups.DefaultFilter));
               world.addAction(characterController);
... (in render - moving)
    if (!load)
        {
            if (Gdx.input.isKeyPressed(Keys.LEFT)) {
                hand.transform.rotate(0, 1, 0, 5f);
                ghostObject.setWorldTransform(hand.transform);
                }
                if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
                    hand.transform.rotate(0, 1, 0, -5f);
                ghostObject.setWorldTransform(hand.transform);
                }
                // Fetch which direction the character is facing now
                characterDirection.set(-1,0,0).rot(hand.transform).nor();
                // Set the walking direction accordingly (either forward or backward)
                walkDirection.set(0,0,0);
                if (Gdx.input.isKeyPressed(Keys.UP))
                walkDirection.add(characterDirection);
                if (Gdx.input.isKeyPressed(Keys.DOWN))
                walkDirection.add(-characterDirection.x, -characterDirection.y, -characterDirection.z);
                walkDirection.scl(4f * Gdx.graphics.getDeltaTime());
                // And update the character controller
                characterController.setWalkDirection(walkDirection);
                // And fetch the new transformation of the character (this will make the model be rendered correctly)
        }
        world.stepSimulation(delta, 5, 1f/60f);
        if (!load)
        ghostObject.getWorldTransform(hand.transform);

How to fix this?

A: I set up the debugDrawer, so i was able to see the shapes of the bullet objects.. and my problem was that: the ghostObject(charController) was pushing my objects down.. Although my objects were static. So i set the mass of the objects to 0 and problem is fixed.  But I still dont know, how it could push static objects. But i dont care. :)
EDIT: i will accept this answer in 2 hours, because now i cant.


text:
Q: Cron Job for Django Project not activating I am trying to add a cronjob to my django project that will reset the scores of my game every 1 minutes.
I used cron tab and I think it's my pathing/location of the function that is causing it to not trigger.
Here is the hierarchy of the files and a few files in each of them.
ProjectBackend—
    ProjectBackend—
        - settings.py
        - wsgi.py
        __init__.py
        urls.py
    manage.py
    heroku
    scores—
        admin.py
        cron.py
        models.py
        views.py
        urls.py
        apps.py

In the settings.py above, I have the following : I added only crontab to installed_apps and the cronjob array.
CRONJOBS = [
    ('*/1 * * * *', 'scores.cron.my_scheduled_job')
]
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'scores.apps.ScoresConfig',
    'django_crontab',
]

I have replaced  the cronjob's second parameter with 'ProjectBackend.scores.cron.my_scheduled_job'  and other variations with no luck. I chose 'scores' instead of  'scores.apps.ScoresConfig'  because it is designed as the name in apps.py
I placed the function called my_scheduled_job in the cron.py in the above location.
Right now all the function does is print out a string, which does not show up on Terminal when I do the following in the directory where manage.py is located.
'Python3 manage.py crontab add'
'Python3 manage.py crontab show'

To which it says : Currently active jobs in crontab: ('*/1 * * * *', 'scores.cron.my_scheduled_job')
After this, I do python3 manage.py runserver and nothing happens.
https://pypi.org/project/django-crontab/ I followed this. Do I have everything set up correctly?

A: django_cronjob runs with crontab not with run server command
you can also use your manage command and write your code to that command and add it to crontab manually or when a function called with  python code.

A: It looks like , there is something wrong with configuration of cronjob. You can visit this link given below:
http://django-cron.readthedocs.io/en/latest/sample_cron_configurations.html
You can also visit this link for more description about crontab
https://kite.com/python/docs/celery.task.schedules.crontab


text:
Q: eCommerce / Shop system with good support for GDPR requirements I know this and that but I think my question is valid. Also I couldn't find another, more appropriate StackExchange community for my question.
My task is to replace our legacy webshop with a new one which makes compliance to the GDPR requirements as easy as possible. Until now, I haven't found a shop system with the following features:

*

*guest checkout

*explicit active consent for the different kinds of personal data

*support for parental consent

*software support for customers to see, edit, export and delete ALL their personal data

I imagine if those are fulfilled the company itself would have also made sure that it acts in a GDPR compliant way, so I don't mention this explicitly.


text:
Q: Resolving tasks in VSTS / VSO (Agile Template) I have created a new project in VSTS (Visual Studio Online) using the Agile Template.
I have created a sprint, and added a user-story. Within the user-story I have some tasks.
On the sprint Kanban board there are 4 columns;

*

*New

*Active

*Resolved

*Closed

I can move tasks from New to Active, but cannot move them from Active to Resolved.
How do I do this?

A: This confusing behavior is because the Agile Template shows both Bugs and Tasks on the same board view. While Tasks have a New -> Active -> Closed workflow, bugs have an additional Resolved step.
Your task should transition directly from Active to Closed.
You bugs will be able to rest a bit in the Resolved column before being dragged all the way to Closed.

A: To recall your question:
I can move tasks from New to Active, but cannot move them from Active to Resolved.
This is also not a problem in Azure DevOps but the standard process (Agile workflow states). The following are the steps that can be used for the workflow in the standard process:

*

*User Story (New, Active, Removed, Resolved, Closed)

*Bug (New, Active, Resolved, Closed)

*Task (New, Active, Removed, Closed)

In Azure DevOps, however, this workflow can be adapted. For this the process must be modified. Here you can also add Resolved for a task within the workflow. Role "Collection administrator" is needed.
via Organization settings / Boards / Process / Agile (default) ... Create inherited process
Further information and picture source under https://learn.microsoft.com/en-us/azure/devops/boards/work-items/guidance/agile-process-workflow?view=vsts
and https://learn.microsoft.com/de-de/azure/devops/organizations/settings/work/manage-process?view=vsts&tabs=new-nav#create-inherited-process

A: You need to first create an inherited Process from Agile template as explained here:
https://www.visualstudio.com/en-us/docs/work/process/manage-process#create-inherited-process
Then , you can simple Hide the "Resolved" state for Bugs from your workflow as shown here:
https://www.visualstudio.com/en-us/docs/work/process/customize-process-workflow
That's it! the column is gone from your Task Board!
Moreover: you can now add your own States and Columns.
Good luck!
Michael


text:
Q: Modulo in Assembly x86 So I tried to do a program that does the modulo. I couldn't do so.
I tried using idiv or div but I just couldn't think off a way to do so. I will really appreciate if you can show me how to perform the modulo operation.

A: Modulo operator is % or \ in most assemblers.
The modulo operation represents the remainder after dividend is integer-divided by divisor.
For instance when dividend is 13 and divisor is 5, then the modulo result is 13 % 5 = 3. Unsigned division is provided in x86 by the instruction DIV and it depends on CPU mode:
; 8bit, works with dividend 0 .. (2^16 - 1)      64 KiB
MOV AX, 13  ; dividend
MOV CL,  5  ; divisor
DIV CL      ; Remainder 3 is now in AH, quotient 2 is in AL.

; 16bit, works with dividend 0 .. (2^32 - 1)      4 GiB
MOV AX, 13  ; lower 16 bits of dividend
MOV DX,  0  ; higher 16 bits of dividend
MOV CX,  5  ; divisor
DIV CX      ; Remainder 3 is now in DX, quotient 2 is in AX.

; 32bit, works with dividend 0 .. (2^64 - 1)     16 EiB
MOV EAX, 13  ; lower 32 bits of dividend
MOV EDX,  0  ; higher 32 bits of dividend
MOV ECX,  5  ; divisor
DIV ECX      ; Remainder 3 is now in EDX, quotient 2 is in EAX.

; 64bit, works with dividend 0 .. (2^128 - 1)   256 ???
MOV RAX, 13  ; lower 64 bits of dividend
MOV RDX,  0  ; higher 64 bits of dividend
MOV RCX,  5  ; divisor
DIV RCX      ; Remainder 3 is now in RDX, quotient 2 is in RAX.

It is rather more complicated with signed numbers using signed division IDIV, see the article Modulo on Wikipedia.


text:
Q: Google Deep links error: "Your app's back button doesn't send users back to search results" I have an Android app, and also a website that show the same content.
I setup google deep linking, placing a meta field on each page with the url that matches that content in my android app.
Google is crawling my app and sends me an email stating that "Your app's back button doesn't send users back to search results"
I get instructions to check the app links using applinktest.appspot.com/....
When I do so, if my app is not on the background on the testing device, then the back button works OK, going back to Chrome and the app links test page.
If the app is in the background, then the back button does not go back to the test page, but to the previous activity in the stack. What I'm interpreting is that the activity launched from the link is placed on top of the stack the app in the background had, and as this stack is not empty, then the back doesn't return to the test page but to the previous activity in the stack (still in my app).
I would think the crawler would always launch my app from scratch, and would not find this problem scenario, should I even try to fix it? Maybe the problem the crawler is having is something else... if not I think this would happen to most people implementing google deep linking, but so far I cannot find people complaining about the same scenario.
Anyone having the same problem reported by Google? How did you fixed it?

A: I have the same issue. I clear my app's navigation stack to resolve this. But when I press the back button, it does not go to search results page. Instead everything shuts down (App and google chrome). Now when I click on Google Chrome, search results page is up. @Maria Del Valle Duhagon do you face this issue too?


text:
Q: jQuery works on my page, but firebug says $ is not defined error. Why and how to avoid it? UPDATE: Finally I found the solution, it was totally my fake. There were an iframe tag on the site, and in the external file I didn't include jQuery.
But I learned a lot from your answer and checked my code a lot of time. :)
update END.
Firebug console issues the following error message:
$ is not defined
ajaxlib.js()ajaxlib.js (line 6)
[break on this error] $(document).ready(function()
But jQuery works perfectly on my page.
I include the jQuery source in the first script tag (it was the most commonly suggested solution), so it's should be loaded.
Any help appreciated.
<script language="javascript" type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script language="javascript" type="text/javascript" src="js/advexpad_lib.js"></script>
<script language="javascript" type="text/javascript" src="js/ajaxlib.js"></script>
<script language="javascript" type="text/javascript" src="js/highlight.pack.js"></script>

A: Try changing all $ characters with "jQuery". They are possibly conflicting with an other library you are including.
as in;
$(document).ready(function() {} );

to
jQuery(document).ready(function() {} );

A: Based on the error, the problem is in the 3rd script.  Try moving the second script below the 3rd one.  The advexpad maybe overwriting the $ shortcut in their module.  Also including jquery first isn't recommended, but rather required in your case.  Since the 3rd script uses it, you have to have it precede it.


text:
Q: How to Create a Value for key Im trying to have my SKNode have a value forkey that I can access to get a value from. Its just like the name property (skspritenode.name) but I want to be able to have booleans be the value.
This is how I'm trying to create this value.
block.setValue(false, forUndefinedKey: "is-Block")

Then when I try to access it I use this
if block.valueForKey("is_Block") == true {
   //run code here
}

I'm stumped. Any suggestions?
I apologize if this is a little confusing. I'm not good at explaining simple things.

A: The issue is that is_Block does not exist on SKNode.
setValue forUndefinedKey will raise NSUndefinedKeyException by default.
If you had a subclass, you would override this function to do what you want to do.
See https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/BasicPrinciples.html to better understand key value coding.
If you want to have SKNode have a custom variable named is_Block, you are going to have to create an extension for SKNode, and create a property that will store this data for you.
import Foundation
import SpriteKit
import ObjectiveC

extension SKNode{
    var isBlock: Bool {
        get {
            var key = "isBlock";

            guard let block = objc_getAssociatedObject(self, &key) as? Bool
            else{
                print("Error");
                return false
            }
            print("Success");
            return block
        }
        set(newValue) {
            var key = "isBlock";
            print("Setting \(newValue)")
            objc_setAssociatedObject(self, &key, newValue , objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

}

Test in playground:
import Foundation
import SpriteKit
import ObjectiveC

extension SKNode{
    var isBlock: Bool {
        get {
            var key = "isBlock";

            guard let block = objc_getAssociatedObject(self, &key) as? Bool
            else{
                print("Error");
                return false
            }
            print("Success");
            return block
        }
        set(newValue) {
            var key = "isBlock";
            print("Setting \(newValue)")
            objc_setAssociatedObject(self, &key, newValue , objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

}

let a = SKNode()
let b = SKNode()

a.isBlock = false
b.isBlock = true
print ("\(a.isBlock), \(b.isBlock)")

b.isBlock = false
a.isBlock = true
print ("\(b.isBlock), \(a.isBlock)")


text:
Q: REGEX match unlimited of one character but only two of another I would like to capture a string with the longest possible amount of one character followed by no more than two of another character.
Example:
aaaaabbbbbbbb

Would capture:
aaaaabb, bb and b

I have tried:
(a*)(b)(?!\2{2})

but this is only grabbing the two b's like so:
bb

A: a*b{0,2}

This matches any number of a followed by up to 2 b.
When using your input, it matches
aaaaabb
bb
bb
bb

Since {0,2} is greedy, it always matches pairs of b, not just a single one. It matches all the remaining bb because they're preceded by zero a, which is matched by a*.
DEMO


text:
Q: Name of author who wrote books for pre-teens and teens about "classic" sci-fi and horror movies I had two books by this author back in the 1980s when I was a teenager. Both books were pretty thin paperbacks (no more than 100 or so pages). One book was about science fiction movies, mostly from the 1950s. I remember the cover of the book had one or two of the spaceships from the original "War of the Worlds," along with one of the aliens. I think that one of the big-brained aliens from "This Island Earth" was on the cover too.
The horror/monster movie book featured a lot of Ray Harryhausen movies, Japanese kaiju movies, and the omnipresent giant bug movies of the 1950s. This book featured Gorgo (England's answer to Godzilla) and Rodan on the cover.
I've been wracking my brain trying to remember the names of both books, along with the author's name. Like I said, he wrote both books. Thanks!!!

A: Your description of the horror book reminds me of something that I had a long times ago (must have been mid 1970s). I'm pretty sure it was called "Monsters from the Movies".
Google turns up one book with this title (possibly aka "Movie Monsters") by Thomas G Aylesworth.
Not much official info (amazon have some reviews)
I can't find an equivalent SF book by the same author however.


text:
Q: Response.Write("OK") gives error Object required: "" in VBScript What should I do to use Response.Write in VBScript?
Everything else works fine up to this statement.
I never used VBScript before...
The code, which is my first in VBScript and is being written incrementally, works OK with exception of these objects:
 WScript.Echo Response.Write Print

I have enabled ASP but I couldn't find a way to install these objects on my PC, which acts as a development server. The production website uses VBScript, ASP and SQL Server. Here is the code:
'...

Do While Not Rs.EOF

AllTerms = AllTerms & Rs("Term")
Rs.MoveNext

Loop

MsgBox AllTerms

' @ Print AllTerms

' WScript.Echo AllTerms

' Response.Write Rs("Term")

Rs.Close

A: Are you using ASP? Response is part of the ASP object model. It's not available when running a VBScript under the Windows Script Host.
Edit:
I see you've updated your code and it looks like you are indeed using ASP. Since you're collecting all of the recordset info in a variable named AllTerms, you should be able to display it using the line:
Response.Write AllTerms    ' Use this in place of: MsgBox AllTerms

But if you're new to ASP, you may want to just create a simple page just to test your configuration. Something like this should do:
<%
    Response.Write "Today is " & Date
%>

Save it with an .asp extension, request the page from the web server, and make sure the output is proper.


text:
Q: Navigate user to loaded geojson object in leaflet map How to navigate a user to a loaded geojson in leaflet map?
When application is loaded i get the map center from the props which are hard coded. I have a checkbox and whet it is press it loads polygon on the map and when it is loaded i want automatically navigate to it, not search with the mouse on the map....
render() {
    const position = [this.state.lat, this.state.lng];
    const { profile } = this.props;
    if (profile.role === "User" || profile.role === "Admin") {
      console.log("User role", profile.role);
      console.log("URL", this.state.url);
      const basemapsDict = {
        osm: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        hot: "https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png",
        dark: "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}@2x.png",
        cycle: "https://dev.{s}.tile.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png",
        sentinel:
          "http://services.sentinel-hub.com/ogc/wms/bb1c8a2f-5b11-42bb-8ce4-dbf7f5300663?REQUEST=GetMap&BBOX=3238005,5039853,3244050,5045897&LAYERS=TRUE_COLOR&MAXCC=20&WIDTH=320&HEIGHT=320&FORMAT=image/jpeg&TIME=2018-03-29/2018-05-29",
      };
      return (

          <HorizontalLinearStepper />

          <Map
            style={{ height: "50vh" }}
            center={position}
            zoom={13}
            onClick={this.handleClick}
            onCreate={this.onCreate}
            onLocationfound={this.handleLocationFound}
          >
            <Search />

              Show Geojson
              <input
                style={{ opacity: 1, pointerEvents: "auto" }}
                type="checkbox"
                name="layertoggle"
                id="layertoggle"
                value={this.state.geojsonvisible}
                onChange={this.onGeojsonToggle}
              />

            {this.state.geojsonvisible && (
              <GeoJSON
                data={geojson}
                style={this.geoJSONStyle}
                value={this.state.geojsonvisible}
              />
            )}
            {/* /////////////////////////////////////// */}

            <GeoJSON
              data={london_postcodes}
              style={this.geoJSONStyle}
              onEachFeature={this.onEachFeature}
            />
          </Map>

      );

A: You need to get the map reference and the geojson reference and once you do that you will fit the map bounds around the geojson bounds:
export default class LeafletMap extends Component {
  state = {
    lat: 51.505,
    lng: -0.09,
    zoom: 13
  };

  mapRef = React.createRef();
  geojsonRef = React.createRef();

  pointToLayer = (feature, latlng) => {
    return L.marker(latlng, { icon }); // Change the icon to a custom icon
  };

  bindGeoJson = geojsonRef => {
    const map = this.mapRef.current;
    if (map && geojsonRef) {
      map.leafletElement.fitBounds(geojsonRef.leafletElement.getBounds());
    }
  };

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <Map
        ref={this.mapRef}
        center={position}
        zoom={this.state.zoom}
        style={{ height: "90vh" }}
      >
        <TileLayer
          attribution='&copy OpenStreetMap contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <GeoJSON
          ref={this.bindGeoJson}
          data={dataJson}
          pointToLayer={this.pointToLayer}
        />
      </Map>
    );
  }
}

Demo


text:
Q: Cannot connect to the Jenkins slave machine when running Jenkins as a java prgoram When I set up my Jenkins master using the windows installer version and attempt to connect to a slave machine using "Launch Jenkins via Java webstart", I can connect the slave server to the master fine with no issues.

However, I'm now required to launch the jenkins Master using "java -jar jenkins.war" so I can see the GUI interface being tested in realtime, but I cannot seem to create a connection to the slave machine this way (when I try to access the url on the slave machine, it says it cannot be displayed).

Is it possible to connect with jenkins while it is being run as a java program? Or is there an alternative method I can use?
EDIT: Below is a copy of the console output when I start jenkins on the console.
C:\Program Files (x86)\Jenkins>java -jar jenkins.war
Running from: C:\Program Files (x86)\Jenkins\jenkins.war
webroot: $user.home/.jenkins
Oct 11, 2016 3:07:09 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Logging initialized @279ms
Oct 11, 2016 3:07:09 PM winstone.Logger logInternal
INFO: Beginning extraction from war file
←[33mOct 11, 2016 3:07:09 PM org.eclipse.jetty.util.log.JavaUtilLog warn
WARNING: Empty contextPath
←[0mOct 11, 2016 3:07:09 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: jetty-9.2.z-SNAPSHOT
Oct 11, 2016 3:07:10 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
Jenkins home directory: C:\Users\user\.jenkins found at: $user.home/.jenkins
Oct 11, 2016 3:07:11 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Started w.@1aac487{/,file:/C:/Users/user/.jenkins/war/,AVAILABLE}{C:\Us
ers\user\.jenkins\war}
Oct 11, 2016 3:07:11 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Started ServerConnector@1154ccd{HTTP/1.1}{0.0.0.0:8080}
Oct 11, 2016 3:07:11 PM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Started @1571ms
Oct 11, 2016 3:07:11 PM winstone.Logger logInternal
INFO: Winstone Servlet Engine v2.0 running: controlPort=disabled
Oct 11, 2016 3:07:11 PM jenkins.InitReactorRunner$1 onAttained
INFO: Started initialization
Oct 11, 2016 3:07:11 PM jenkins.InitReactorRunner$1 onAttained
INFO: Listed all plugins
Oct 11, 2016 3:07:14 PM jenkins.InitReactorRunner$1 onAttained
INFO: Prepared all plugins
Oct 11, 2016 3:07:15 PM hudson.ExtensionFinder$GuiceFinder$FaultTolerantScope$1
error
INFO: Failed to instantiate optional component hudson.plugins.build_timeout.oper
ations.AbortAndRestartOperation$DescriptorImpl; skipping
Oct 11, 2016 3:07:16 PM jenkins.InitReactorRunner$1 onAttained
INFO: Started all plugins
Oct 11, 2016 3:07:16 PM jenkins.InitReactorRunner$1 onAttained
INFO: Augmented all extensions
Oct 11, 2016 3:07:16 PM jenkins.InitReactorRunner$1 onAttained
INFO: Loaded all jobs
Oct 11, 2016 3:07:16 PM hudson.model.AsyncPeriodicWork$1 run
INFO: Started Download metadata
Oct 11, 2016 3:07:16 PM hudson.model.AsyncPeriodicWork$1 run
INFO: Finished Download metadata. 4 ms
Oct 11, 2016 3:07:17 PM org.springframework.context.support.AbstractApplicationC
ontext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.StaticWebApplicationCon
text@150b22a: display name [Root WebApplicationContext]; startup date [Tue Oct 1
1 15:07:17 BST 2016]; root of context hierarchy
Oct 11, 2016 3:07:17 PM org.springframework.context.support.AbstractApplicationC
ontext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.supp
ort.StaticWebApplicationContext@150b22a]: org.springframework.beans.factory.supp
ort.DefaultListableBeanFactory@1b4a611
Oct 11, 2016 3:07:17 PM org.springframework.beans.factory.support.DefaultListabl
eBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.
DefaultListableBeanFactory@1b4a611: defining beans [authenticationManager]; root
 of factory hierarchy
Oct 11, 2016 3:07:17 PM org.springframework.context.support.AbstractApplicationC
ontext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.StaticWebApplicationCon
text@10920bb: display name [Root WebApplicationContext]; startup date [Tue Oct 1
1 15:07:17 BST 2016]; root of context hierarchy
Oct 11, 2016 3:07:17 PM org.springframework.context.support.AbstractApplicationC
ontext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.supp
ort.StaticWebApplicationContext@10920bb]: org.springframework.beans.factory.supp
ort.DefaultListableBeanFactory@1403952
Oct 11, 2016 3:07:17 PM org.springframework.beans.factory.support.DefaultListabl
eBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.
DefaultListableBeanFactory@1403952: defining beans [filter,legacy]; root of fact
ory hierarchy
Oct 11, 2016 3:07:17 PM org.jenkinsci.main.modules.sshd.SSHD start
INFO: Started SSHD at port 56276
Oct 11, 2016 3:07:17 PM jenkins.InitReactorRunner$1 onAttained
INFO: Completed initialization
Oct 11, 2016 3:07:17 PM hudson.WebAppMain$3 run
INFO: Jenkins is fully up and running


text:
Q: Add prefix to each word of each line if it does not exist in bash I have an output CSV file like below and need to add a prefix if mrt WORD does not exist in the CSV file.
mrt/abc .1, mrt/def .3, mrt/mlz .4, mrt/gyt .5, abc-d .6, lbr-e .7,

Please advise.

A: Assuming: you want to add "mrt/" to any field that is missing that prefix:
With a perl one-liner:
perl -pe 's{, (?!mrt/)}{, mrt/}g' file.csv

With bash:
IFS=","
while read -ra fields; do
    fields=("${fields[@]/# /}")
    for ((i=0; i<${#fields[@]}; i++)); do
        [[ ${fields[i]} == mrt/* ]] || fields[i]="mrt/${fields[i]}"
    done
    echo "${fields[*]}"
done < file.csv

outputs
mrt/abc .1,mrt/def .3,mrt/mlz .4,mrt/gyt .5,mrt/abc-d .6,mrt/lbr-e .7


text:
Q: React-plotly set default coordinates which the plot is center about How can I set a default zoom level and center my plot around the origin (0,0)? in react-plotly
I am not sure what options are responsible for this in the layout object.

import React from 'react';
import Plot from 'react-plotly.js';

export default function App() {

  var layout = {
    shapes: [
      {
        type: 'circle',
        xref: 'x',
        yref: 'y',
        x0: -2,
        y0: -1.56,
        x1: 2,
        y1: 2.09,
        opacity: 0.2,
        fillcolor: 'red',
        line: {
          color: 'red'
        }
      }
    ],
    height: 400,
    width: 480,
    showlegend: false,
    dragmode: 'pan'
  }

  return (
    <Plot
      layout={layout}
    />
  );
}

A: Define the x and y axis and use constraintoward: "center". Note you may need to extrapolate the max and min values inside each range from your data if it's not static:
import React from "react";
import Plot from "react-plotly.js";

export default function App() {
  var layout = {
    shapes: [
      {
        type: "circle",
        xref: "x",
        yref: "y",
        x0: -2,
        y0: -1.56,
        x1: 2,
        y1: 2.09,
        opacity: 0.2,
        fillcolor: "red",
        line: {
          color: "red",
        },
      },
    ],
    yaxis: {
      visible: true,
      constraintoward: "center",
      showticklabels: false,
      range: [-10, 10],
    },
    xaxis: {
      visible: true,
      constraintoward: "center",
      showticklabels: false,
      range: [-10, 10],
    },
    height: 400,
    width: 480,
    showlegend: false,
    dragmode: "pan",
  };

  return <Plot layout={layout} />;
}


text:
Q: How to make embedded servlet engine instantiate servlets eagerly? The problem is simple, but I'm struggling a bit already.
Server server = new Server(8080);
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();

That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets.
Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?

A: I'm not sure why using Guice make's Justin's option not work for you.  What exactly is getting injected in?  I'm not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating.
Context context = new Context(server, "/", Context.NO_SESSIONS);
ServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class);
// Do this to force Jetty to instantiate the servlet
mainPageViewHolder.getServlet();
context.addServlet(mainPageViewHolder, "/");

A: Use the Context.addServlet overload that takes a ServletHolder.  ServletHolder is a class that accepts either a Class or a Servlet instance.
Servlet myServlet = new MyServlet();
ServletHolder holder = new ServletHolder(myServlet);
context.addServlet(holder, "/");

This assumes Jetty 6.  I think it will work for Jetty 7 as well.


text:
Q: Probability of particles being in a state $\epsilon_i$ I have a set of $N$ particles that can be in two energy states, $\epsilon_1=0$ and $\epsilon_2=\epsilon$. The probability of a particle being in each state is
$$p_1=\frac{1}{1+e^{-\beta\epsilon}}\\
p_2=\frac{e^{-\beta\epsilon}}{1+e^{-\beta\epsilon}} $$
Where $\beta$ is a positive constant.
I have to find what is the mean number of particle in the state $i$, $i=1,2$. Let's call this number $N_i$.
My reasoning is:
$$\mathbb{E}[N_i]=\sum\limits_{k=1}^Nk\mathbb{P}(N_i=k)$$
and $\mathbb{P}(k=N_i)$ is the probability that exactly $k$ particles are in the state $i$, i.e ${{N}\choose{k}} p_i^k p_j^{N-k}$. Thus, for $i=1$
$$\mathbb{E}[N_i]=\sum\limits_{k=1}^Nk{{N}\choose{k}}\left(\frac{1}{1+e^{-\beta\epsilon}}\right)^k\left(\frac{e^{-\beta\epsilon}}{1+e^{-\beta\epsilon}} \right)^{N-k}=\left(\frac{e^{-\beta\epsilon}}{1+e^{-\beta\epsilon}} \right)^{N}\sum\limits_{k=1}^Nk{{N}\choose{k}}e^{\beta\epsilon k}$$
Which is something difficult to calculate.
However the solution says
$$ \mathbb{E}[N_1]=Np_1=\frac{N}{1+e^{-\beta\epsilon}}$$
And the same for $i=2$.
Are the two equivalent? If not, what is my error?
EDIT: Mathematica says
$$\sum\limits_{k=1}^Nk{{N}\choose{k}}e^{\beta\epsilon k}=e^{\beta\epsilon}(1+e^{\beta\epsilon})^{N-1}N$$
Thus $$ \mathbb{E}[N_1]=\left(\frac{e^{-\beta\epsilon}}{1+e^{-\beta\epsilon}} \right)^{N}e^{\beta\epsilon}(1+e^{\beta\epsilon})^{N-1}N$$
I don't see at all how to reduce this to $Np_1$

A: $$\begin{aligned}\sum_{k=1}^{N}k\binom{N}{k}\left(\frac{1}{1+r}\right)^{k}\left(\frac{r}{1+r}\right)^{N-k} & =\left(\frac{r}{1+r}\right)^{N}\sum_{k=1}^{N}k\binom{N}{k}r^{-k}\\
 & =N\left(\frac{r}{1+r}\right)^{N}\sum_{k=1}^{N}\binom{N-1}{k-1}r^{-k}\\
 & =N\left(\frac{r}{1+r}\right)^{N}r^{-1}\sum_{k=0}^{N-1}\binom{N-1}{k}r^{-k}\\
 & =N\left(\frac{r}{1+r}\right)^{N}r^{-1}\left(r^{-1}+1\right)^{N-1}\\
 & =N\frac{1}{1+r}
\end{aligned}
$$


text:
Q: Error running tutorial samples in JDBC: UnsupportedClassVersionError About Me:
I'm a newer programmer, and not really sure how Apache-Ant works and what it does

Goal:
Run the sample programs in the javaconnector jcdb tutorial

Platform Background:
My machine is OSX 10.5.8 32-bit
"which java" gives "/usr/bin/java", which links to "/System/Library/Frameworks/JavaVM.frameworks/Versions/A/Commands/java"
"which javac" gives "/usr/bin/javac", which links to "/System/Library/Frameworks/JavaVM.frameworks/Versions/A/Commands/javac"
"echo $JAVA_HOME" gives a blank line
Java Preferences app in Applications/Utilities lists four versions of Java: 1.6.0_26_b03-385 (64 bit), 1.5.0_30-b03 (32 bit), 1.5.0_30-b03 (64 bit), 1.4.2_22 (32 bit). Currently the 1.6.0 and the two 1.5.0 versions are checked.
NOTE: There is no Java 1.6 for 32-bit OSX 10.5.8

What I Did:
First I downloaded connector/j unpacked it, moved it to /usr/local/mysql-connector-java, installed it per the README.txt sections 3.1 and 3.2, including modifying CLASSPATH. I already have and use mysql
Next, I got the ant binary distribution for version 1.8.4 and installed it according to the manual. Notably, the manual states apache ant works with Java 1.5. "ant -version" returned the correct version, 1.8.4
Then I  downloaded the tutorial files, unzipped the file into a directory, and modified the build.xml and properties/mysql-build-properties.xml file per the tutorial's instructions.
Finally I complied the package and samples using "ant jar", and created the databases, tables, and populated tables using "ant create-mysql_database". I also ran "ant setup" for good mesure
According to to the tutorial, I should now be able to run the samples by putting my shell at the tutorial directory and running "ant <<sample_name>>" . Therefore, I tried to run the sample suggested by the tutorial, "ant runct".
In the middle of this procedure, I never changed which Java I was using in the Java Preferences in Applications/Utilities; I did try the procedure using both 1.5.0_30 and 1.6.0_26 as described below

My Problem:
After running "ant <<sample_name>>" (for example "ant runct"), I get the following error:

Buildfile: /Users/adam/Desktop/JDBCTutorial/build.xml
runct:
       [java] Exception in thread "main" java.lang.UnsupportedClassVersionError:
  com/oracle/tutorial/jdbc/JDBCTutorialUtilities : Unsupported
  major.minor version 51.0
       [java]   at java.lang.ClassLoader.defineClass1(Native Method)
       [java]   at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
       [java]   at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
       [java]   at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
       [java]   at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
       [java]   at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
       [java]   at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
       [java]   at java.security.AccessController.doPrivileged(Native Method)
       [java]   at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
       [java]   at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
       [java]   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
       [java]   at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
       [java] Java Result: 1
BUILD SUCCESSFUL Total time: 1 second

My Attempts at Self-Rectification:
As far as I can tell from googling, the error has arisen because the files that I downloaded for the tutorial and am attempting to run where compiled with a java other than the one that I am attempting to use to run the files. Therefore, I tried using the 1.6.0 version by putting it at the top of the list in Applications/Utilities/Java_Preferences, and confirming it is being used by using "java -version", and then executing the above procedure. Same error.
I also tried re-unzipping the tutorial and modifying the .xml files same as above, but changed the $JAVA and $JAVAC properties in mysql-sample-properties.xml to point at files in /System/Library/Frameworks/JavaVM.framwork/Versions/1.5.0/Home/bin, i.e. a version whose number I know, as opposed to files in "/usr/bin", which point to files in /System/Library/Frameworks/JavaVM.framwork/Versions/A/Home/bin. I then re-ran "ant jar", "ant create-mysql_database" and "ant setup"; from what I understand this should re-compile the .java files using the compiler I specified(correct?). However, I had the same error when I ran "ant runct"
I also tried the following, both with re-setting $JAVA and $JAVAC in mysql-sample-properties.xml to the default (i.e. /usr/bin/java and /usr/bin/javac), and without resetting. I set $JAVA_HOME in my .profile to /System/Library/Frameworks/JavaVM.framwork/Versions/1.5.0/Home, tested the correct java is used by running which java which returned the above path and java -version which returned 1.5.0_30, and re-ran "ant jar", "ant create-mysql_database" and "ant setup". When I ran "ant runct" I got the same error.
NOTE: The .java files in the tutorial appear to use some objects/syntax added in Java 1.6
A significant problem is I don't know which Java Ant is using.

Additional Questions:
Why does "usr/bin/java(c)" point to version "A"?
What is Java version A???
How do I have a 64-bit java on my 32-bit machine? Is it just emulating a 64-bit machine somehow? If so, does it run slower than 32-bit versions for some tasks?
Why do i have a 64-bit 1.5 Java?
Which Java complier and Java does ant use?
When I change which Java is at the top of the list in Applications/Utilties/Java_Preferences, I can confirm that the machine is using the right default Java by doing "java -version", and can check the path of the Java being used by doing "which java". Regardless of which Java is at the top of the list i.e. being used, "which java" points at "usr/bin/java", which is a shortcut to "/System/Library/Frameworks/JavaVM.frameworks/Versions/A/Commands/java"; this is the same regardless of which version of Java is being used according to Applications/Utilities/Java_Preferences and "java -version"; how is the machine using different versions of Java while pointing to the same directory/file??

A: From ant manual:
Environment Variables

The wrapper scripts use the following environment variables (if set):

JAVACMD - full path of the Java executable. Use this to invoke a different JVM than JAVA_HOME/bin/java(.exe).

So you should have your JAVA_HOME set to a correct Java > 1.5 JDK. However its unclear to me which one Ant is using currently since your JAVA_HOME is not set. You should uninstall 64bits version of Java if you are on a 32bits system I don't think they can work.
I'm not an OSX expert so I'm also troubled by the full path of your javaexecutable, usually it should be in a bin folder whose parent is the one you should set for the JAVA_HOME environment variable (as explained in the Ant manual). You can search on your system for java executables with find -name java -perm +x, maybe you can find a clean java install this way.
Otherwise one of your solutions here is to download a JDK from oracle website, unzip it in a folder like /opt/java_xxx and use that as JAVA_HOME. Its what I did to have for instance java 6 and 7 side by side on my system.


text:
Q: Can't reach certain web site/server via DNS, only with ip I am having trouble getting to a certain server/website online and also connecting to the server with ssh USERNAME@HOSTNAME. Am using a machine with Lubuntu 14.04. I can connect to the server from all other computers I have tried.
My main problem is that I can't get to any websites on the server in a web browser (using Firefox) - the ssh-ing isn't a problem, as I can do it using ssh USERNAME@IP-ADDRESS.
I have also seen that ping HOSTNAME renders the wrong IP-address, so I guess this could be a clue to what's wrong?
Some further info below, if it's useful. I'm new to working with servers and networking, so do say if there is other information needed to say what is wrong.
root@Elizabeth:/# nm-tool | grep "DNS"
DNS: 172.20.10.1
DNS: 172.20.10.1

root@Elizabeth:/# nslookup HOSTNAME
Server:        127.0.1.1
Address:    127.0.1.1#53

Non-authoritative answer:
Name:    HOSTNAME
Address: IP-address # correct IP-address for HOSTNAME

root@Elizabeth:/# ip route
default via 172.20.10.1 dev eth1  proto static
172.20.10.0/28 dev eth1  proto kernel  scope link  src 172.20.10.3  metric 1
172.20.10.0/28 dev wlan0  proto kernel  scope link  src 172.20.10.5  metric 9

(This question is similar to this one, but that question didn't focus on the browsing problem.)

A: DNS at the workstation was sabotaged with:
130.238.39.248  ws1.bmc.uu.se

in /etc/hosts.


text:
Q: F#. Expecting a type supporting the operator '-' but given a function type I'm new to F# and have some compilation problems in this code fragment:
let rec mywhile p f s =
    if p s then s
    else
       let s1 = f s
       mywhile p f s1

let eps = 0.001

let dichotomy f a b =
    let out (a, b) = a
    let c a b = (a + b) / 2.
    out (mywhile (fun (a, b) -> a - b < eps)
        (fun (a, b) -> if f c * f a < 0 then (a, c) else (c, b))
        (a, b))

In particular, here: a - b < eps, then (a, c)

Expecting a type supporting the operator '-' but given a function type. You may be missing an argument to a function.

A: Since c is defined as c : float -> float -> float, and you're writing f c, it must mean that f : (float -> float -> float) -> 'x (for some 'x that we don't know yet).
Since you also write f a, and we already know that f's argument is float -> float -> float, it means that a : float -> float -> float.
And this, in turn means that you can't subtract anything from a. It's a function, not a number. This is what the compiler is telling you.
Usually, when you get yourself in a situation where you don't understand what your type are doing, go ahead and add some type annotations. They will provide anchors for the compiler, sort of walls that the type inference cannot cross, and thus will contain the type inconsistencies.
For example, if you specify the type of f:
let dichotomy (f : float -> float) a b =
   ...

this immediately reveals an error at f c, stating that c was expected to be a float, but actually is a function.
If I understand correctly, what you meant to do is to apply f to (c a b), not to c itself. And then, correspondingly, return that same value in the tuples (a, c) and (c, b):
out (mywhile (fun (a, b) -> a - b < eps)
    (fun (a, b) ->
      let d = c a b
      if f d * f a < 0. then (a, d) else (d, b)
    )
    (a, b))

(also, your zero was an int; I made it into a float by adding a dot after it)


text:
Q: SQL Task Exporting query result to Excel missing rows I am trying to export my query result to an excel file. I did it successfully but when I look to the data instead of showing 12859 it only contains 104
EDIT 1: It only occurs when I added another column.
EDIT 2: Screenshots
It should have

EDIT 3
 Its really weird coz I just found out something weird. The source type of summary column is date

A: I solved it. I just go to Edit Mappings > Edit Sql > and change the data type to LongText


text:
Q: How to access details of a swiped paper-card in iron-swipeable-container I have a swipeable-container with a dom-repeat (firebase data)
<iron-swipeable-container id="teamchat">
    <template is="dom-repeat" items="[[tcmmessages]]" as="tcmmessage">

      <paper-card id="tcmcard" class="swipe item blue" data-index$="[[tcmmessage.__firebaseKey__]]">

          [[tcmmessage.teamname]]
          <paper-icon-button style="color: red;" on-tap="_startChat" icon="communication:chat"></paper-icon-button>

          [[tcmmessage.beitrag]]

          von [[tcmmessage.username]]
          • [[tcmmessage.update]] • [[tcmmessage.uptime]]

      </paper-card>
    </template>
</iron-swipeable-container>

I defined a listener
listeners: {
    'teamchat.iron-swipe': '_onTeamChatSwipe'
    },

I try to access data-index from the swiped paper-card.
_onTeamChatSwipe: function() {

 var card = this.$$('#tcmcard');
 var key = card.getAttribute("data-index");

but after swipe event I can not access data-index of the swiped card.

A: With this.$$('#tcmcard') in the iron-swipe handler, you're querying the local DOM for the swiped element, but it's removed from the DOM before the iron-swipe event fires, so the query would not return what you'd expect.
But you don't need to query for the swiped element because <iron-swipeable-container> fires the iron-swipe event with the swiped element stored in event.detail.target.
Try this:
_onTeamChatSwipe: function(e) {
  var card = e.detail.target;
  var key = card.getAttribute("data-index");

  // simpler syntax to get `data-index`
  // key = card.dataset.index;
}

  <base href="https://polygit.org/polymer+1.4.0/components/">

  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="paper-card/paper-card.html">
  <link rel="import" href="iron-swipeable-container/iron-swipeable-container.html">
  <link rel="import" href="iron-flex-layout/iron-flex-layout-classes.html">

  <x-foo></x-foo>

  <dom-module id="x-foo">

    <template>
      <iron-swipeable-container class="container" on-iron-swipe="_onSwipe">
        <template is="dom-repeat" items="[[items]]">
          <paper-card heading="{{item}}" data-index$="{{index}}" class="layout vertical">

              Swipe me left or right

          </paper-card>
        </template>
    </iron-swipeable-container>
    </template>

  </dom-module>

codepen


text:
Q: SSH proxy problem I used to use follows as my proxy server
 start c:\ssh\plink.exe -N username@mysite.com -pw mypasswd -P 22 -D localhost:8003

Now my company decides to block 22 port and I cannot access the 22 port of my site host directly.But there's one machine that doesn't blocked in my lan and I can use SSH to logon it.So how can I make my proxy via the unblocked machine? Thanks!

A: Basically, in situations like this, you probably want to ditch the SSH-based proxy and use an SSL VPN tyoe of proxy.  Such a proxy makes all your traffic look like HTTPS SSL traffic, and no one's going to block port 443.
A good one to run on Linux is Adito.  It's not trivial to set up, but it works very well.  I would suggest installing this, making sure it's listening on port 443, and playing around with it.  It helps me RDP to my home computer despite my school blocking the port.

A: is mysite.com a machine you control (ie, your home machine)? If so, simply run sshd (the SSH server) on port 80 or 443 (instructions vary per OS).
Then modify your line above to:
 start c:\ssh\plink.exe -N username@mysite.com -pw mypasswd -P 443 -D localhost:8003

If you're going to use port 443, for example.

A: On your machine, do:
plink -L 1234:mysite.com:22 unBlockedUser@unBlockedMachine

(decorate with passwords, actual ssh command, -N etc. to taste) This will forward connections to port 1234 of your machine to port 22 on mysite.com via the un-blocked machine. Then, all you need to do to get your proxy is:
plink -D 8003 -P 1234 mysiteUser@ulocalhost

This will open an ssh connection to port 1234 on the localhost, which will then be forwarded into a tunnel going to the un-blocked machine which will send it to port 22 of mysite.com and end up talking to the ssh server there, so your proxy will behave like normal.


text:
Q: How to Search a specfic value in parse.com? Method checkMobileTableAccount uses to check a phone number in table Account, strMobile is phone number to search.
public boolean checkMobileTableAccount(final String strMobile) {
    result = false;
    ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Account");
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            for (ParseObject user : objects) {
                String mobile = user.getString("phonenumber");
                if (strMobile.equals(mobile)) {
                    result = true;
                    break;
                }
            }
        }
    });
    return result;
}

How can I get result after for loop finished?

A: Just dont use method findInBackground(). Use find() which is not making your request in background.
public boolean checkMobileTableAccount(final String strMobile) {
        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Account");
        try {
            List<ParseObject> objects = query.find();
            for (ParseObject user : objects) {
                String mobile = user.getString("phonenumber");
                if (strMobile.equals(mobile)) {
                    return true;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }


text:
Q: Association between groups of features and outcome variable I am working with a high-dimensional dataset (e.g., ~150 features) and possible confounders (e.g., ~10 features to control). The goal is to identify association with an outcome variable that is categorical. Some example problems where this is relevant are genomics and protoemics. You would have a dataset where each row is an individual and columns are genes. Confounding variables include age, weight, gender, blood pressure, etc. Outcome variable would be a clinical feature, like presence or absence of a disease.
As a first step to approach this problem, I identify individual associations, i.e., perform 150 regressions, and use False Discovery Rate to find significant associations.
In addition, I am interested in identifying groups of features that together are associated with the outcome variable. I do not know a straightforward method for this kind of analysis. Association rule mining comes to mind, but I wanted to know if there are standard procedures that give associations along with their statistical significance. The hypothesis here is that usually it is not an individual gene, but groups of several genes acting together that influence the outcome. There could be more than one group which are associated, and the goal would be to rank those groups by the magnitude of their associations. One possible problems is correlation among the features.
This could sound like an exploratory question, but knowing more about possible directions would also be of great help. The reason is that although I have a fairly broad knowledge of statistics and machine learning, I do not remember seeing these problems in standard textbooks or coursework. Pointers to research papers that detail such methods are welcome too. So are ways to utilize non-traditional methods like decision trees, or neural networks to identify such associations (while being less explainable).

A: Challenging question. Groups of feature variables are likely to show some deeper dependencies. You have a large search space and the optimal classifier is really difficult to find. The discriminative performance of your classifier is the only criterion that is useful in determining whether a subset of features predict your categorical outcome well.
My suggestion is that you perform a parallel search for the most well-performing feature subsets in terms of classifier performance. On such approach is that by Siedlecki and Sklansky. They developed a promising genetic algorithm approach for walking through the feature space. You can use their approach to feature selection with for example neural networks - or random forest classifiers.
Reference
Siedlecki W., & Sklansky J. (1989). A note on genetic algorithms for largescale feature selection. Pattern Recognition Letters, 10 (5), 335–347.


text:
Q: C returning answer through parameters ( refernce) Hy everyone,
pls consider this small code, and help me to figure out, why it's not working?
#include <stdio.h>
#include <stdlib.h>

void setup(int* helo) {
    helo = (int*) malloc(sizeof(int));
    (*helo) = 8;
}

int main(int argc, char* argv[]) {
    int* helo = NULL;
    setup(helo);
    printf("Value: %s \n", (*helo));
    getchar();
    return 0;
}

A: You are looking for one of two options here. You can either take the memory pointer allocation out of the equation, and pass the memory address of a standard variable:
void setup(int* helo)
{
    *helo = 8;
}

int main(int argc, char* argv[]) {
    int helo = 0;
    setup(helo);
    printf("Value: %d\n", helo);
    getchar();
    return 0;
}

Or, if you want to stick with your approach, the signature of your function needs to change to receive a pointer to a pointer:
void setup(int** helo) {
    *helo = (int*) malloc(sizeof(int));
    *(*helo) = 8;
}

int main(int argc, char* argv[]) {
    int* helo = NULL;
    setup(&helo);
    printf("Value: %d \n", (*helo));
    getchar();
    return 0;
}

The reason for this is that setup(int* helo) receives a copy of int* helo declared in main(), and this local copy will point to the same place. So whatever you do with helo inside setup() will be changing the local copy of the variable and not helo from main(). That's why you need to change the signature to setup(int** helo).

A: can you try printf("Value: %d \n", (*helo)); instead of printf("Value: %s \n", (*helo));?

A: c is pass by value. When you pass a parameter to a function, a copy of it is made. You need to receive as pointer to pointer to achieve C++ feature of pass by reference.
void setup(int** helo) {
    *helo = (int*) malloc(sizeof(int));
    (*(*helo)) = 8;
}

And at the call it as -
setup(&helo) ;


text:
Q: UITextField stroke attribute opaque in Swift I am running into a strange issue while working on developing a Meme app. I am trying to create a UITextField that has a black outline with filled white text. I am able to create just a white text field and another that is outlined in black, however I cannot get both simultaneously. Any help would be much appreciated.
Here is the attributes I am assigning to the text field:
let attribs = [
            NSForegroundColorAttributeName: UIColor.whiteColor(),
            NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
            NSStrokeColorAttributeName: UIColor.blackColor(),
            NSStrokeWidthAttributeName: 1.0
        ]
Here is what the app looks like:

A: Apple has a page describing exactly the problem you were facing: Drawing attributed strings that are both filled and stroked. The trick is to change the stroke width to negative:
Swift 4:
let attributes: [NSAttributedStringKey: Any] = [
    .foregroundColor: UIColor.white,
    .font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
    .strokeColor: UIColor.black,
    .strokeWidth: -1 // Change here
]

Swift 2:
let attributes = [
    NSForegroundColorAttributeName: UIColor.whiteColor(),
    NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
    NSStrokeColorAttributeName: UIColor.blackColor(),
    NSStrokeWidthAttributeName: -1 // Change here
]

A: .strokeWidth = 0 yields fill without stroke.
.strokeWidth = positiveNumber yields stroke without fill.
.strokeWidth = negativeNumber yields both stroke and fill.


text:
Q: Define custom error messages on invalid attribute call How do I define custom error messages for specific invalid attribute calls in python?
I wrote a class thats attribute assignment is dependent on the input on instance creation and like to return a more descriptive error message if an unassigned attribute is called:
class test:
    def __init__(self, input):
        if input == 'foo':
            self.type = 'foo'
            self.a = 'foo'
        if input == 'bar':
            self.type = 'bar'
            self.b = 'bar'

class_a = test('foo')

print class_a.a
print class_a.b

On execution I get this error-message
AttributeError: test instance has no attribute 'b'

Instead of that I'd like to get something like
AttributeError: test instance is of type 'foo' and therefore has no b-attribute

A: Override getattr in your class.
class test(object):
    def __init__(self, input):
        if input == 'foo':
            self.type = 'foo'
            self.a = 'foo'
        if input == 'bar':
            self.type = 'bar'
            self.b = 'bar'

    def __getattr__(self, attr):
        raise AttributeError("'test' object is of type '{}' and therefore has no {}-attribute.".format(self.type, attr))

getattr is called when python can't find the attribute normally.  Essentially, it's like an "except" clause when your class raises an AttributeError.