text:
Q: Can I coerce a lifetime parameter to a shorter lifetime (soundly) even in the presence of `&mut T`? I'm trying to make a tree with parent pointers in Rust. A method on the node struct is giving me lifetime issues. Here's a minimal example, with lifetimes written explicitly so that I can understand them:
use core::mem::transmute;

pub struct LogNode<'n>(Option<&'n mut LogNode<'n>>);

impl<'n> LogNode<'n> {
    pub fn child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        LogNode(Some(self))
    }

    pub fn transmuted_child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        unsafe {
            LogNode(Some(
                transmute::<&'a mut LogNode<'n>, &'a mut LogNode<'a>>(self)
            ))
        }
    }
}

(Playground link)
Rust complains about child...

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'n due to conflicting requirements

...but it's fine with transmuted_child.
I think I understand why child won't compile: the self parameter's type is &'a mut LogNode<'n> but the child node contains an &'a mut LogNode<'a>, and Rust doesn't want to coerce LogNode<'n> to LogNode<'a>. If I change the mutable references to shared references, it compiles fine, so it sounds like the mutable references are a problem specifically because &mut T is invariant over T (whereas &T is covariant). I guess the mutable reference in LogNode bubbles up to make LogNode itself invariant over its lifetime parameter.
But I don't understand why that's true—intuitively it feels like it's perfectly sound to take LogNode<'n> and shorten its contents' lifetimes by turning it into a LogNode<'a>. Since no lifetime is made longer, no value can be accessed past its lifetime, and I can't think of any other unsound behavior that could happen.
transmuted_child avoids the lifetime issue because it sidesteps the borrow checker, but I don't know if the use of unsafe Rust is sound, and even if it is, I'd prefer to use safe Rust if possible. Can I?
I can think of three possible answers to this question:

*

*child can be implemented entirely in safe Rust, and here's how.

*child cannot be implemented entirely in safe Rust, but transmuted_child is sound.

*child cannot be implemented entirely in safe Rust, and transmuted_child is unsound.

Edit 1: Fixed a claim that &mut T is invariant over the lifetime of the reference. (Wasn't reading the nomicon right.)
Edit 2: Fixed my first edit summary.

A: The answer is #3: child cannot be implemented in safe Rust, and transmuted_child is unsound¹. Here's a program that uses transmuted_child (and no other unsafe code) to cause a segfault:
fn oops(arg: &mut LogNode<'static>) {
    let mut short = LogNode(None);
    let mut child = arg.transmuted_child();
    if let Some(ref mut arg) = child.0 {
        arg.0 = Some(&mut short);
    }
}

fn main() {
    let mut node = LogNode(None);
    oops(&mut node);
    println!("{:?}", node);
}

short is a short-lived local variable, but since you can use transmuted_child to shorten the lifetime parameter of the LogNode, you can stuff a reference to short inside a LogNode that should be 'static. When oops returns, the reference is no longer valid, and trying to access it causes undefined behavior (segfaulting, for me).

¹ There is some subtlety to this. It is true that transmuted_child itself does not have undefined behavior, but because it makes other code such as oops possible, calling or exposing it may make your interface unsound. To expose this function as part of a safe API, you must take great care to not expose other functionality that would let a user write something like oops. If you cannot do that, and you cannot avoid writing transmuted_child, it should be made an unsafe fn.

A: To understand why the immutable version works and the mutable version is unsound (as written), we have to discuss subtyping and variance.
Rust mostly doesn't have subtyping. Values typically have a unique type. One place where Rust does have subtyping, however, is with lifetimes. If 'a: 'b (read 'a is longer than 'b), then, for example, &'a T is a subtype of &'b T, intuitively because longer lifetimes can be treated as if they were shorter.
Variance is how subtyping propagates. If A is a subtype of B, and we have a generic type Foo<T>, Foo<A> might be a subtype of Foo<B>, vice versa, or neither. In the first case, where the direction of subtyping stays the same, Foo<T> is said to be covariant with respect to T. In the second case, where the direction reverses, it's said to be contravariant, and in the third case, it's said to be invariant.
For this case, the relevant types are &'a T and &'a mut T. Both are covariant in 'a (so references with longer lifetimes can be coerced to references with shorter lifetimes). &'a T is covariant in T, but &'a mut T is invariant in T.
The reason for this is explained in the Nomicon (linked above), so I'll just show you the (somewhat simplified) example given there. Trentcl's code is a working example of what goes wrong if &'a mut T is covariant in T.
fn evil_feeder(pet: &mut Animal) {
    let spike: Dog = ...;

    // `pet` is an Animal, and Dog is a subtype of Animal,
    // so this should be fine, right..?
    *pet = spike;
}

fn main() {
    let mut mr_snuggles: Cat = ...;
    evil_feeder(&mut mr_snuggles);  // Replaces mr_snuggles with a Dog
    mr_snuggles.meow();             // OH NO, MEOWING DOG!
}

So why does the immutable version of child work, but not the mutable version? In the immutable version, LogNode contains an immutable reference to a LogNode, so by covariance in both the lifetime and the type parameter, LogNode is covariant in its lifetime parameter. If 'a: 'b, then LogNode<'a> is a subtype of LogNode<'b>.
We have self: &'a LogNode<'n>, which implies 'n: 'a (otherwise this borrow would outlast the data in LogNode<'n>). Thus, since LogNode is covariant, LogNode<'n> is a subtype of LogNode<'a>. Furthermore, covariance in immutable references again allows &'a LogNode<'n> to be a subtype of &'a LogNode<'a>. Thus, self: &'a LogNode<'n> can be coerced to &'a LogNode<'a> as needed for the return type in child.
For the mutable version, LogNode<'n> isn't covariant in 'n. The variance here comes down to the variance of &'n mut LogNode<'n>. But since there's a lifetime in the "T" part of the mutable reference here, the invariance of mutable references (in T) implies that this must also be invariant.
This all combines to show that self: &'a mut LogNode<'n> can't be coerced to &'a mut LogNode<'a>. So the function doesn't compile.

One solution to this is to add the lifetime bound 'a: 'n, though as noted above, we already have 'n: 'a, so this forces the two lifetimes to be equal. That may or may not work with the rest of your code, so take it with a grain of salt.


text:
Q: Python - making a function library but says my functions are not defined in the secondary file I want to make a user made function library filled with custom functions to use in other codes without having to write all the code and just importing the file, i have defined a function called hello() which prints hello, however when  i try to call it in my secondary file it say the hello() is not defined.
'python library.py'
def hello():
     print("Hello")

'library test.py'
myfile = open('python library.py', 'a')

hello()

A: The open() command is for opening a file as text to read from or write to (principally). Your 'a' is saying you want to append text to the file `'python library.py'
One option to do what you want is to use import to get your functions from the file.
from file import function
in your case
from python library import hello
#NOTE the .py is left off
hello()

If you have multiple functions to import, you can do import * instead of import function. Though I am not sure if this will work having a space in your filename, so if it gives an error, my first suggestion would be to rename your file using an underscore or something so that it's all one word.
More info: How to call a function from another file in Python?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Groovy POST large content using HttpURLConnection I have the below code for doing a POST request to a REST API end point to update SAP application data.
#!/usr/bin/env groovy
import groovy.json.JsonSlurper

def call(total_record, url, bearer_token, scriptId, payload)  {

    Integer tot = total_record as Integer // Convert string to Integer
    HttpURLConnection connection = null;
    if (tot == 1) {
        StringBuilder stringBuilder = new StringBuilder("${url}");
        stringBuilder.append(URLEncoder.encode("${scriptId}", "UTF-8"))
        URL put_url = new URL(stringBuilder.toString());
        connection = (HttpURLConnection) put_url.openConnection()
        connection.setRequestMethod("PUT");
        println("Executing PUT")
    }
    else if (tot == 0) {
        URL post_url = new URL("${url}");
        connection = (HttpURLConnection) post_url.openConnection()
        connection.setRequestMethod("POST");
        println("Executing POST")
    }
    else {
        println("Total records can not be calculated")
    }
    connection.setRequestProperty("Authorization", bearer_token);
    connection.setRequestProperty("Content-Type", "application/json;odata=verbose")
    connection.setRequestProperty("Accept", "application/json")
    connection.setDoOutput(true)
    OutputStream pos = connection.getOutputStream()
    pos.write(payload.getBytes())
    pos.flush();
    pos.close();
    println(connection.responseCode)
    def msg = null
    if(connection.responseCode == 200){
        msg = "Executing Deployment"
    }
    else{
        msg = "Error is Connection\n"
        msg += connection.responseCode
    }
    connection.disconnect()
    return msg
}

Reading the script/file content as input
File f = new File("out.py")
def content = f.readLines().toString()

Example Payload:
String payload = """{
                            "Definition": {
                            "name": "filename",
                            "modifiedBy": "user_name",
                            "active": true,
                            "systemId": "filename_sid",
                            "script": "${content}"

                            }
                        }"""

Basically , I want to upload some python script content (python code) to API end point url.
The above code is working good when I simply post any random text which is not code.
But it gives 400 Bad Request when it reads the file content as code.Example error below:
my script file contains:
import clr
import sys
import System

# Testing Changes Priyabrata
clr.AddReference("System.Core")
clr.ImportExtensions(System.Linq)
clr.AddReference('System.Xml')
from System import DateTime, Random
Offeringid = ""
tableInfo = SqlHelper.GetTable("COMPOSIOTION")

Below is error response:
{"error":{"code":"110000","message":"One or more fields in the API request contains invalid data. See the log for more information","target":"/api/script/v1/globalscripts/37","details":[{"code":"110000","message":"ScriptDefinition.Script: After parsing a value an unexpected character was encountered: S. Path 'ScriptDefinition.Script', line 13, position 18."}],"internalMessage":"Model validation failed"}}

However when i try to code in Python, script content also posted to endpoint using python requests module.
But this gives error i.e. 400 Bad Request in groovy.
I have a requirement to make the pipeline in groovy as per organization standard.
enter image description here
Any suggestion would be much appreciated. Thanks.

A: your POST code is fine.
problem not in content size , but in a way you are building json payload.
you have doublequotes in content
so, using string interpolation  for json building like this:
def content = 'println "world"'
def payload = """{ "script":"${content}" }"""

will give you incorrect json:
{ "content": "println "world"" }

better to use groovy.json.JsonBuilder or groovy.json.JsonOutput
def content = 'println "world"'
def payload = new groovy.json.JsonBuilder([
    'active': true,
    'script': content
]).toPrettyString()

this will result well-formatted json with all required escaped doublequotes and other special characters
{
    "active": true,
    "script": "println \"world\""
}


text:
Q: Registering to a new site after asking a question is broken on the iOS app version 1.1.0 After using the mobile app to ask a question on a new site (I didn't have an account there yet), the question was posted just fine, however when trying to add a comment on that question the app asks me to join the site (but I already did), and even if I try to join it a second time it fails (it'd be nice if it failed silently and just refreshed when it realized that I was already registered), see the following screenshots :

Also the app seems to behave as if I wasn't registered there since I can't even edit my own question, despite having my account correctly created there and linked to my other accounts.
iOS version 7.1.2, app version 1.1.0 on iPhone 5S.


text:
Q: Monitoring battery level on iPhone I'm using the basic battery monitoring code on iOS and I've read somewhere that it drains battery to do so.
UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];

I can't really find any good reference with actual data on this.
Is it really bad to check the changes in battery level? What other possibilities do I have?
I would like to do much less treatment when the battery is low so that I don't finish it off.

A: Use this:
 UIDevice *myDevice = [UIDevice currentDevice];
 [myDevice setBatteryMonitoringEnabled:YES];
 double batLeft = (float)[myDevice batteryLevel] * 100;

A: I can think that the continous battery level monitoring is expensive. You may want to not monitor the battery continously.
Set a timer to every 5 minutes. In the tick method, set monitoring to YES, get level, then set monitoring to NO again. Don't need to subscribe to any notifications this way.
You may increase the interval below 20% battery, or so.
-(void)tick:(NSTimer*) timer
{
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    self.batteryPercentace = [[UIDevice currentDevice] batteryLevel];
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:NO];
}

I'm not sure if it needs to be monitored at all, you may try out just simply read battery level.


text:
Q: iframe suddenly not appearing in google chrome half way through building a website an iframe on my page has disappeared when the webpage is viewed in chrome. The iframe is still visible in firefox, ie, safari and opera. All browsers are up to date. It was working fine up until a point, however I do not know what that point was!

New Arrivals

Yard Sale

Car Sales

House Rental

Hot Spots

  Events

    Chatter

This is the iframe which sources a marquee from a seperate html file, it sits just under the menu. Please help. I have only included a snippet of code. I only have the ability to test locally too :)
The error in the chrome console says Uncaught ReferenceError: LoadFile is not defined


text:
Q: How do I upload a file(picture) from android and save to the blobstore using GAE and google endpoints? Sorry if this is a little general. Hopfully I can get pointed in the correct direction.
I have an android app that includes instant messaging. I want to add the functionality to send photos in messages as well. My backend is built on GAE and cloud endpoints and is written in Java.
So far, I've looked into google cloud storage, the blobstore, java servlet pages, etc. But a clear solution (or example using endpoints) has been impossible to find.
So, as the question states, how can I send and serve images from the blobstore using android and GAE endpoint backend?
Edit: This question is only regarding the back end. In android, I can do the http post easily enough. I'm just lost when it comes to doing this in endpoints

A: I suggest the following approach to implement what you require:

*

*Pass the image data as base64 encoded text from your client.

*On the server side, you can extract out the image content and then use one of many options that are available, which include Blobstore, Google Cloud Storage, etc. I suggest that you go with Google Cloud Storage because that is the recommended approach. If you prefer the Datastore, keep in mind that the data is limited to 1 MB in size, so you might hit that limit depending on the size of images that you are dealing with.

*A SO question and answer here contains lot of relevant code that you could utilize: Sending images as a base64 string to a google cloud endpoint from cms

A: If you are already using endpoints you can follow @Romin 's suggestion and send the images as Base64 or upload your images in 2 steps using the blobstore/GCS service, first get the Upload URL (via endpoints) and then post your image to that URL.

A: Why not using a simple HTTP POST to handler for image upload?
When I use the blobstore I typically have a pair of handlers one for uploading and one for serving images.
So, in your case I'll rather do a post to a URL sending the image file and some parameter than can link it to the proper place in the datastore (i.e. user ID).
Then, using endpoints I'll have the same linking key and display the image using the serving handler with the given parameter.


text:
Q: My iPhone's Album Art is Wrong. How can I fix it? All the art in my iTunes app is wrong. I pay for iTunes Match, but it's disabled on my phone. (It has been enabled in the past.)
What can I do to fix the art?

A: The "awesome" thing is, that if you want to have the right Coverart in your iPhone you are obligated to buy your music in the iTunes store, else it messes the Coverart up (even though it is the correct one in iTunes). Bottomline: neither Amazon mp3 nor imported CD (no matter if original or not) will have the right cover in your iPhone.
Thanks apple for this great new feature !

A: i know this sounds silly but go into your settings into music and try unchecking "show all music"

A: I don't think this is a problem with iTunes showing the wrong artwork because you didn't buy the music from them.
It seems like they have artist artwork and album artwork. It makes sense if you have multiple albums by the same artist; which 'album art cover' should it use to represent the artist?
Now if you only have one album for an artist, it does seem a little messed up that they aren't using that cover, especially when you are scrolling through artists and expecting to see that cover.


text:
Q: Changing font size of a JavaScript number variable I want to change the font size of a number that is assigned to a variable and then printed out.
var secondsPerMinute = 60;
var minsPerHour = 60;

var hoursPerDay = 24;
var daysPerWeek = 7;
var weeksPerYear = 52;
var secondsPerDay =  secondsPerMinute*minsPerHour*hoursPerDay;
document.write(secondsPerDay);
var alpha = "blah";
document.write(alpha.fontsize(10));

Here I want to change the font size of the output secondsPerDay .. for some reason .fontsize() does not work on it.
 I am new to javascript so apologies if this seems like a foolish question.

A: According to the MDN page on String#fontsize:

Deprecated
  This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

Nor should you use document.write, for many reasons.
Write output into HTML elements defined on your page, styled using CSS. For example:

document.getElementById('secondsPerDay').textContent = secondsPerDay;

A: change the last line to
document.write(""+secondsPerDay+"");
document.write(""+alpha+"");

use font-size property of the css
after checking @torazaburo's answer, try to use innerHTML rather than document.write
document.body.innerHTML += ""+secondsPerDay+"";
document.body.innerHTML += ""+alpha+"";

A: EDIT:
The fontsize function is a deprecated method from the String object and you should avoid using it. See some of the other solutions people have posted as a safer alternative.
I recommend outputting HTML and setting the font-size using inline CSS:
document.write('' + secondsPerDay + '');
                             ^^^^^^^^^^^^^^^

Updated fiddle

You have to also apply fontsize() to the secondsPerDay:
document.write(secondsPerDay.toString().fontsize(10));

See your working code here.


text:
Q: Getting question marks and now exceeding tex capacity after trying to add reference I'm using TexMaker, and I'm fairly new this using latex.
Some time ago, I wrote a report in LaTeX. If I wanted to reference something I would type in \cite{blah} (assuming blah was referenced in the bibfile), then I would run quick build. Sometimes I would get a question mark where the reference should be, but I would randomly run the other options like Dvi->PS or BibTeX, then I would run Quick Builder again and it would work.
This time it doesn't seem to work. When running Quick Builder it gives  question marks as usual, then when I randomly run the other options, and then run quick builder again, I get an error now:
! TeX capacity exceeded, sorry [input stack size=5000].\hmode@bgroup ->\leavevmode\bgroup
on line 43
Can anyone help? I've included a zip file of my document at this
download link.
The file with this issue is called Report_Template

A: I looked at it again, and I do get problems after removing all the aux files and recompiling. It seems the harvard package does not handle URLs really well.
Compiles just fine if I add this after the harvard package.
\usepackage{url}
\renewcommand{\harvardurl}[1]{\textbf{URL:} \url{#1}}

The problem is that you have an URL with _ in it. The harvard does not protect the URLs.
But I never get a TeX capacity exceeded error


text:
Q: Using Chutzpah to test CommonJS modules used in duktape I'm working in a game engine (Atomic Game Engine) which uses the Duktape embeddable javascript engine. This allows loading of CommonJS modules, so I have modules like the following:
require("Scripts/LumaJS/Interface");

// Interface to be implemented by state objects
var IState = new Interface({
    optional: ["onEnter", "onExit", "onUpdate"],
    reserved: ["label"]
});

StateMachine = function(onStateChanged) {
    this.states = {};
    this.currentState = null;
    this.onStateChanged = onStateChanged;
    this.log = false;
}

StateMachine.prototype.addState = function (label, stateOrOnEnter, onExit, onUpdate) {
    // Support objects or individual functions
    var state;
    if (!stateOrOnEnter ||
        typeof (stateOrOnEnter) == "function") {
        state = {
            onEnter: stateOrOnEnter,
            onExit: onExit,
            onUpdate: onUpdate
        };
    } else {
        state = stateOrOnEnter;
    }

    // Validate and add
    IState.throwIfNotImplementedBy(state);
    state.label = label;
    this.states[label] = state;
}

StateMachine.prototype.getCurrentStateLabel = function() {
    return this.currentState ? this.currentState.label : null;
}

// Many more class functions..

exports.create = function (onStateChanged) {
    return new StateMachine(onStateChanged);
}

I've got Chutzpah set up to unit test in VS Community Edition (with qunit). Testing something that doesn't use the require function or export object is fine, testing the above module as follows:
/// <reference path="..\Resources\Scripts\LumaJS\stateMachine.js" />

test("starts with no state", function() {
    var stateMachine = new StateMachine();

    equals(stateMachine.getCurrentStateLabel(), null);
});

Chutzpa fails with a "Can't find variable" error.
I've got around this by adding the following in a fakeJSCommon.js which I then reference from test files:
require = function () { }
exports = {};

But I then need to manually reference the requires from the modules I'm testing as well, which doesn't seem ideal.
So my question is: Is there a way to get Chutzpah to treat requires like reference tags, or a better way to do this that would achieve what I'm looking for?

A: Chutzpah just runs your code in the browser so anything you reference needs to be valid javascript that it can load. If you are using methods that are "magic" and have no real definition than Chutzpah will fail on them. I think you best option is to have a shim (like you made) which prevents Chutzpah to not error on the statement. And then add a chutzpah.json file to declare your references.


text:
Q: How to write forgetpassword manually for laravel I wrote a login system myself and for authentication I us auth and User model.
Now I want to wrote Reset Password,
I found PasswordBroker so I wrote a method in my controller:
public function forgetPassword(Request $request, PasswordBroker $password) {
        if (empty($request->session()->get('email'))) {
            return redirect()->route('login');
        }

        $response = $password->sendResetLink([$request->session()->get('email')], function($message)
        {
            $message->subject('Password Reset');
        });

    }

But when I trying to reset my password I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `users` where `0` = email@domain.com limit 1)

What should I do?
UPDATE :
my users migration:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

A: I found the solution,
In sendResetLink we should pass email as key in first parameter,
so my code should change to this:
public function forgetPassword(Request $request, PasswordBroker $password) {
        if (empty($request->session()->get('email'))) {
            return redirect()->route('login');
        }

        $response = $password->sendResetLink(['email' => $request->session()->get('email')], function($message)
        {
            $message->subject('Password Reset');
        });

    }


text:
Q: Angular 4 ngFor looping through array of objects with HTML I'm using Angular 4 and I want to loop through an array of objects and display the information in Angular Material grids tiles. My html (app.component.html) looks a bit like this

 <mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts">
  <mat-grid-tile>

{{contacts[i].name}}

  </mat-grid-tile>
 </mat-grid-list>

And contacts is an array of objects inside app.component.ts. There are NINE objects within contacts but for simplicity I've only put two here.
export class AppComponent {
// array of contact objects
contacts = [
{
  name: "Robbie Peck",
  image: "src/assets/robbie.jpg",
},
{
  name: "Jenny Sweets",
  image: "src/assets/jenny.jpg",
},

...

]
}

So rather than have nine different 's appear, each with their own information (looping i through contacts), I only have one and the console shows an error where it doesn't recognize contacts[i]. What have I done wrong? How can I get the  to have 9 's, each with name and image i within the contacts object in the typescript (app.component.ts) file?

A: You don't have to pass the index, you can just use the variable i and access i.image and i.name
<mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts" >
 <mat-grid-tile>

{{i.name}}

  </mat-grid-tile>


text:
Q: Docker file builds correctly but fails to run $ docker image build -t python-blog .
Step 1/5 : FROM ubuntu:16.04
 ---> 005d2078bdfa

Step 2/5 : RUN apt-get update -y &&     apt-get install -y python-pip python-dev
 ---> Using cache
 ---> 7c1fdabcc215

Step 3/5 : ADD . .
 ---> Using cache
 ---> 5e2784fac3bd

Step 4/5 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 7d038ff8d993

Step 5/5 : CMD ["/usr/bin/python3","run.py"]
 ---> Using cache
 ---> 24f691d13886

Successfully built 24f691d13886
Successfully tagged python-blog:latest

$ docker run -p 5000:5000 python-blog:latest

docker: Error response from daemon: OCI runtime create failed:
  container_linux.go:349: starting container process caused "exec:
  \"/usr/bin/python3\": stat /usr/bin/python3: no such file or
  directory": unknown. ERROr[0005] error waiting for container: context
  canceled

Dockerfile
FROM ubuntu:16.04

RUN apt-get update -y && \
    apt-get install -y python-pip python-dev

ADD . .

RUN pip install -r requirements.txt

CMD ["/usr/bin/python3","run.py"]

A: Your Dockerfile, doesn't not specifically installs python3, ubuntu-16.04 by default selects python (2.7.12-1ubuntu0~16.04.11), that's why it fails to execute the CMD instruction which expects /usr/bin/python3  which does not exists.
you have to update your Dockerfile to specifically install python3 if you want to run your code with python3.


text:
Q: Front Side Bus and RAM speed We encouted an odd question during a Cisco IT Esstenials course which didn't make sense.

Which memory module has a front side bus speed of 200 MHz

Possible choices were

*

*DDR-333

*DDR-400

*DDR3-667

*PC100 SDRAM

The answer was DDR-400. The question we're asking is what is the relationship between FSB speed and RAM, and why wasn't DDR-333 a valid answer?

A: In older systems, the front-side bus (FSB) was synchronously tied to the northbridge and memory controller.  This meant that, without the use of clock dividers (introducing complicated and expensive PLL circuitry to keep control of the different clock rates), your memory bus would operate at the FSB speed.  In your case, DDR-400 was the answer, since DDR-400 memory modules have a clock rate of 200 MHz.
Now, as history progressed, systems that still used an FSB now had a clock divider between itself and the memory controller.  This allowed for the use of different memory speeds independent of the FSB speed (so if we set the FSB to 400 MHz, and had a clock ratio of 1:2, the memory would run at 400 * 1 / 2 = 200 MHz).
I assume that since this isn't a computer architectures course, and since there was only one answer, it was implicitly implied that the system did not have a clock divider.  If it did (and indeed, nearly all computers since the late 90's did), we could simply solve the ratio to make any of the above listed memory modules work with the computer.
To make DDR-333 work for example, we need a memory clock of 166 MHz, or a clock divider of 5:6.  For DDR3-667, we need a memory I/O clock (not memory speed, DDR3 is different) of 333 MHz, or 5:3.  Finally, PC100 would work with a divider of 1:2 for a memory clock of 100 MHz.

TL,DR: Without a memory clock divider, the FSB has to match the memory clock speed.  With a clock divider, so long as you can create an integer ratio X:Y to match the memory:FSB speeds, then you can use that memory module (and that ratio can be satisfied for all of the memory modules listed in your question).

A: If you're required to choose one answer, you have to make assumptions such that only one answer is correct. The only sensible assumptions that will do that is assuming that the FSB speed equals the RAM clock speed. In that case, DDR-400 is correct since DDR-400 RAM has a RAM clock speed of 200MHz.
If you were permitted more than one answer, then the question is broken.

A: Double data rate (DDR) is the advanced version of synchronous dynamic random access memory (SDRAM). SDRAM waits for clock signals before responding to control inputs. DDR uses both the falling and rising edges of the clock signal.
So 200mhz front side bus is doubled to operate at 400mhz with DDR memory.

A: FSB is needed for 3D direct hardware driving of games and PCI-E sockets 667 MHz is ok if you got OpenGL 2.0 or higher driver for 3D-direct thru  output to monitor HD will work but may buffer on-screen.


text:
Q: OrchardProject - How to create a choice field that list content items I'm trying to find some functionality that is somewhere between the Container Part and the Taxonomy Field.
What I'd like to do is say that Foo has a field which contains many of Bar.  There are two varieties of this, the one to many and many to many.  Let's just stick to the simpler one to many version.
At first pass I thought the Container might work, but it seems that a content type is limited to one container part (at least it is through the GUI admin).  That means that I can't have foo.products and foo.locations (that'd be two Containers in the same ContentType.)
What might work would be a container field, but I don't see that one of those is available.
The Taxonomy Module might work but that requires that I create Bar as a taxonomy.  Then go to content types and add parts to the Bar Term.  This just doesn't feel right and it requires that I recreate a bunch of content types as taxonomies.
I think I could achieve this if there were a taxonomy part that I could add to foo, but unfortunately I don't see one of those either.
Maybe I should just bite the bullet and create a custom module with my domain model, but I thought I'd ask here first.
thx,
Dan

A: I think you need to read this if you are going to roll your own: http://orchardproject.net/docs/Creating-1-n-and-n-n-relations.ashx
Alternatively, there is a module on the gallery that might work for you: http://orchardproject.net/gallery/List/Modules/Orchard.Module.Downplay.Mechanics

A: Have you looked at the tags module? It allows you to have multiple tags against a content item. You could write your own module that implements a more restrictive interface, wrapping some of the tags functionality in a custom content part that restricts tags to those within a certain set, provides an admin controller that lets you edit the subset of tags.
If that won't work for you then you might be better off writing your own module. It sounds like both Taxonomies and Lists both implement some functionality you want but not all, so you should be able to use both of those modules as a reference and/or solid foundation for your own.


text:
Q: How to add more information to the details page of a file in Windows explorer In my previous company, we were working with GIT, which uses hashing technology for identifying purposes. I remember that the commit hash of a file was present in the details of a file (open a file in Windows explorer, right-click, go to the "Details" tab).
However, now I'm working with SourceSafe, and when I look at the mentioned "Details" tab, I see the following entries (freely translated from Dutch):

*

*Name

*Type

*Path

*Size

*Creation date

*Modification date

*Properties (?)

*Owner

*Computer

So, except for maybe the "Properties (?)" entry, I don't see any place where that information can be written. Is this possible, is it possible using SourceSafe and how?


text:
Q: Android Service not running in background I am developing a birthday reminder app. I am using service for getting notification of one's b'day at 12:00 am & the service is called from the OnCreateView() method of a fragment . But when my app is closed, service is not running in the background.
How can i make the service running always ?
Service class

package works.viswajith.birthdayreminder;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import java.util.Calendar;

/**
* Created by Viswajith on 6/17/2015.
*/
public class NotificationService extends Service {

DBHelper db;
private Cursor cur;
private Calendar cal;
private int d,m,y;
private String[] temp;
private NotificationManager nm;
int i=0;

@Override
public void onCreate() {
    super.onCreate();

    db=new DBHelper(getApplicationContext());
    cur=db.getDetails();
    cal= Calendar.getInstance();
    d=cal.get(Calendar.DAY_OF_MONTH);
    m=cal.get(Calendar.MONTH)+1;
    y=cal.get(Calendar.YEAR);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(getApplicationContext(),"Service",Toast.LENGTH_SHORT).show();

    i=0;
    cur.moveToFirst();

    for(i=0;i<db.getCount();i++)
    {
       temp=cur.getString(2).split("/");
        if(Integer.parseInt(temp[0])==d && Integer.parseInt(temp[1])==m)
        {

            NotificationCompat.Builder mbuilder=new NotificationCompat.Builder(this);
            mbuilder.setSmallIcon(R.drawable.happy);
            mbuilder.setContentTitle("Happy B'day "+cur.getString(0));
            mbuilder.setContentText("Today is "+cur.getString(0)+"'s B'day , Wish him ..");
            nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            nm.notify(100,mbuilder.build());

        }

        cur.moveToNext();

    }

    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

Fragment class
package works.viswajith.birthdayreminder;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Calendar;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import android.database.Cursor;
import android.database.DatabaseUtils;

/**
* Created by Viswajith on 6/8/2015.
*/
public class BirthdayFragment extends Fragment {

private View v;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

Cursor c;
DBHelper db;
Intent i;
int count=0;

private static String LOG_TAG = "CardViewActivity";

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    i=new Intent(getActivity(),NotificationService.class);
    getActivity().startService(i);

    setHasOptionsMenu(true);
    v=inflater.inflate(R.layout.birthday_fragment,container,false);

    db=new DBHelper(getActivity());

    mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new MyRecyclerViewAdapter(getDataSet());
    mRecyclerView.setAdapter(mAdapter);

    return v;

}

@Override
public void onResume() {

    i=new Intent(getActivity(),NotificationService.class);
    getActivity().startService(i);

    super.onResume();
}

private ArrayList<DataObject> getDataSet() {

    ArrayList results = new ArrayList<DataObject>();

    count=0;

    c=db.getDetails();

    Calendar cal=Calendar.getInstance();
    int day=cal.get(Calendar.DAY_OF_MONTH);
    int month=cal.get(Calendar.MONTH)+1;

    if(c.getCount()!=0)
    {
    for (int index = 0; index < c.getCount(); index++) {

        String str[]=c.getString(2).split("/");

        if((month==Integer.parseInt(str[1])&&    (Integer.parseInt(str[0]))>day)) {
            DataObject obj = new DataObject(c.getString(0).toString() + "'s  B'day",
                    c.getString(1).toString(), c.getString(2).toString());
            results.add(count,obj);
            count++;
        }
        c.moveToNext();
    }
  }
    return results;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu,inflater);

    MenuItem refresh=menu.add(1,100,1,"Refresh");
    refresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    refresh.setIcon(R.drawable.ic_autorenew_black_18dp);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()) {

        case 100: mAdapter = new MyRecyclerViewAdapter(getDataSet());
                  mRecyclerView.setAdapter(mAdapter);
            break;
    }

   return super.onOptionsItemSelected(item);
}

}

A: You should use AlarmManager Class instead. It's there specifically for that purpose.
Here's a link to a tutorial.
http://www.learn-android-easily.com/2013/05/android-alarm-manager_31.html

A: Make your service foreground. Then it won't get killed by android.


text:
Q: Java TCP socket server with PHP client? Hey there,
I am developing an TCP socket server in Java. The client(s) must connect to a webpage (in PHP)
Well, here come's my trouble.. They can connect to the specified host, but the server can't read the packets that the client send.
If I create the client in Java, it works 100%. Well, here are some snippets of my code. I hope someone have a answer for me. Because I'm stuck.
This is my little PHP script that sends:
<?php

set_time_limit(0);

$PORT = 1337; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
     or die("error: could not create socket\n");

$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
    or die("error: could not connect to host\n");

 $text = "wouter123"; //the text we want to send to the server

 socket_sendto($sock, $text, strlen($message), MSG_EOF, '127.0.0.1', '1337');
//socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
 //      or die("error: failed to write to socket\n");

 $reply = socket_read($sock, 10000, PHP_NORMAL_READ) //Reading the reply from socket
   or die("error: failed to read from socket\n");

echo $reply;
?>

The socket side is:
package com.sandbox.communication;

public class PacketHandler {

public String processInput(String theInput) {
    String theOutput = null;

    if (theInput == "wouter123") {
        theOutput = theInput;
    }else {
        theOutput = "Cannot find packet. The output packet is " + theInput;
    }

    return theOutput;
}

}
And this little code connects to the PacketHandler:
    PacketHandler ph = new PacketHandler();
        while ((inputLine = in.readLine()) != null)
        {

            outputLine = ph.processInput(inputLine);

            out.println(outputLine);
        }

A: As you are using readLine on your input stream so make sure your clients are sending the data with linefeed.
From the javadocs

readLine() Reads a line of text. A line is considered to be terminated
  by any one of a line feed ('\n'), a carriage return ('\r'), or a
  carriage return followed immediately by a linefeed.


text:
Q: Problems with input boxs and Complex types I am trying to make a web page that allows the user to submit information about an object using input boxes and a save button. So far I have found it relatively easy to get the page to work for names, numbers etc. using basic types like strings, integers, booleans and doubles. I can enter this basic information into the input boxes and get the information to save into the database by hitting the save button.
However, the last input field that I need to get working is the Location field. This field is saved as a complex type called LatLng containing Latitude and Longitude values. I have been able to get the input boxes to display properly using the razor HTML form element EditorFor(). It automatically creates two input boxes one for Lat and one for Long.
EX:

But it seems that no matter what I input into these boxes the value stored in the database is always lat:0, long:0.
By setting a break point in my model file I have found out that the by the time it gets to the model the 'value' variable inside the 'set' in Location is already {0,0}.
So my Question is:
Is there something wrong with my code that would cause the value passed from the EditorFor() text boxes to be zeroed before reaching my model file? Or is there some way that will allow me to debug this deeper?
This code is from my view page. I removed everything I thought was irrelevant and all of the other fields besides Name and Location, to show one thing that is working for me and the one that is not:

            @using (Html.BeginForm("Create", "GenericModel", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {

                    @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })

                        @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })

                    @Html.LabelFor(m => m.Location, new { @class = "col-md-2 control-label" })

                        @Html.EditorFor(m => m.Location, new { @class = "form-control" })

                        <input type="submit" value="Create" class="btn btn-default" />

             }

I also removed everything from the model page besides Name and Location:
public class GenericModel
{
    public GenericModel()
    {
        Location = new LatLng(0, 0);
    }
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }

    private LatLng _Location;

    [Display(Name = "Location")]
    public LatLng Location
    {
        get
        {
            return _Location;
        }
        set
        {
            _Location = value ?? new LatLng(0, 0); //WHEN DEBUGGING THIS IS WHERE value = {0,0}
        }
    }
}

This is the code that defines the Complex Type LatLng:
[ComplexType]
public class LatLng : IEquatable<LatLng>
{
    public LatLng(){ }
    public double Latitude { get; private set; }
    public double Longitude { get; private set; }

    public LatLng(double latitude, double longitude)
    {
        Latitude = Math.Min(Math.Max(-90.0, latitude), 90.0);
        Longitude = Math.Min(Math.Max(-180.0, longitude), 180.0);
    }
    public override string ToString()
    {
        return string.Format("{0},{1}", Latitude, Longitude);
    }
    public override bool Equals(object obj)
    {
        return obj is LatLng && this.Equals((LatLng)obj);
    }
    public bool Equals(LatLng other)
    {
        return this.Latitude == other.Latitude
            && this.Longitude == other.Longitude;
    }
}

I am new to programming in these languages so please be patient with me. Also, please let me know if you required more code.

A: The problem is the two properties in your LatLng class:
public double Latitude { get; private set; }
public double Longitude { get; private set; }

They have a private setter on them.
I see what you're trying to do, you're trying to set them via a constructor call, but that's not how the model binder works.
The model binder will do the following when you post that form:

*

*Create a new instance of your model

*Latitude and Longitude properties will be set from the values found in the respective form fields.

If you want to keep your model how it is you'll need to read up on how to create a custom model binder and register it. It's pretty straight forward and you'll have full control.
Additionally, in your model the Location property doesn't need any implementation for the getter or setter:
[Display(Name = "Location")]
public LatLng Location { get; set; }

You're setting the default in your constructor and if Location is null then it just ignores it, it won't set it to null.


text:
Q: Relative referencing of columns when calculating another column I am calculating difference of two columns in dataframe like this
cases['7dayIncrement'] = (cases['10/15/20'] - cases['10/8/20'])
However, I need to change this to relative values, being last column - 7th column from last. The dataset gets new column added every day.
I was trying something like cases['7dayIncrement'] = (cases.iloc[:,-8,-7] - cases.iloc[:,-1:]) but that doesn't seem to work, throwing IndexingError: Too many indexers.
Any suggestions how is this done, please?

A: If I understand you correctly, You are looking for something like this:
cases['7dayIncrement'] = (cases.iloc[:,-1] - cases.iloc[:,-7])

last col would be : cases.iloc[:,-1]
and 7th col from last would be: cases.iloc[:,-7]


text:
Q: Congruence $320 \equiv 1 (\text{mod }x)$ I have the following congruence $320 \equiv 1 (\text{mod }x)$
And the question is : find all the modulos $x$ that make this congruence true.

A: Well basically the definition of $$a \equiv b (\text{mod }n)$$ is that n should divide $(a-b)$ So according to your question $x$ should divide $320-1$ that is $319$. It would be $11$ and $29$
Since you want all the $x$'s then it would be $11$, $29$ and $319$

A: $320 \equiv 1 (\text{mod }x)  \rightarrow 320-1 \equiv 0 (\text{mod }x) \rightarrow 319 \equiv 0 (\text{mod }x) \rightarrow x=11$ or $29$, since that only works for the divisors.

A: $320 \equiv 1 \pmod{x} \implies x \mid 320 -1 =319$ and hence there exists an integer $k$ such that $$xk = 319$$
Now should find all pairs $x,k$ that when you multiply them together you get $319$
$1 \times 319$
$29 \times 11$
$-1 \times -319$
$-29 \times -11$
any one of these 8 numbers can work for $x$
Basically you get the prime factorization for $319$ and then you add to your list the negatives of these numbers plus the number itself plus 1, that will give you a complete list for the divisors of $319$ or generally any number.


text:
Q: React: Accessing a target element as 'this' This has probably been answered before, but I can't seem to google it as it overlaps a bit with .bind(this) questions.
What I want to do is to refer the calling element as this when I run a function e.g.
highlight()
{
  this.select();
}

<input value={final_line} onClick={this.highlight} ></input>

However, this is undefined after clicking it. So what would the best way to do this? Right now I'm using event.target as a replacement, which works. I've also seen ref being used, but am not sure if this is applicable as I am returning an array of input.
So my question overall is: Is there an alternative to using event.target?

A:
So what would the best way to do this?

There is no way to do this. Using event.target is actually the right way to achieve it.
If you have several inputs, you should use the name property to identify the targeted element:
inputs.map(input =>
  <input name={input.name} onClick={this.highlight} />
)

highlight(event) {
  this.setState({ [event.target.name]: 'clicked!' })
}

A: I agree with GG. - you should use event.target, but an alternative is to use refs:
import { Component } from 'react';
import React from 'react';

class MyComponent extends Component {
  render() {
    const { final_line } = this.props;

    return <input value={final_line}
      onClick={ this.highlight.bind(this)}
      ref="inputToHighlight"
    />;
  }

  highlight() {
    this.refs.inputToHighlight.select();
  }
}

A: Use call() inside an arrow function as your onClick to set this to event.target like:
onClick={ (event)=>{onClick.call(event.target, contact.id) }


text:
Q: How to select rows in swt table I am trying to create a UI using SWT in eclipse. I have a table with multiple rows and two buttons Start and Next.When I click on Start, the first row is supposed to get selected. When I click Next, the next row has to be selected. And when a row is selected I have to read the corresponding row data.
I tried using
tableViewer.getTable().setFocus();
tableViewer.setSelection(new StructuredSelection(tableViewer.getElementAt(0)),true);

But no row is getting selected.
I also tried with table.getSelection(0);
And now each row is selected but with grey colour.As a result the row selection is not invoking table.addListener().
Please help me with this. I am new to this topic.
Thanks in advance.

A: You might have missed
 tableViewer.refresh ();

before doing setSelection


text:
Q: Wasted Space in VS Code Markdown Preview Pane is ... A Pain I'm writing a README.md file in VS Code, and I'm seeing over half the preview pane being left blank.  I don't recall this happening when I used VS Code for the same purpose last summer -- I was getting nice full preview panes.
Bug? Misconfiguration on my part?
Screen shot: https://photos.google.com/share/AF1QipPr8U4FsOsEOYJcHgQiMs3XNpPheAdwKAKUkDmCUdIpiEy5WnKIFq4Y-9LVpyXVlg?key=X0RSa1RoeUNMZDQwM0RSTzFscmNjdzBEbnhwSlhn

A: You are running into this known issue regarding zoom level and webviews: https://github.com/Microsoft/vscode/issues/5745
I just submitted a PR with the fix: https://github.com/Microsoft/vscode/pull/24465 Hopefully this fix will be in insiders builds soon and will make it into the next VSCode 1.12 release


text:
Q: SSRS Changes User Email in Subscription We have a user with a subscription to an SSRS report.  His email is (with last name & domain changed to protect his identity):
dexter.name@company.com
Periodically he won't receive his reports and if we investigate find that his email has been changed to "dexter.".
What could cause this?


text:
Q: GROUP BY in a temp table I'm working on a stored procedure and altering a temp table to spit out data depending on a specific condition. This stored procedure is quite complex and has like 40 columns, however for this specific issue I simply need to group the records by the DESCR column. The other 37 columns all have the same value so it shouldn't be an issue but in this case how can I group them by their DESCR and consolidate the LATEFEE and CHG values?
The query essentially looks like this:
SELECT [columns1], [column38], t.descr t.chg, t.lateFee, (t.chg + t.lateFee) as Total
FROM #tmpStatement t
    INNER JOIN dbo.Association a ON t.AssocID = a.AssocID
    INNER JOIN dbo.Company c ON a.CompanyID = c.CompanyID
GROUP BY
  [all columns]

If I remove the t.chg or the t.lateFee columns from the GROUP BY clause then SQL tells me that they are invalid in the SELECT list since they're not included in the GROUP BY, however I still want those values in my table.
Currently this is the outcome of the table:
DESCR      CHG   LATEFEE    TOTAL
=================================
Assessment  1       0         1
Spec        0       2         2
Spec        3       0         3
Assessment  0       5         5
Res         3       0         3

What I want the expected result to look like:
DESCR      CHG   LATEFEE    TOTAL
=================================
Assessment  1       5         6
Spec        3       2         5
Res         3       0         3

A: Looking at the sample data, you probably need something as simple as:
select descr, other, sum(chg) as chg, sum(latefee) as latefee, sum(chg) + sum(latefee) as total
from t
group by descr, other


text:
Q: How can I deal with undesired template instantiation for a function that isn't called? I'm trying to implementing some code where I want to call certain templated methods based on type traits. Unfortunately, the methods are instantiated with types (that are never called with said types) that are incompatible with the function, which causes compilation errors. Ideally I could use the traits to prevent said uncalled methods from being instantiated but that's not the case, so I'm looking for a workaround or design pattern I can use.
I have a few simple POD structs. Each type has different members (their existence is indicated by corresponding traits)
struct ThingA
{
    int a;
};

struct ThingAB
{
    int a;
    int b;
};

struct ThingABC
{
    int a;
    int b;
    int c;
};

template <typename Thing>
struct ThingTraits
{
    static const bool has_a=false;
    static const bool has_b=false;
    static const bool has_c=false;
};

Here's the template function; ThingA, ThingAB and ThingABC can be passed to it as either the Src or the Dst type
template<typename Src, typename Dst>
void assign(Src const &src, Dst &dst)
{
    constexpr bool c_a = ThingTraits<Src>::has_a && ThingTraits<Dst>::has_a;
    constexpr bool c_b = ThingTraits<Src>::has_b && ThingTraits<Dst>::has_b;
    constexpr bool c_c = ThingTraits<Src>::has_c && ThingTraits<Dst>::has_c;

    c_a ? copy_a(src,dst) : do_nothing();
    c_b ? copy_b(src,dst) : do_nothing();
    c_c ? copy_c(src,dst) : do_nothing();
}

The copy_a/b/c methods just copy the corresponding member:
template<typename Src, typename Dst>
void copy_a(Src const &src, Dst &dst)
{
    dst.a = src.a;
}

template<typename Src, typename Dst>
void copy_b(Src const &src, Dst &dst)
{
    dst.b = src.b;
}

template<typename Src, typename Dst>
void copy_c(Src const &src, Dst &dst)
{
    dst.c = src.c;
}

When trying to compile this, I get errors because copy_a/b/c are instantiated for types where the required members don't exist (ie copy_b).
How can I implement something functionally equivalent since this way doesn't really work? I need ThingA,AB,ABC to stay as simple PODs with no additional members (size req is strict) and I don't want to determine which copy operations to call during run time.

A: You may have something like:
template<bool hasA>
struct copy_a_caller
{
    template <typename Src, typename Dst>
    void operator () (const Src& src, Dst& dst) const
    {
        dst.a = src.a;
    }
};

template<>
struct copy_a_caller<false>
{
    template <typename Src, typename Dst>
    void operator () (const Src&, Dst&) const {}
};

template<typename Src, typename Dst>
void copy_a(Src const &src, Dst &dst)
{
    copy_a_caller<ThingTraits<Src>::has_a && ThingTraits<Dst>::has_a>()(src, dst);
}

// similar thing for b and c

And then
template<typename Src, typename Dst>
void assign(Src const &src, Dst &dst)
{
    copy_a(src, dst);
    copy_b(src, dst);
    copy_c(src, dst);
}

A: You can simply use the delegate-to-class trick & (partial) specialisation:
template<typename Src, typename Dst>
void assign(Src const &src, Dst &dst)
{
    constexpr bool c_a = ThingTraits<Src>::has_a && ThingTraits<Dst>::has_a;
    constexpr bool c_b = ThingTraits<Src>::has_b && ThingTraits<Dst>::has_b;
    constexpr bool c_c = ThingTraits<Src>::has_c && ThingTraits<Dst>::has_c;

    copy_a<c_a>::call(src, dst);
    copy_b<c_b>::call(src, dst);
    copy_c<c_c>::call(src, dst);
}

template <bool HasA>
struct copy_a;

template <>
struct copy_a<true>
{
  template <class Src, class Dst>
  static void call(Src const &src, Dst &dst)
  { src.a = dst.a; }
};

template <>
struct copy_a<false>
{
  template <class Src, class Dst>
  static void call(Src const &, Dst &)
  {}
};

copy_b and copy_c are left as an excercise for the reader :-)

A: Although a bit longer than the other answers, here's an example of using SFINAE, specifically the "has some member" trick, to accomplish what you are trying to do:
// Using this as a "type expression container" to force
// the deduction of a type. If said deduction fails,
// the compiler will defer emitting an error message
// until it fails to bind any of the functions below.
//
template<typename nope_t>
struct voidme{using type = void;};

// Using a late return type here allows us to
// reference argument symbols.
//
// Note that the expression within the decltype()
// does not require knowledge of any concrete type.
//
template<typename source_t, typename target_t>
auto copy_a(const source_t &src, target_t &dst)
-> typename voidme<decltype(dst.a = src.a)>::type
{
    dst.a = src.a;
}

// A "catch-all" copy_a. If type deduction fails in
// the above version, the compiler will attempt to
// bind this version, which will succeed.
//
// This takes advantage of the "Not An Error" part of SFINAE.
//
void copy_a(...)
{
}

template<typename source_t, typename target_t>
auto copy_b(const source_t &src, target_t &dst)
-> typename voidme<decltype(dst.b = src.b)>::type
{
    dst.b = src.b;
}

void copy_b(...)
{
}

template<typename source_t, typename target_t>
auto copy_c(const source_t &src, target_t &dst)
-> typename voidme<decltype(dst.c = src.c)>::type
{
    dst.c = src.c;
}

void copy_c(...)
{
}

template<typename source_t, typename target_t>
void assign(const source_t &src, target_t &dst)
{
    copy_a(src, dst);
    copy_b(src, dst);
    copy_c(src, dst);
}

Elsewhere...
struct ThingWithA
{
    int a;
};

struct ThingWithB
{
    int b;
};

struct ThingWithAandB
{
    int a;
    int b;
};

void DoTheThings()
{
    ThingWithA srcA, dstA;

    ThingWithB srcB, dstB;

    ThingWithAandB srcAB, dstAB;

    // assign() wherein "copy_b" and "copy_c" do nothing.
    assign(srcA, dstA);

    // assign() wherein "copy_a" and "copy_c" do nothing.
    assign(srcB, dstB);

    // assign() wherein only "copy_c" does nothing.
    assign(srcAB, dstAB);
}

Note that this approach works for any type, and does not require using traits.
Unless there are other constraints to enforce on the types involved, it is my opinion that parametrized traits you've described are maintenance hazards (they would need to be specialized for every type that needs to be used with assign, exposing their definitions to this detail).


text:
Q: Regex help for filtering extension number (phone) out of data I need to find a regex pattern that will match on only the extension number from a string that may contain other phone/fax numbers and names that end in E or X. Need help breaking down a regex pattern or tips to do this more effectively.
I tried playing with a regex pattern and was able to match on extension numbers only when other phone/fax numbers are present.
(?i)\s*([Ext]*?[- .]*\d{1,4})([X]*?[- .]*\d{1,4})([Ex]*?[- .]*\d{1,4})

From the pattern I have right now i can match on numbers like Ext. 115, X 256, Ex 2114 only when no other numbers are present. However when a phone number is present I'll match that first.
Also when a fax is indicated from the string "Jane Doe 888-888-8888/Fx 888-8888 ill match on x 888-8888.
Input strings:
 1. "Jane  EXT. 115"
 2. "Jane X289 FAX 888-888-8888"
 3. "John Doe-X 241 OR CELL888/8888888"
 4. "Jane Doe 888-888-8888"
 5. "John Doe FX 888-888-8888"

Output is:
 1. "EXT. 115"
 2. "X289"
 3. "X 241"
 4. "e 888-888-8888"
 5. "X 888-888-8888"

(When there is no extension present)

A: This seems to work for your samples
(?i)\s*((?:Ext|Ex|X(?<!FAX))[- .]*\d{1,4}(?![-\d]))
https://regex101.com/r/UqJKeE/1
Expanded
 (?i)
 \s*
 (                             # (1 start)
      (?:
           Ext
        |  Ex
        |  X
           (?<! FAX )
      )
      [- .]* \d{1,4}
      (?! [-\d] )
 )                             # (1 end)


text:
Q: Javascript Timer with input I am trying to create a interactive timer that can be able to receive input.
How do I add an input to this code below so I am able to get a time(like in minutes) from a user so that I can time the timer?
HTML
<!DOCTYPE html>

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="styles.css" rel="stylesheet">
    <title>Timer</title>

Home

Timer

            <form onsubmit="timer(); return false;">
                <input type="submit" value='Start' class='button button1'>
            </form>

            <form onsubmit="stopper();">
                <input type="submit" value='Stop' class='button button2'>
            </form>

Javascript
function stopper() {
    let stop = true;
}

let stop = false;
function timer() {

    // Set the date we're counting down to
    var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

        // Get today's date and time
        var now = new Date().getTime();

        // Find the distance between now and the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Display the result in the element with id="demo"
        document.getElementById("demo").innerHTML = days + " : " + hours + " : " + minutes + " : " + seconds;

        // If the count down is finished, write some text
        if (distance < 0) {
            document.getElementById("demo").innerHTML = 'Times up!';
            alert('Times up!');
        }
    }, 1000);
    if (stop === true) {
        return;
    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

A: Try the following snippet by replacing console.log with actual logic.
setTimeout(() => {
    console.log('logic timedout')
}, parseInt(prompt()) * 1000)


text:
Q: Testing a Spring Boot command line application I'd like to test my Spring Boot command line application. I would like to mock certain beans (which I was able to do by annotating @ContextConfiguration(classes = TestConfig.class) at the top of my test class. In TestConfig.class, I override the beans that I would like to mock. I'd like Spring Boot to find the rest of the components. This seems to work.
The problem is that when I run the test, the entire application starts up as normal (ie. the run() method is called).
@Component
public class MyRunner implements CommandLineRunner {

    //fields

    @Autowired
    public MyRunner(Bean1 bean1, Bean2 bean2) {
        // constructor code
    }

    @Override
    public void run(String... args) throws Exception {
        // run method implementation
    }

I've tried to override the MyRunner @Bean and put it in TestConfig.class, but that doesn't seem to work. I understand that I'm loading the regular application context, but that's what I'd like to do (I think?) since I would like to re-use all (or most) of the @Component I created in my Application, and only mock a tiny subset.
Any suggestions?
EDIT:
Application.java
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

A: The answer was simpler than I thought. Add the MockBean in
@TestConfiguration
public class TestConfig {

    @MockBean
    private MyRunner myRunner;

}

We can use the @MockBean to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context.
So MyRunner.run() is never called but I can still use all the other beans in my application.

A: CommandLineRunners are ordinary beans with one exception:
After the application context is loaded, spring boot finds among all its beans the beans that implement this interface and calls their run method automatically.
Now, I would like you to ask to do the following:

*

*Remove ContextConfiguration from the test and place a breakpoint in constructor of MyRunner. The test should look like this:

@RunWith(SpringRunner.class) // if you're on junit 4, adjust for junit 5 if you need
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class MyTest {
   @Autowired
   private MyRunner myRunner;
   @Test
   public void testMe() {
     System.out.println("hello");
   }
}

*Run the test and make sure that myRunner is loaded and its run method is called

*Now mock this class with MockBean annotation:

@RunWith(SpringRunner.class) // if you're on junit 4, adjust for junit 5 if you need
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class MyTest {

   @MockBean
   private MyRunner myRunner;
   @Test
   public void testMe() {
     System.out.println("hello");
   }
}

*Run the test. Make sure that run method is not running. Your Application Context now should contain a mock implementation of your component.

*If the above works, then the problem is with TestConfig and ContextConfiguration annotation. In general when you run without ContextConfiguration you give spring boot test engine a freedom to mimic the application context started as if its a real application (with autoconfigurations, property resolution, recursive bean scanning and so forth).
However if you put ContextConfiguration, spring boot test doesn't work like this - instead it only loads the beans that you've specified in that configuration. No Autoconfigurations, no recursive bean scanning happens for example.
Update
Based on OP's comment:
It looks like the MyRunner gets loaded when you put @ContextConfiguration because of component scanning. Since you have an annotation @Component placed on MyRunner class it can be discovered by Spring boot engine.
In fact there is a "dangerous" mix of two types of beans definitions here:
1. The beans defined with @Bean in @Configuration annotation
2. The beans found during component scanning.
Here is the question for you: If you don't want to mimic the application startup process and instead prefer to load only specific beans, why do you use @SpringBootTest at all? Maybe you can achieve the goal with:
@RunWith(SpringRunner.class)
@ContextConfiguration(YourConfig.class)
public class MyTest {
  ...
}

A: One way you could do this is to have 2 classes with the main method, one which sets up the "normal" context, and another that sets up the "mock" context:
Normal App Context, uses the usual Application
@SpringBootApplication(scanBasePackages = "com.example.demo.api")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public Foo foo() {
        return new Foo("I am not mocked");
    }

    @Bean
    public Bar bar() {
        return new Bar("this is never mocked");
    }
}

Add another Application class that overrides the normal context with the mocked one
@SpringBootApplication(scanBasePackageClasses = {MockApplication.class, Application.class})
@Component
public class MockApplication {

    public static void main(String[] args) {

        SpringApplication.run(MockApplication.class, args);
    }

    @Bean
    public Foo foo() {
        return new Foo("I am mocked");
    }
}

When you run Application.main Foo will be "I am not mocked", when you run MockApplication.main() it will be "I am mocked"


text:
Q: provide method for check status code with pass callback function in bash script I faced with problem with organization code. I have api which returned jwt token with some expire lifetime and several api which protected by jwt token, I need call this api's during some time and jwt token can be expired, how to protect from this case ? Need develop some approach until http_code !=401 -> execute curls, else -> relogin. How to organization bash script for correct works ? Maybe need move some logic(aobut check status code 401) to method, how to pass callback function with some curl(for some api) to method ?
This what I did, looking at this, you can analyze it and made conclusion how it should works:
http_code='401'
successful_status_code='200'
auth='false'

while [ "$auth" != "true" ]
do
    # in that [if] cheking status code if it 401, int case hwen token expired, need to fetch new token, by again execute api/v2/login
    if [ "$http_code" != "$successful_status_code" ]

    then
    # this curl execute api with username and password from file, then
    #response with `token` saving in `result.json`, from this file
    #anotther #api will be fetch token for get access to the protected api
      http_code=$(curl --request POST -sL \
       --url 'http://qbee.local/api/v2/login'\
       --output './result.json' \
       --header "Content-Type: application/json" \
       -d "@login.json" \
       --write-out "%{http_code}")

    else

      auth='true'
      # fetched token which was saved after api/v2/login curl
      tokenValue=$(jq -r '.token' './result.json')

      echo 'token was' + $tokenValue
      # For get access to  the potected api need to add header
      # 'Authorization: Bearer some_token', then apireturn some data,
      #but in case when toke expired need to execute `api/v2/login`
      # this api curl saved response in file, that's it
      http_code=$(curl --request GET -sL \
           --url 'http://qbee.local/api/v2/grouptree?_format=json'\
           --output './grouptree_result.json' \
           --header 'Authorization: Bearer '"$tokenValue")

      echo "$(cat grouptree_result.json)"
    fi

done

How I imagine it, some bash script should executed several api during by some time period, so need to provide some structure which should be catch case when toke will be expire and relogin again, saving new tokne in file.
#some scenario where several api's should be call

statuscode = executeApi(fetchGroupTree())
statuscode = executeApi(fetchSomeData())
...
//etc methods which call api

#method which provide approach catch 401 and relogin user, refresh
#toke and then again execute current api method
public function executeApi(function api())
{
   statuscode = execute api()
   if (statuscode == 401) {
       execute auth()
       statuscode = execute api()
   }
   return statuscode
}
# another some api which expect not expire token for provide access
public function fetchSomeData()
{
          tokenValue=$(jq -r '.token' './result.json')

          echo 'token was' + $tokenValue

          // execute some curl api
}

# some api which expect not expire token for provide access
public function fetchGroupTree()
{
          tokenValue=$(jq -r '.token' './result.json')

          echo 'token was' + $tokenValue

          curl --request GET -sL \
               --url 'http://qbee.local/api/v2/grouptree?_format=json'\
               --output './grouptree_result.json' \
               --header 'Authorization: Bearer '"$tokenValue" \

          echo "$(cat grouptree_result.json)"
}

# method for relogin and saving new token in file after old token was expired
public function auth()
{
        http_code=$(curl --request POST -sL \
         --url 'http://qbee.local/api/v2/login'\
         --output './result.json' \
         --header "Content-Type: application/json" \
         -d "@login.json" \
         --write-out "%{http_code}")
}

But this is my vision, I'm not expert on bash scripts how usually develop bash script for this goal, maybe some best practices ?

A: You typically write some wrappers:
# the tokenfile location
tokenf=$(mktemp)
trap 'rm "$tokenf"' EXIT

# just some abstractions
get_token() {
    cat "$tokenf"
}
has_token() {
    [[ -s "$tokenf" ]]
}
clear_token() {
    : > "$tokenf"
}

# the generic curl wrapper way we take
# remember to add -S so that you see errors
_curl() {
    curl -sSL "$@"
}

# execute authentication request and place the result in token file
do_auth() {
   local cmd
   cmd=(
       _curl --request POST
       --url 'http://qbee.local/api/v2/login'
       --output "$tokenf"
       --header "Content-Type: application/json"
       -d "@login.json"
       # TODO: implement checking error code
       # --write-out "%{http_code}"
   )
   "${cmd[@]}"
}

# small wrapper so that loop looks nice
# first argument - filename for output
# other arguments passed to curl
# outputs HTTP exit code
_execute_api_callback() {
   local outf cmd
   outf="$1"
   shift
   cmd=(
      _curl --request GET
      --header 'Authorization: Bearer '"$(get_token)"
      --output "$outf" --write-out "%{http_code}"
      "$@"
   )
   "${cmd[@]}"
}

# run curl request in a loop requesting for authentication
execute_api() {
   # execute in a subshell for EXIT trap to auto-cleanup
   (
      # The temporary location for curl output
      tmpf=$(mktemp)
      trap 'rm "$tmpf"' EXIT
      while
         # TODO: check other error codes
         statuscode=$(_execute_api_callback "$tmpf" "$@")
         ((statuscode != 200)
         # TODO: implement timeout
      do
         do_auth   # TODO: check failure
      done
      cat "$tmpf"
  )
}

if ! has_token; then
   do_auth
fi
# is --url really that needed?
execute_api 'http://qbee.local/api/v2/grouptree?_format=json'

This is just a code I have written in 5 mins on this forum - I did not test it, I did not run it. Check your code with https://shellcheck.net , read https://mywiki.wooledge.org/BashFAQ/005 and check out https://mywiki.wooledge.org/BashGuide/Parameters .


text:
Q: Deseo actualizar el campo "estado" de todos los registros de mi tabla convocatoria cuando el atributo "fecha_vencimiento" sea igual a la fecha actual mi código HTML de la vista

                    Id
                    Descripción
                    Categoria
                    PDF
                    Fecha Publicación
                    Fecha Vencimiento
                    Estado
                    Opciones

                @foreach ($convocatorias as $conv)

                    {{$conv->idconvocatoria}}
                    {{$conv->descripcion}}
                    {{$conv->categoria_convocatoria}}
                    archivo)}}"> PDF
                    {{$conv->fecha_publicacion}}
                    {{$conv->fecha_vencimiento}}

                    estado)}}">{{$conv->estado}}

                        idconvocatoria)}}"><button class="btn btn-primary">Editar</button>
                        idconvocatoria}}" data-toggle="modal"><button class="btn btn-danger">Eliminar</button>

                @include('convocatoria.locacion.modal')
                @endforeach

Mi Controller, estoy trabajando con laravel 5.2
public function store (ConvocatoriaFormRequest $request)
{
    $convocatoria=new Convocatoria;
    $convocatoria->idpersona=$request->get('idpersona');
    $convocatoria->descripcion=$request->get('descripcion');
    $convocatoria->categoria_convocatoria=$request->get('categoria_convocatoria');
    $convocatoria->estado= 'VIGENTE';
    $mytime = Carbon::now('America/Lima');
    $convocatoria->fecha_publicacion=$mytime->format('Y-m-d H');
    $datee = Carbon::parse($request->get('fecha_vencimiento'));
    $convocatoria->fecha_vencimiento=$datee->toDateTimeString();

    if (Input::hasFile('archivo')){
     $file=Input::file('archivo');
     $para_extencion=$file->getClientOriginalName();
     $extension = pathinfo($para_extencion, PATHINFO_EXTENSION);
     $nombre_archivo="pdf_".$request->get('categoria_convocatoria')."_".time().".".$extension;
     $file->move(public_path().'/archivos/pdf/',$nombre_archivo);
     $convocatoria->archivo=$nombre_archivo;
    }
    $convocatoria->save();
    return Redirect::to('convocatoria/locacion');

}

En la base de datos

Esta es mi vista

Intente usando triggers y procedimientos almacenados pero lo que me interesa es que se se actualicen en tiempo real o cada cierto tiempo los estados de todos los registros de VIGENTE a FINALIZADO cuando el atributo "fecha_vencimiento" sea igual o menor a la fecha actual

A: Es posible hacerlo en Laravel, con una tarea programada y ejecutando un comando personalizado que debes crear.
En el procedimiento handle() de tu comando, podrías terner algo como:
$convocatorias = Convocatoria::where('fecha_vencimiento','<',Carbon::now())->get;

foreach($convocatorias as $convocatoria){
   $convocatoria(['estado']=>'No vigente')->save();
}

Podrías incluir un Log dentro del proceso para ver qué convocatorias se han actualizado. Este comando se podría ejecutar 1 vez al día.
Y siempre tendrías tus convocatorias actualizadas.


text:
Q: Typescript error TS2420 : Class incorrectly implements interface Upon building my app , I get the following error, which seems strange to me as the property appName is stated :

ERROR in ../src/app/app.service.ts (30,14): Class 'AppService'
incorrectly implements interface 'InternalStateType'.   Property
'appName' is missing in type 'AppService'.)

app.service.ts
import {Injectable} from '@angular/core';

interface InternalStateType {
  [key: string]: any;
  appName: string;
  darkMode: boolean;
  defaultLang: string;
  topnavTitle: string;
  messagePanelOpen: boolean;
  sidenavOpen: boolean;
  sidenavMode: string;
  sidenavCollapse: boolean;
  pageFullscreen: boolean;
  pageFooter: boolean;
  initial: boolean
};

/**
 * App service
 */
@Injectable()
export class AppService implements InternalStateType {

  // Set your states default value.
  private state: InternalStateType = {
    appName: 'MyApp',
    darkMode: false,
    defaultLang: 'en',
    topnavTitle: 'MyApp',
    messagePanelOpen: false,
    sidenavOpen: false,
    sidenavMode: 'over',
    sidenavCollapse: true,
    pageFullscreen: false,
    pageFooter: false,
    initial: false
  };

  public cloneState(): InternalStateType {
    return JSON.parse(JSON.stringify(this.state));
  }

  public reloadState(state: InternalStateType) {
    this.state = state;
  }

  public getState(prop?: any): InternalStateType {
    const state = this.state;
    return state.hasOwnProperty(prop) ? state[prop] : state;
  }

  public setState(prop: string, value: any) {
    return this.state[prop] = value;
  }
}

Where am I wrong ? thanks for your feedback

A: The interface you defined does only has "direct properties", but your class that should implement InternalStateType all properties of InternalStateType are members of the state properties.
You have to remove the state property from your class. Everything should work then :)

A: You do not actually have the appName property on AppService type. Your state is typed as InternalStateType and has appName property. If you actually want AppService to implement InternalStateType, define it like below:
@Injectable()
export class AppService implements InternalStateType {

  private appName: string;
  // ... define other members of `InternalStateType` here

}

If you did not intend for AppService to implement InternalStateType, remove it from the class declaration:
export class AppService {
  // ...
}


text:
Q: replace underscores with dashes in codeigniter URL structure im having a website which is developed using codeigniter. My URL strcuture has around 4 segments and over 500 pages. Currently my URL has underscores (_) but i need to replace it which dashes (-)
current structure
mywebsite.com/app/standalone_apps/high_runner_beta/download

required URL structure
mywebsite.com/app/standalone-apps/high-runner-beta/download

i cant user the routing feature in CI coz there are too many links that needs to be redirected.
i did try the solutions in
Codeigniter Routes regex - using dashes in controller/method names
but it didn't work.
can someone suggest a method where i can replace the underscores with dashes on my URLs.

A: This work for me -> create a a php file: MY_Route.php
with this code and upload to 'application/core' directory:
<?php class MY_Router extends CI_Router {
function set_class($class)
{
    $this->class = str_replace('-', '_', $class);
}

function set_method($method)
{
    $this->method = str_replace('-', '_', $method);
}

function set_directory($dir) {
    $this->directory = $dir.'/';
}

function _validate_request($segments)
{
    if (count($segments) == 0)
    {
        return $segments;
    }

    // Does the requested controller exist in the root folder?
    if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).'.php'))
    {
        return $segments;
    }

    // Is the controller in a sub-folder?
    if (is_dir(APPPATH.'controllers/'.$segments[0]))
    {
        // Set the directory and remove it from the segment array
        $this->set_directory($segments[0]);
        $segments = array_slice($segments, 1);

        while(count($segments) > 0 && is_dir(APPPATH.'controllers/'.$this->directory.$segments[0]))
        {
            // Set the directory and remove it from the segment array
            $this->set_directory($this->directory . $segments[0]);
            $segments = array_slice($segments, 1);
        }

        if (count($segments) > 0)
        {
            // Does the requested controller exist in the sub-folder?
            if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).'.php'))
            {
                if ( ! empty($this->routes['404_override']))
                {
                    $x = explode('/', $this->routes['404_override']);

                    $this->set_directory('');
                    $this->set_class($x[0]);
                    $this->set_method(isset($x[1]) ? $x[1] : 'index');

                    return $x;
                }
                else
                {
                    show_404($this->fetch_directory().$segments[0]);
                }
            }
        }
        else
        {
            // Is the method being specified in the route?
            if (strpos($this->default_controller, '/') !== FALSE)
            {
                $x = explode('/', $this->default_controller);

                $this->set_class($x[0]);
                $this->set_method($x[1]);
            }
            else
            {
                $this->set_class($this->default_controller);
                $this->set_method('index');
            }

            // Does the default controller exist in the sub-folder?
            if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php'))
            {
                $this->directory = '';
                return array();
            }

        }

        return $segments;
    }

    // If we've gotten this far it means that the URI does not correlate to a valid
    // controller class.  We will now see if there is an override
    if ( ! empty($this->routes['404_override']))
    {
        $x = explode('/', $this->routes['404_override']);

        $this->set_class($x[0]);
        $this->set_method(isset($x[1]) ? $x[1] : 'index');

        return $x;
    }

    // Nothing else to do at this point but show a 404
    show_404($segments[0]);
} }


text:
Q: Wildfly deploy and launch command line (JavaEE and Kafka) I've been struggling with deploy on Wildfly and can't find an answer (maybe I'm looking to it wrongly).
So my goal is to deploy an app that works on two ways :

*

*REST API

*Kafka processes (Producers / Consumers / Streams)

I want to give my users the way to push me informations to feed some streams, whereas I'll have producers running alongside to fetch data from different datasources.
For now, I'm succesfully compiling my WAR file, API is accessible and i can run my command lines to launch my many processes but I wan't to make it automatic on deployment.
Anything I can look at? So far I haven't found anything about it.
Thank you for your kind help


text:
Q: Modular Vaadin Flow application. Frontend resources dynamic loading We have a big monolithic Flow/Spring/Gradle application, and we want to introduce some modularity, with a hot-load plugin system.
Plugin are vaadin/flow independent projects with :

*

*web resources in META-IN/resources/frontend : javascript, CSS, images..

*eventually import of third party NPM resources

On the server side, I had some success with my prototype using pf4j and pf4j-spring
On the client side, I don't know how to tackle the problem. In a monolithic way, all frontend resources are webpacked. How can I dynamically make web resources accessible to the client ?
I have read about the notion of NPM chunking

*

*https://github.com/vaadin/flow/issues/5623

*https://github.com/vaadin/flow/issues/5339
It should also be related to the Page.loadDynamic feature
I'm missing some keys. Anyone to point me in a good direction ??