text:
Q: How to ensure goroutines launched within goroutines are synchronized with each other? This is the first time I'm using the concurrency features of Go and I'm jumping right into the deep end.
I want to make concurrent calls to an API. The request is based off of the tags of the posts I want to receive back (there can be 1 <= N tags). The response body looks like this:
{
    "posts": [
        {
            "id": 1,
            "author": "Name",
            "authorId": 1,
            "likes": num_likes,
            "popularity": popularity_decimal,
            "reads": num_reads,
            "tags": [ "tag1", "tag2" ]
        },
        ...
    ]
}

My plan is to daisy-chain a bunch of channels together and spawn a number of goroutines that read and or write from those channels:
- for each tag, add it to a tagsChannel inside a goroutine
- use that tagsChannel inside another goroutine to make concurrent GET requests to the endpoint
- for each response of that request, pass the underlying slice of posts into another goroutine
- for each individual post inside the slice of posts, add the post to a postChannel
- inside another goroutine, iterate over postChannel and insert each post into a data structure

Here's what I have so far:
func (srv *server) Get() {
    // Using red-black tree prevents any duplicates, fast insertion
    // and retrieval times, and is sorted already on ID.
    rbt := tree.NewWithIntComparator()
    // concurrent approach
    tagChan := make(chan string)                       // tags -> tagChan
    postChan := make(chan models.Post)                 // tagChan -> GET -> post -> postChan
    errChan := make(chan error)                        // for synchronizing errors across goroutines
    wg := &sync.WaitGroup{}                            // for synchronizing goroutines
    wg.Add(4)
    // create a go func to synchronize our wait groups
    // once all goroutines are finished, we can close our errChan
    go func() {
        wg.Wait()
        close(errChan)
    }()
    go insertTags(tags, tagChan, wg)
    go fetch(postChan, tagChan, errChan, wg)
    go addPostToTree(rbt, postChan, wg)
    for err := range errChan {
        if err != nil {
            srv.HandleError(err, http.StatusInternalServerError).ServeHTTP(w, r)
        }
    }
}

// insertTags inserts user's passed-in tags to tagChan
// so that tagChan may pass those along in fetch.
func insertTags(tags []string, tagChan chan<- string, group *sync.WaitGroup) {
    defer group.Done()
    for _, tag := range tags {
        tagChan <- tag
    }
    close(tagChan)
}

// fetch completes a GET request to the endpoint
func fetch(posts chan<- models.Post, tags <-chan string, errs chan<- error, group *sync.WaitGroup) {
    defer group.Done()
    for tag := range tags {
        ep, err := formURL(tag)
        if err != nil {
            errs <- err
        }
        group.Add(1) // QUESTION should I use a separate wait group here?
        go func() {
            resp, err := http.Get(ep.String())
            if err != nil {
                errs <- err
            }
            container := models.PostContainer{}
            err = json.NewDecoder(resp.Body).Decode(&container)
            defer resp.Body.Close()
            group.Add(1) // QUESTION should I add a separate wait group here and pass it to insertPosts?
            go insertPosts(posts, container.Posts, group)
            defer group.Done()
        }()
        // group.Done() -- removed this call due to Burak, but now my program hands
    }
}

// insertPosts inserts each individual post into our posts channel so that they may be
// concurrently added to our RBT.
func insertPosts(posts chan<- models.Post, container []models.Post, group *sync.WaitGroup) {
    defer group.Done()
    for _, post := range container {
        posts <- post
    }
}

// addPostToTree iterates over the channel and
// inserts each individual post into our RBT,
// setting the post ID as the node's key.
func addPostToTree(tree *tree.RBT, collection <-chan models.Post, group *sync.WaitGroup) {
    defer group.Done()
    for post := range collection {
        // ignore return value & error here:
        // we don't care about the returned key and
        // error is only ever if a duplicate is attempted to be added -- we don't care
        tree.Insert(post.ID, post)
    }
}

I'm able to make one request to the endpoint, but as soon as try to submit a second request, my program fails with panic: sync: negative WaitGroup counter.
My question is why exactly is my WaitGroup counter going negative? I make sure to add to the waitgroup and mark when my goroutines are done.
If the waitgroup is negative on the second request, then that must mean that the first time I allocate a waitgroup and add 4 to it is being skipped... why? Does this have something to do with closing channels, maybe? And if so, where do I close a channel?
Also -- does anyone have tips for debugging goroutines?
Thanks for your help.

A: Firstly, the whole design is quite complicated. Mentioned my thoughts towards the end.
There are 2 problems in your code:

*

*posts channel is never closed, due to which addPostToTree might never be existing the loop, resulting in one waitGroup never decreasing (In your case the program hangs). There is a chance the program waits indefinitely with a deadlock (Thinking other goroutine will release it, but all goroutines are stuck).
Solution: You can close the postChan channel. But how? Its always recommended for the producer to always close the channel, but you've multiple producers. So the best option is, wait for all producers to finish and then close the channel. In order to wait for all producers to finish, you'll need to create another waitGroup and use that to track the child routines.

Code:
// fetch completes a GET request to the endpoint
func fetch(posts chan<- models.Post, tags <-chan string, errs chan<- error, group *sync.WaitGroup) {
    postsWG := &sync.WaitGroup{}
    for tag := range tags {
        ep, err := formURL(tag)
        if err != nil {
            errs <- err
        }
        postsWG.Add(1) // QUESTION should I use a separate wait group here?
        go func() {
            resp, err := http.Get(ep.String())
            if err != nil {
                errs <- err
            }
            container := models.PostContainer{}
            err = json.NewDecoder(resp.Body).Decode(&container)
            defer resp.Body.Close()
            go insertPosts(posts, container.Posts, postsWG)
        }()
    }

    defer func() {
        postsWG.Wait()
        close(posts)
        group.Done()
    }()
}

*Now, we've another issue, the main waitGroup should be initialized with 3 instead of 4. This is because the main routine is only spinning up 3 more routines wg.Add(3), so it has to keep track of only those. For child routines, we're using a different waitGroup, so that is not the headache of the parent anymore.

Code:
errChan := make(chan error)                        // for synchronizing errors across goroutines
    wg := &sync.WaitGroup{}                            // for synchronizing goroutines
    wg.Add(3)
    // create a go func to synchronize our wait groups
    // once all goroutines are finished, we can close our errChan

TLDR --
Complex Design - As the main wait group is started at one place, but each goroutine is modifying this waitGroup as it feels necessary. So there is no single owner for this, which makes debugging and maintaining super complex (+ can't ensure it'll be bug free).
I would recommend breaking this down and have separate trackers for each child routines. That way, the caller who is spinning up more routines can only concentrate on tracking its child goroutines. This routine will then inform its parent waitGroup only after its done (& its child is done, rather than letting the child routinue informing the grandparent directly).
Also, in fetch method after making the HTTP call and getting the response, why create another goroutine to process this data? Either way this goroutine cannot exit until the data insertion happens, nor is it doing someother action which data processing happens. From what I understand, The second goroutine is redundant.
group.Add(1) // QUESTION should I add a separate wait group here and pass it to insertPosts?
            go insertPosts(posts, container.Posts, group)
            defer group.Done()


text:
Q: How to parse information from blog to iphone? could someone point me in the right direction in how i can parse data from a blog to an iphone. E.g. You have a table view displaying the posts of the blog, you select a table cell and text content is displayed. Are there any tutorials/examples on this?
I have a bit of experience with parsing data using JSON (parsed data from database to iphone) but unsure on where to start with this?
Thanks for an help..

A: What you want to do is use the Wordpress API. The flow goes like this:

*

*Make an API call. This is a subject unto itself, but typically you'd use NSHTTPRequest and NSURLConnection to make the request.

*Parse the result. I forget if you get XML back; you probably do; in that case there are tons of solutions for parsing, including NSXMLParser and libxml2.

*Populate UITables, etc. with the retrieved information.

The Wordpress API is not that big or complex, but it's a bigger subject than I can really get into in the context of an SO answer, so I'll just refer you to the aforelinked documentation and wish you happy reading.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the default model manager (queryset?) for filters I want to change the default model manager of django rest framework filter and I can't seem to find a way to do it. My default model manager objects excludes some records, I have created objects_all for getting all records. filter seems to be using Model.objects instead of objects_all, is there a way I can somehow make it use objects_all so that filtering is possible.
filters.py
import rest_framework_filters as filters

ItemFilter(filters.FilterSet):
    name = filters.AllLookupsFilter()
    some_id = filters.NumberFilter(name="some_name")

    class Meta:
        model = Item

models.py
class myModel(models.Model):
    objects_all = models.Manager() # Rename the default model manager
    objects = ObjectsWithNoStateManager()
    objects_deleted = ObjectsDeletedManager()
    objects_archived = ObjectsArchivedManager()

A: It seems like you need to add extra filter to your ModelManager. Why don't you just add methods for that extra filter in single ModelManager rather than creating separate manager for each.
Here is the example https://docs.djangoproject.com/en/1.9/topics/db/managers/#adding-extra-manager-methods


text:
Q: Projects that were build with GWT I was wondering which projects were build in GWT? Especially by Google itself...

A: http://gwtgallery.appspot.com/ seems to be a starting point.

A: AdWords, AdSense, Google Health, Wave...

A: I work on mapfaire.com

A: Consider using the search functionality first next time. Projects that were build with GWT

A: Google Wave is the only one that I'm sure of (that was built by Google).
Here's another list of applications that use GWT.

A: new UI for blogger.com (avi at draft.blogger.com) is also built with GWT.


text:
Q: Can you include PHP in a Perl file? I have a page written in Perl by someone else. I don't know Perl, so I wrote a PHP file that right now just links from the Perl page. What I'd like to do is embed the PHP file in the Perl file if the perl page has been passed a certain variable. If I were using PHP for both I could just do
if ($_GET['sidebar']) include "embedded.php";

I know there are ways to read text files in Perl, but can I include a PHP file within a Perl file?
I'm assuming it wouldn't work because they're processed by different parts of the server, so no high hopes, but maybe someone's tried something like it.

A: Perl interpreter can execute Perl syntax commands, despite there are some similarities between Perl and PHP syntax, you will need a PHP interpreter to run PHP code.
Instead you can use some Perl commands to use output of a PHP script. you should execute the PHP script using the system PHP interpreter in your Perl code, and then use the output of that execution. your PHP code needs to be some command line code that will return (like echo or print) the output. if you need to pass arguments to the PHP code, use command line arguments when executing the PHP script in your Perl code.
so your Perl code will be like this:
 // your code before PHP call
 $php_output = `php /path/to/php/script -param1 -param2 -param3`;
 // your code after PHP call

and your PHP script can receive parameters like this:
<?php
// argv() is defined by PHP and contains all command line params
$params = argv();
// first index of argv is the name of the PHP script you are running.
array_shift($params);
// now you have all parameters.
// your code here generates some results.
echo $resutls;
?>

I'm not a Perl programmer, so there might be other (better) ways to execute a external program in Perl. but the general steps are like this.

A: If you simply want to include the resulting output (HTML, etc.) of the PHP script into the perl-generated page you can use backticks to call either the PHP script via php-cli, like this:
First, the test.pl script:
[root@www1 cgi-bin]# cat test.pl
#!/usr/bin/perl
print "This is a perl script\n";
my $output = `php test.php`;
print "This is from PHP:\n$output\n";
print "Back to perl...\n";
exit 0;

Next, the test.php script:
[root@www1 cgi-bin]# cat test.php
<?php

echo "PHP generated this";

?>

Here's the output of running "test.pl":
[root@www1 cgi-bin]# perl test.pl
This is a perl script
This is from PHP:
PHP generated this
Back to perl...

A: There are the PHP and PHP::Interpreter modules, both have an include method. Haven't tried either of them myself though.

A: You could check out this project:
http://metacpan.org/pod/PHP::Include

HP::Include builds on the shoulders of
  Filter::Simple and Parse::RecDescent
  to provide a Perl utility for
  including very simple PHP Files from a
  Perl program.
When working with Perl and PHP it is
  often convenient to be able to share
  configuration data between programs
  written in both languages. One
  solution to this would be to use a
  language independent configuration
  file (did I hear someone say XML?).
  Another solution is to use Perl's
  flexibility to read PHP and rewrite it
  as Perl. PHP::Include does the latter
  with the help of Filter::Simple and
  Parse::RecDescent to rewrite very
  simple PHP as Perl.
Filter::Simple is used to enable
  macros (at the moment only one) which
  cause PHP to be interpolated into your
  Perl source code, which is then parsed
  using a Parse::RecDescent grammar to
  generate the appropriate Perl.
PHP::Include was designed to allow the
  more adventurous to add grammars that
  extend the complexity of PHP that may
  be included.


text:
Q: jQuery code, how I can do easier to read I wanna try to make my code easier to read and I'm looking for a solution something like this, in Visual Basic:
 With $('.class or sector') {
    $(this).removeClass('some-class');
    $(this).addClass('some-other-class');
 } End With

I tried this, but it doesn't work:
$('.class or sector') = function() {
    $('.class or sector inside > *', this).addClass('some-class');
}

.container is a class inside .footer-finale
maybe anyone can help me

A: jQuery uses a fluent interface, so you can chain your calls.
$('.class')
    .removeClass('some-class')
    .addClass('some-other-class');

You can also assign a variable:
var item = $('.class');
item.removeClass('some-class');
item.addClass('some-other-class');


text:
Q: Eventually stopping a bouncing ball Creating a simple HTML5 Canvas program where there is an array of balls and each one moves at its own velocity and bounces against the canvas's 'walls'. I've also added gravity and friction by adding to the ball's vy and multiplying the vx and vy by a fraction of one, respectively.
For the bounce, I used a value of -0.7 so the ball loses a bit of energy on each bounce, but the problem is... it never completely 'stops'. It does a kind of 'bobbing' motion on the bottom of the map. Fiddle.
Here is the code that checks the boundaries...
checkBounds(ball, map, -0.7);
(note: checkBounds is defined in utils.js)
function checkBounds(obj, map, bounce) {
  bounce = bounce || -1;
  var offset = {
    x: obj.width / 2 || obj.radius,
    y: obj.height / 2 || obj.radius
  };
  var bounds = {
    left: map.left || 0,
    right: map.right || map.width || innerWidth,
    top: map.top || 0,
    bottom: map.bottom || map.height || innerHeight
  }
  if (obj.x - offset.x < bounds.left) {
    obj.x = offset.x;
    obj.vx *= bounce;
  } else if (obj.x + offset.x > bounds.right) {
    obj.x = bounds.right - offset.x;
    obj.vx *= bounce;
  }
  if (obj.y - offset.y < bounds.top) {
    obj.y = offset.y;
    obj.vy *= bounce;
  } else if (obj.y + offset.y > bounds.bottom) {
    obj.y = bounds.bottom - offset.y;
    obj.vy *= bounce;
  }
  return obj;
}

How would I make the ball ease into a stop at some point?


text:
Q: Derive macro generation I'm making my own Serializable trait, in the context of a client / server system.
My idea was that the messages sent by the system is an enum made by the user of this system, so it can be customize as needed.
Too ease implementing the trait on the enum, I would like to use the #[derive(Serializable)] method, as implementing it is always the same thing.
Here is the trait :
pub trait NetworkSerializable {
    fn id(&self) -> usize;
    fn size(&self) -> usize;
    fn serialize(self) -> Vec<u8>;
    fn deserialize(id: usize, data: Vec<u8>) -> Self;
}

Now, I've tried to look at the book (this one too) and this example to try to wrap my head around derive macros, but I'm really struggling to understand them and how to implement them. I've read about token streams and abstract trees, and I think I understand the basics.
Let's take the example of the id() method : it should gives a unique id for each variant of the enum, to allow headers of messages to tell which message is incoming.
let's say I have this enum as a message system :
enum NetworkMessages {
    ErrorMessage,
    SpawnPlayer(usize, bool, Transform), // player id, is_mine, position
    MovePlayer(usize, Transform), // player id, new_position
    DestroyPlayer(usize) // player_id
}

Then, the id() function should look like this :
fn id(&self) -> usize {
    match &self {
        &ErrorMessage => 0,
        &SpawnPlayer => 1,
        &MovePlayer => 2,
        &DestroyPlayer => 3,
    }
}

Here was my go with writting this using a derive macro :
#[proc_macro_derive(NetworkSerializable)]
pub fn network_serializable_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = syn::parse(input).unwrap();

    // Build the trait implementation
    impl_network_serializable_macro(&ast)
}

fn impl_network_serializable_macro(ast: &syn::DeriveInput) -> TokenStream {

    // get enum name
    let ref name = ast.ident;
    let ref data = ast.data;

    let (id_func, size_func, serialize_func, deserialize_func) = match data {
        // Only if data is an enum, we do parsing
        Data::Enum(data_enum) => {

            // Iterate over enum variants

            let mut id_func_internal = TokenStream2::new();
            let mut variant_id: usize = 0;

            for variant in &data_enum.variants {

                // add the branch for the variant
                id_func_internal.extend(quote_spanned!{
                    variant.span() => &variant_id,
                });
                variant_id += 1;
            }

            (id_func_internal, (), (), ())
        }
        _ => {(TokenStream2::new(), (), (), ())},
    };

    let expanded = quote! {
        impl NetworkSerializable for #name {
            // variant_checker_functions gets replaced by all the functions
            // that were constructed above
            fn size(&self) -> usize {
                match &self {
                    #id_func
                }
            }
            /*
            #size_func
            #serialize_func
            #deserialize_func
            */
        }
    };

    expanded.into()
}

So this is generating quite a lot of errors, with the "proc macro NetworkSerializable not expanded: no proc macro dylib present" being first. So I'm guessing there a lot of misunderstaning from my part in here.


text:
Q: Build input file cannot be found: '/Users/wt/myfolder/Todo/ios/QRCodeFrameProcessor/QRCodeFrameProcessor.swift'
At first my Project running fine. when I add this command according to
the library of react-native-vision-camera it adds some files in IOS
folder. I run this command npx vision-camera-plugin-builder iOS
and it add some folder of frame processor. after that it gives some
error whenever I run the code.  after that I delete all the folders of
QRFrameProcessing which was created . now I received another error

SwiftCompile normal x86_64 Compiling\ QRCodeFrameProcessor.swift /Users/wt/myprojects/todo/ios/QRCodeFrameProcessor/QRCodeFrameProcessor.swift (in target 'todo' from project 'todo')

/Users/wt/myprojects/todo/ios/ios/QRCodeFrameProcessor/QRCodeFrameProcessor.swift:1:2: error: @objc attribute used without importing module 'Foundation'
@objc(QRCodeFrameProcessorPlugin)

I just need to know that how to delete all the frame Processors which I have added from the above command I mentioned
this is the link where I add frame processor for IOS

A: you can check the Frame Processor manual setup instructions and revert these changes. For example for SWIFT version is like this:

*

*Remove QRCodeFrameProcessorPlugin.swift

*Remove generated BrigingHeaders files

*Remove QRCodeFrameProcessorPlugin.m

https://mrousavy.com/react-native-vision-camera/docs/guides/frame-processors-plugins-ios/#manual-setup


text:
Q: Regex expression for Python single and mulitline comments I am going to make Python editor with C#. I want to write a regex expression for single-line and multiline comment for Python. I was trying to modify this expression for single-line and multiline comment in C#, but I couldn't do it, because in C# they use /* and */ so we can know which is start or end. But in Python they only use """(or ''') so we can't know which is start or end.
Regex expression for C#:
/\*(?:(?!\*/).)*\*/

Example of singleline and multiline in Python
Singleline:
''' comment comment '''

""" comment comment """

Multiline
''' comment comment
comment comment
'''

""" comment comment
comment comment
"""

A: Something like this could work: /("""[^"]*+"""|'''[^']+'''|#[^\n]*)/ except...
While #stuff unambiguously denotes a comment, '''this one''' and """this
(next line)
other""" are not necessarily single/multi-line comments, they are just strings. The triple (single/double) quotes notation is for strings that can be split over multiple lines.
For example this is valid Python code.
s="""My name is Alice.
My name is Bob."""
So is this.
eggs("""spam, sausages,
spam, spam, spam""").
An accurate answer should take care to exclude at the very least the above two cases.

A: Try Regex: ("""|''')[\s\S]*?\1
Demo


text:
Q: Is `std::pow(double, int)` faster than `std::pow(double, double)`? if yes, how much faster? I saw this old question about std::pow: What is more efficient? Using pow to square or just multiply it with itself?
The old question mentions std::pow has a variant that is std::pow(double, int) and some users said this version might be faster.
Is std::pow(double, int) faster than std::pow(double, double)? if yes, how much faster?
p.s. standard boilerplate disclaimer about "I already know that premature optimization is evil, but I'm asking this optimization question for academic purposes or I've already identified that line/block of code as a bottleneck"

A: Expectation:
std::pow(double, int) is the log-reducing for loop for log(n) runtime.
std::pow(double x, double y) { exp(log(x) * y); }
Should be pretty close.

from comments:

*

*en.cppreference.com/w/cpp/numeric/math/pow (7) Since C++11, "If any argument has integral type, it is cast to double". – Bob__ Apr 11 '18 at 20:10

*My interpretation (I may be wrong and library implementers may disagree) of that statement is that until C++11, they may have had different implementations, but since C++11, they should share the same, while the parameters are simply casted. – Bob__ Apr 11 '18 at 20:25


text:
Q: javascript algorithm - check if record count falls between various number ranges I have a web page that loops through my query depending on a predetermined value. I want to print the query results in, say, 10 records per page. Since my users are going to print double-sided, I want a blank page inserted when total record count is between 21-30, 41-50, 61-70, 81-90, etc.  If total count falls in these ranges that means that the last page my results will be printed on is an odd-numbered page (other than 1) and so I need to insert a blank page so that the next query results are printed on the next odd-numbered page. For example, if total records are between 21-30, these will be printed on 3 pages and need a blank page inserted so that next results are printed starting on page 5. I know the code to insert the blank page but I don't know  the code as to when to insert the blank page.
Thanks for any help you can provide.


text:
Q: Spring Boot returns 404 for static resources with docker I'm using spring boot with docker. I have static resources in spring boot project and when I runt it with mvn spring:boot run everything works fine and resources are available. But when I create docker image from it using command
FROM openjdk:8-jdk-alpine
ADD /target/example-*.jar /
EXPOSE 8080
ENTRYPOINT java -jar example-*.jar

Then my static resources are not available by the localhost:8080. App started successfully(no errors in logs.)

A: Resources in a jar file can be tricky.
Here are some tips for trouble shooting:

*

*Is the url for the 404 the same with both methods of deployment?

*Inspect the jar file used in docker, are your resources even there?

*Try running the jar file without docker, I suspect your resources
are missing. If missing, you need to get maven to push them to the jar and you are probably not following the springboot conventions for resources.
Here is what worked for me when I needed to include a full springboot app as a dependency in a parent application:
Location

*

*Resources => src/main/resources/META-INF/resources/static

*View Templates => src/main/resources/WEB-INF/templates

If MVC, make sure you map your resources:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/static/**").addResourceLocations("classpath:META-INF/resources/static/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:META-INF/resources/webjars/");
    registry.addResourceHandler("/**").addResourceLocations("classpath:META-INF/");
}

Also needed some changes to my gradle build:
buildscript {
    ext {
        springBootVersion = '2.0.0.M7'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
        maven { url 'http://repo.spring.io/plugins-release' }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath 'io.spring.gradle:propdeps-plugin:0.0.9.RELEASE'
        classpath 'org.springframework:springloaded:1.2.6.RELEASE'
    }
}

ext {
    springBootVersion = '2.0.0.M7'
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'groovy'
//apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'propdeps'
apply plugin: 'propdeps-idea'

group = 'com.example.app'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

configurations {
    includeInJar
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-groovy-templates')
    compile('org.codehaus.groovy:groovy')

    includeInJar("org.webjars:bootstrap:4.0.0")
    includeInJar("org.webjars:jquery:3.3.1")
    configurations.compile.extendsFrom(configurations.includeInJar)
}

idea {
    module {
        inheritOutputDirs = true
    }
}

jar {
    from configurations.includeInJar.collect { it.isDirectory() ? it : zipTree(it) }
}

compileJava.dependsOn(processResources)


text:
Q: PHP class and var memory size confusion i've written this code to test the size of some objects in PHP
<?php
class MyClass
{
    public $string1="first string";
    public $string2="second string";
    public $string3="third string";

    public function __toString() {
        return $this->string;
    }
}

function mem() {
    return memory_get_usage(false);
}

$before = mem();
$class = new MyClass;
var_dump("new object size: ".(mem() -$before));

$before=mem();
$string = "test";
var_dump("string size: ".(mem() -$before));

$before=mem();
$objcopy = $class;
var_dump("object copy size: ".(mem() -$before));

$before=mem();
$objref = &$class;
var_dump("object reference size: ".(mem() -$before));

and this is the output in my system:
string(20) "new object size: 188"
string(15) "string size: 80"
string(20) "object copy size: 44"
string(25) "object reference size: 72"

i'm quite confusing now, why do we have: $class>$string>$objref>$objcopy
shouldn't be instead : $class=$objcopy>$string>$objref ?
$objcopy in fact contains 3 strings inside, instead $string is a single one..
could someone explain me how php handle memory with this kind of object?
thanks in advance.

A: You're observations base on wrong assumptions.
First of all, your $objcopy is a reference to the same instance as $class, because Instances are not cloned when assigning them to another variable. Check the manual or add this to your code:
$objcopy->string1 = 'a';
echo $class->string1, "\n";

Second, even if the assignment operator would effectively make them point to different objects, PHP would probably not allocate new memory because it uses copy-on-write optimization, see http://php.net/manual/en/internals2.variables.intro.php.
Finally, you can't expect precise memory informations returned by PHP. It may allocate more than the current statement requires and may implicitly free memory by the garbage collector. (Well, at least you can turn that off.)

A: Yes my question was based on wrong knowledge derived by C++ and other languages reference point of view.
So , after long research , i've created a post on my blog about this argument where i explain in depth how php handle memory.
http://hyperweb2.com/home/blog/2013/10/11/php-reference-vs-copy-vs-clone/


text:
Q: discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role This seems like a popular error, but I can't for the life of me find a fix that'll work for me. I'm trying to give a member a role whenever they join my server but every time it reaches await member.add_roles(member, role) it sends off the error in the title. I've tried testing in the on_message function with the exact same results.
import os
import discord
from discord.ext import commands
from replit import db

client = discord.Client()

intents = discord.Intents.all()
client = commands.Bot('PREFIX',intents=intents)

@client.event
async def on_ready():
  print("I'm in")
  print(client.user)

@client.event
async def on_message(message):

  if message.author == client.user:
    return

  if message.content == "ping":
    await message.channel.send("pong")

@client.event
async def on_member_join(member):
    print(f"{member} has joined")
    role = discord.utils.get(member.guild.roles, name="Member")
    await member.add_roles(member, role)

client.run(token)

A: print(f"{member} has joined")
role = discord.utils.get(member.guild.roles, name="Member")
await member.add_roles(member, role) # member argument is causing issue, remove that

member is discord.Member object, if you put that in add_roles, it will error out and throw discord.NotFound 404
print(f"{member} has joined")
role = discord.utils.get(member.guild.roles, name="Member")
await member.add_roles(role)

also consider getting rid of that client = discord.Client() line, it's quite useless


text:
Q: which is the best way to maintain controls values during post back in MVC4? currently i am using ViewData and Viewbag for storing data and tempdata for redirection all are working fine.
i just want to know is there any optimize way to store data or controls values during postback in MVC ?
this is my controller method , i am passing two model classes from controller to view using dynamic object.
    [HttpGet]
    public ActionResult Index(int? page)
    {

        IList<Customer> _CustomerList = new List<Customer>();
        IList<LCOddl> LCODDL= new List<LCOddl>();

        // some logic to bind both classed with database ..

        dynamic DashboardClassed = new ExpandoObject();
        DashboardClassed.LCODDL = LCODDL;
        DashboardClassed.CUSTOMER = _CustomerList.ToPagedList(page ?? 1, 30);

   return View(DashboardClassed);

    }

here is my razor view which use dynamic object :
@using PagedList;
@using PagedList.Mvc;
@model dynamic
@{
    Layout = null;
 }
 @using (Html.BeginForm("SearchMethod", "Dashboard", FormMethod.Post))
                            {
 @foreach (Models.LCOddl item in Model.LCODDL)
     {
        // Render HTML
     }

 @foreach (Models.Customer item in Model._CustomerList )
     {
        // render html
     }

<button type="submit" class="btn btn-success">Go</button>

   }

after button click from my razor view SearchMethod from Dashboard Controller will called .
Now here i want two things :

*

*Don't want to bind customer class again with database - for that i am using tempdata .

*i have to maintain paging using PagedList.

again my question is same should i use tempdata for storing data or is there any other optimize way to do the same.

A: The best way to retain your form values during a post back is to bind your view to a view model.
I wrote an answer as to what a view model is, please go and read it:
What is ViewModel in MVC?
Let us go through it step by step. I do not know what you are trying to achieve so I am going to use my own example. Let us assume you are trying to add a new user.
First of all create your view model for your form data. Your view model is different to your domain model in that it only contains the data that you want to use on your view. Sometimes your domain model might contain lots of data, but you do not want to add or edit everything. So you create a view model with only the data that you want to add or edit. In our example, I only want to add a first and last name for my user, so I will create 2 properties, namely FirstName and LastName:
public class UserViewModel
{
     public string FirstName { get; set; }

     public string LastName { get; set; }
}

The above view model will be instantiated and be passed to the view from your action method. When your form is posted your action method will receive this view model as a parameter. It will contain the values of first and last name (if entered):
public class UserController : Controller
{
     private IUserRepository userRepository;

     public UserController(IUserRepository userRepository)
     {
          this.userRepository = userRepository;
     }

     public ActionResult Create()
     {
          UserViewModel model = new UserViewModel();

          return View(model);
     }

     [HttpPost]
     public ActionResult Create(UserViewModel model)
     {
          // Do some form validation
          if (!ModelState.IsValid)
          {
               return View(model);
          }

          // If form validation succeeds do what you need to do
     }
}

In your create view it will receive this view model. All that you then need to do is to create a form with 2 textboxes for first and last name and a submit button:
@model YourProjectName.ViewModels.UserViewModel

@using (Html.BeginForm())
{

          @Html.TextBoxFor(m => m.FirstName, new { maxlength = "50" })
          @Html.ValidationMessageFor(m => m.FirstName)

          @Html.TextBoxFor(m => m.LastName, new { maxlength = "50" })
          @Html.ValidationMessageFor(m => m.LastName)

          <button type="submit">Save</button>

}

This is really a basic example. Go through it, play around with the code so that you can implement it into your scenario.


text:
Q: Can I be a guild master of two guilds? I was just made Guild Master of the Thieves Guild, and was planning on becoming Guild Master of the Companions, but then the thought popped into my mind that I might not be able to become Guild Master of two guilds. So I looked it up and got nothing, and  that's why I'm asking here.

A: Yes.
Becoming the leader of any guild in the game does not hinder your progress through the others in any way. They have completely standalone quest lines.
For all intents and purposes the "guilds" of Skyrim are:

*

*The College of Winterhold

*The Companions

*The Dark Brotherhood

*The Thieves Guild

Similar but separate factions include:

*

*The Bards College - can be joined as a sort of "helping hand" but not a student, and has no progression

*The Blades - can be joined but not led, nor is there any progression

*The Imperial Legion - there is progression but you can only reach the highest rank of a soldier and the quest line is mutually exclusive with The Stormcloaks

*The Stormcloaks - the opposite and contemporary of The Imperial Legion

The main point of intersection between a guild quest and another quest line is during the Dark Brotherhood when it overlaps with the civil war quest line. This will cause some stalling while one quest line waits for the other but the game and dialog handle it pretty well.


text:
Q: Is there any method to use differently extract_table function in R? original pdf files
I am trying to use extract_tables in tabulizer package.
library(tabulizer)
setwd("directory")
pdf_file <- "filenames.pdf"
cle <- extract_tables(pdf_file, pages=47 ,method="stream", encoding="UTF-8")

what I needed to use extract_table function, is just this code.
However, there is a critical problem. It merges some column automatically

you might understand the situation when you see two images.
Column 6 and 7, in pdf table image is merged.
not
0.9000 | -
0.6450 | -
0.7470 | -
the two columns are merged like
0.9000-
0.6450-
0.7470-
So I want to find method do not making table like this, also which is general method.
Therefore I tried to put another component in the function like this.
library(pdftools)
library(tabulizer)
files <- list.files(pattern = "pdf$")

opinions <- lapply(files, pdf_text)

cle <- extract_tables(opinions[[2]][47],method="stream", encoding="UTF-8")

*!Error in normalizePath(path.expand(path), winslash, mustWork) :*

So please leave any solution if you know what I should do about it. thanks.


text:
Q: how to solve 'tensorflow' has no attribute 'init_scope' I'm using TensorFlow 1.8 in windows.  I used object_detection sample for my project and when i run train.py i get this error:
    (tensorflow_gpu) C:\Users\hewil\Desktop\Tensorflow\models\research>python train.py --logtostderr --train_dir=object_detection/CAPTCHA_training/ --pipeline_config_path=object_detection/CAPTCHA_training/faster_rcnn_inception_v2_coco.config
WARNING:tensorflow:From C:\Users\hewil\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\platform\app.py:126: main (from __main__) is deprecated and will be removed in a future version.
Instructions for updating:
Use object_detection/model_main.py.
WARNING:tensorflow:From C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\legacy\trainer.py:266: create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Please switch to tf.train.create_global_step
WARNING:tensorflow:num_readers has been reduced to 1 to match input file shards.
Traceback (most recent call last):
  File "train.py", line 184, in <module>
    tf.app.run()
  File "C:\Users\hewil\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\platform\app.py", line 126, in run
    _sys.exit(main(argv))
  File "C:\Users\hewil\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\util\deprecation.py", line 250, in new_func
    return func(*args, **kwargs)
  File "train.py", line 180, in main
    graph_hook_fn=graph_rewriter_fn)
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\legacy\trainer.py", line 291, in train
    clones = model_deploy.create_clones(deploy_config, model_fn, [input_queue])
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\slim\deployment\model_deploy.py", line 193, in create_clones
    outputs = model_fn(*args, **kwargs)
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\legacy\trainer.py", line 204, in _create_losses
    prediction_dict = detection_model.predict(images, true_image_shapes)
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\meta_architectures\faster_rcnn_meta_arch.py", line 822, in predict
    prediction_dict = self._predict_first_stage(preprocessed_inputs)
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\meta_architectures\faster_rcnn_meta_arch.py", line 873, in _predict_first_stage
    image_shape) = self._extract_rpn_feature_maps(preprocessed_inputs)
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\meta_architectures\faster_rcnn_meta_arch.py", line 1252, in _extract_rpn_feature_maps
    feature_map_shape[2])]))
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\core\anchor_generator.py", line 108, in generate
    anchors_list = self._generate(feature_map_shape_list, **params)
  File "C:\Users\hewil\Desktop\Tensorflow\models\research\object_detection\anchor_generators\grid_anchor_generator.py", line 111, in _generate
    with tf.init_scope():
AttributeError: module 'tensorflow' has no attribute 'init_scope'

how should I solve that?

A: Following this thread https://github.com/tensorflow/hub/issues/324 it seems that TensorFlow only has the init_scope attribute on version higher than 9. I have TensorFlow 1.12 up and running perfectly for object detection as well.
Give that a shot and let me know how that goes.
P.S. you might want to purge your installation and start from scratch with the specific version. 1.12.0 should do the trick.
Cheers,


text:
Q: Running iPhone crash Logs from testers on XCode When I'm running my app on my device using XCode and I have a crash it's easy tracking where it happened on code.
However, when I deploy my ad-hoc version to testers and they have a crash, is there a way for me to load the crash on XCode as if it crashed on my computer, actually seeing the stack and the variable values ?
Thanks

A: As far as I know, there is no known method to obtain a full core dump file for iOS apps that you can later load on GDB.
Are you already asking your testers to send you the crash logs? Read this otherwise:
Understanding and Analyzing iPhone OS Application Crash Reports
Basically:

When the user synchronizes their device using iTunes, crash reports are
  copied to a directory on the user's
  computer. […]  Depending on the
  platform, the directory is:
Mac OS X:
  ~/Library/Logs/CrashReporter/MobileDevice/
Windows XP: C:\Documents and
  Settings\\Application
  Data\Apple
  Computer\Logs\CrashReporter\MobileDevice\
Windows Vista or 7:
  C:\Users\\AppData\Roaming\Apple
  Computer\Logs\CrashReporter\MobileDevice\


text:
Q: Automating TortoiseSVN and Not to show Log Windows? Is there any parameter for Automating TortoiseSVN and Not to show Log Windows?

A: TortoiseSVN is a GUI client and is not meant to be used in this way. If you don't want a GUI, don't use a GUI - use the command-line client (bundled with TortoiseSVN 1.7 and newer installers), or use the client libraries/language bindings for your language/scripting environment of choice.


text:
Q: VBA Open workbook and assign it to variable error I'm writing macro that goes through the file and marks lines that match some conditions as OK. Everything works fine when launched from the file. The problem is that when I try to launch it from another workbook I keep getting this error "Run time error 1004: Select method or Range class failed" at line
Range("C2").Select
I think that the problem lies in assigning opened file to the variable mainFile. (I can browse for the file, it opens and I can enter the year I want then it crashes)
Could you tell me what I'm doing wrong?
    Sub sbVBA_To_Open_Workbook_FileDialog()

Dim strFileToOpen As Variant
Dim mainFile As Workbook

    strFileToOpen = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", MultiSelect:=False)

    If TypeName(strFileToOpen) = "String" Then
        Set mainFile = Workbooks.Open(strFileToOpen)
    Else
        MsgBox "No file selected."
        Exit Sub
    End If

'sub data works fine
Call data

With mainFile

'Everything below works fine when launched in the mainfile
Dim myYear As Date

myYear = InputBox("Choose year", "Choose year", 2018)

    Range("C2").Select

    Do Until ActiveCell.Value = ""

    If ActiveCell.Offset(0, 2) = "M" Then

        If ActiveCell.Offset(1, 2) = "C" Then

                If Day(ActiveCell.Value) = 1 Then

                                If Year(ActiveCell.Value) = myYear Then

                                    If Month(ActiveCell.Value) & Year(ActiveCell.Value) = Month(ActiveCell.Offset(1, 0).Value) & Year(ActiveCell.Offset(1, 0).Value) Then

                                    '^Comparing years and months

                                        If DateSerial(Year(ActiveCell.Offset(1, 0).Value), Month(ActiveCell.Offset(1, 0).Value + 1), 0) = ActiveCell.Offset(1, 0).Value Then
                                        ' ^End of month?

                                            ActiveCell.Offset(0, 10).Value = "OK"
                                        Else
                                        ActiveCell.Offset(0, 10).Value = "NOK"
                                        End If

                                    Else
                                    ActiveCell.Offset(0, 10).Value = "NOK"
                                    End If

                                Else
                                ActiveCell.Offset(0, 10).Value = "NOK"
                                End If

                Else
                ActiveCell.Offset(0, 10).Value = "NOK"
                End If
        Else
        ActiveCell.Offset(0, 10).Value = "NOK"
        End If
    Else
    ActiveCell.Offset(0, 10).Value = "NOK"
    End If

ActiveCell.Offset(1, 0).Select

Loop

End With

End Sub

A: Just because you open a workbook, it won't automatically assume it's the active workbook.
Please try the following code after the "With mainFile" row:
mainFile.Sheets([your desired sheet]).Activate

Then, before the range.select part, add activesheet:
ActiveSheet.Range("C2").Select


text:
Q: System hangs while using chromedriver 2.20 for chrome browser automation I am using chromedriver 2.20 for chrome browser automation. But system hangs when the execution starts. Tried with chromedriver 2.19 also.
Driver initialization:
System.setProperty("webdriver.chrome.driver", rootDir+ "/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().deleteAllCookies();

System Config:
Intel core i7 processor, 64bit OS, RAM: 16GB
Please suggest any solution.

A: Not facing any issue with below sample code on Win 7, 64-bit. Please share chromedriver log
System.setProperty("webdriver.chrome.driver","/path/to/chromedriver.exe"));
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
driver.manage().deleteAllCookies();
driver.get("http://www.google.com/");
System.out.println(driver.getTitle());


text:
Q: Tetris in GridWorld won't compile I have an AP Computer Science assignment to make Tetris using GridWorld.  I have to make 4 classes, TetrisBug, TetrisGame, TetrisBlock, and TetrisBlockO.
Here are the codes in that order:
TetrisBug.java
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.ArrayList;
import java.awt.Color;

public class TetrisBug extends Bug
{
    public TetrisBug(Color color)
    {
        super(color);
        setDirection(180);
    }

    public void move()
    {

        Grid<Actor> gr = getGrid();
        if (gr == null)
            return;
        Location loc = getLocation();
        Location next = loc.getAdjacentLocation(getDirection());
        if (gr.isValid(next))
            moveTo(next);
        else
            removeSelfFromGrid();
    }

    public void act()
    {
        //this is empty for a reason.
    }
}

TetrisGame.java
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.ArrayList;
import java.awt.Color;
import info.gridworld.*;

public class TetrisGame {

    public static ActorWorld world = new ActorWorld(new BoundedGrid<Actor>(19, 17));

    public static TetrisBlock currentBlock;

    public static int score;

    public static void main(String[] args) {
        //set up world
        for (int i = 0; i < 19; i++) {
            world.add(new Location(i,11),new Rock());
            world.add(new Location(i,0),new Rock());
        }
        nextTetrisBlock();
        //needed code for keyboard event handling
    java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new java.awt.KeyEventDispatcher() {
        public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) {
            String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString();
            if (key.equals("pressed UP"))
                currentBlock.rotate();
            if (key.equals("pressed RIGHT"))
                currentBlock.moveRight();
            if (key.equals("pressed DOWN"))
                currentBlock.act();
            if (key.equals("pressed LEFT"))
                currentBlock.moveLeft();
            world.show();
            return true;
        }
    });
        world.show();
    }
    /**
    * Calls removeCompleteRows and chooses a new TetrisBlock at random
    */
    public static void nextTetrisBlock() {
        removeCompleteRows();
        TetrisBlock randomBlock = new TetrisBlock();//default 2block piece
        //choose random block
        int randNum = (int)(Math.random()*7)+1;//random number between 1 and 7
        //if(randNum == 1)
            // randomBlock = new TetrisBlockO();
        //if(randNum == 2)
            // randomBlock = new TetrisBlockI();
        //if(randNum == 3)
            // randomBlock = new TetrisBlockT();
        //if(randNum == 4)
            // randomBlock = new TetrisBlockL();
        //if(randNum == 5)
            // randomBlock = new TetrisBlock_L();
        //if(randNum == 6)
            // randomBlock = new TetrisBlockZ();
        //if(randNum == 7)
            // randomBlock = new TetrisBlock_Z();
        currentBlock = randomBlock;
    }
    /**
    * checks each row 1 through 18 (skip row 0) for full rows
    * if a row is full, then remove the actor from each cell in that row
    * and ask each actor located above the just deleted row to act and
    * update the score++
    */
    public static void removeCompleteRows() {
        int columnsFilled = 0;
        Grid grid = world.getGrid();
        int row = 0;
        //loops through rows only after each column has finished
        for(row = grid.getNumRows()-1; row >= 0; row--) {        //needed >=
            columnsFilled = 0;             //need to reinitialize this every iteration
            for(int col = 0; col <= grid.getNumCols() - 1; col++) { //needed <=

                if (grid.get(new Location(row,col)) != null) {
                    columnsFilled++;
                }
            }
            if (columnsFilled == 10) {
                for(int col = 0; col <= grid.getNumCols(); col++){
                    world.remove(new Location(row,col));
                }
                columnsFilled =0;
            }
        }
    }
}

TetrisBlock.java
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.util.ArrayList;
import java.awt.Color;
/**
 * TetrisBlock is a type of Bug. It will act in GridWorld by moving down
 * (direction 180) if it can, otherwise it will ask TetrisGame to make a new
 * TetrisBlock for the game.
 */
public class TetrisBlock extends TetrisBug {
    /**
     * value of the current rotation position {0,1,2 or 3}
     */
    protected int rotationPos;
    /**
     * blocks will have three TetrisBug objects in it... they will be added in the
     * constructor
     */
    protected ArrayList<TetrisBug> blocks;
    /**
     * used as a convenient reference to the Grid
     */
    protected Grid<Actor> gr;
    /**
     * default constructor
     */
    public TetrisBlock() {
        super(Color.blue);
        rotationPos = 0;
        gr = TetrisGame.world.getGrid();
        // ==> LAMEST GAME OVER EVER !!! <==
        // if the Grid does not have room for the TetrisBlock.. GameOver
        if (gr.get(new Location(0, 5)) != null
        || gr.get(new Location(1, 5)) != null) {
            javax.swing.JOptionPane.showMessageDialog(null, "Score: "
                + TetrisGame.score, "GAME OVER!", 0);
            System.exit(0);
        }
        putSelfInGrid(gr, new Location(1, 5));
        blocks = new ArrayList<TetrisBug>();
        TetrisBug a;
        // create TetrisBugs for ArrayList blocks and put them in Grid gr
        a = new TetrisBug(Color.blue);
        a.putSelfInGrid(gr, new Location(0, 5));
        blocks.add(a);
        // TetrisBlock subclasses will add two more TetrisBug objects to blocks
    }

    /**
     * TetrisBlock and its TetrisBugs must face down (direction 180) If they can
     * move down, they will. Otherwise, it will ask TetrisGame to create a new
     * TetrisBlock since this one is stuck at the bottom.
     */
    public void act() {
        setDirection(180);
        for (TetrisBug tb : blocks)
            tb.setDirection(180);
        if (canMoveDown())
            moveDown();
        else {
            if (!TetrisGame.currentBlock.canMoveDown())
                TetrisGame.nextTetrisBlock();
        }
    }

    /**
     * Move the TetrisBlock and its TetrisBugs one cell. (they should already be
     * facing down) Note: The order in which all the TetrisBugs move is important
     * and depends on the current rotationPos.
     */
    public void moveDown() {
        if (rotationPos == 0) {
            move();
            blocks.get(0).move();
        } else if (rotationPos == 1) {
            blocks.get(0).move();
            move();
        }
    }

    /**
     * Returns true if the TetrisBlock and its TetrisBugs can move (they should
     * already be facing down) Otherwise, returns false.
     */
    public boolean canMoveDown() {
        if (rotationPos == 0)
            return canMove();
        else if (rotationPos == 1)
            return canMove() && blocks.get(0).canMove();
        else
            return true;
    }

    /**
     * Sets the direction of the TetrisBlock and its TetrisBugs to 90 (right) If
     * they can move, they will move one cell (to the right)
     */
    public void moveRight() {
        setDirection(90);
        for (TetrisBug tb : blocks)
            tb.setDirection(90);
        if (rotationPos == 0) {
            if (canMove() && blocks.get(0).canMove()) {
                blocks.get(0).move();
                move();
            }
        } else if (rotationPos == 1) {
            if (canMove()) {
                move();
                blocks.get(0).move();
            }
        }
    }

    /**
     * Sets the direction of the TetrisBlock and its TetrisBugs to 90 (right) If
     * they can move, they will move one cell (to the right)
     */
    public void moveLeft() {
        setDirection(270);
        for (TetrisBug tb : blocks)
            tb.setDirection(270);
        if (rotationPos == 0) {
            if (canMove() && blocks.get(0).canMove()) {
                blocks.get(0).move();
                move();
            }
        } else if (rotationPos == 1) {
            if (canMove() && blocks.get(0).canMove()) {
                blocks.get(0).move();
                move();
            }
        }
    }

    /**
     * If the TetrisBlock and its TetrisBugs can rotate, then they will all move
     * to their proper location for the given rotation designated by
     * rotationPos... Update rotationPos.
     */
    public void rotate() {
        Location nextLoc;
        if (rotationPos == 0) {
            // only one block must move
            nextLoc = new Location(getLocation().getRow() - 1,
                getLocation().getCol() + 1);
            if (gr.isValid(nextLoc) && gr.get(nextLoc) == null) {
                moveTo(nextLoc);
                rotationPos = (rotationPos + 1) % 2;// will be % 4 with 4 blocks
            }
        } else if (rotationPos == 1) {
            nextLoc = new Location(getLocation().getRow() + 1,
                getLocation().getCol() - 1);
            if (gr.isValid(nextLoc) && gr.get(nextLoc) == null) {
                moveTo(nextLoc);
                rotationPos = (rotationPos - 1) % 2;// will be % 4 with 4 blocks
            }
        }
    }
}

TetrisBlockO.java
public class TetrisBlockO{
public TetrisBlockO() {
        rotationPos = 0;
        gr = TetrisGame.world.getGrid();

        //GAME OVER!
        if (gr.get(new Location(0, 5)) != null
         || gr.get(new Location(1, 5)) != null
         || gr.get(new Location(0, 6)) != null
         || gr.get(new Location(1, 6)) != null) {
            javax.swing.JOptionPane.showMessageDialog(null, "Score: " + TetrisGame.score, "GAME OVER!", 0);
            System.exit(0);
        }

        putSelfInGrid(gr, new Location(1, 5));

        blocks = new ArrayList<TetrisBrick>();

        TetrisBrick a;
        a = new TetrisBrick(Color.blue);
        a.putSelfInGrid(gr, new Location(0, 5));
        blocks.add(a);

        TetrisBrick b;
        b = new TetrisBrick(Color.blue);
        b.putSelfInGrid(gr, new Location(1, 6));
        blocks.add(b);

        TetrisBrick c;
        c = new TetrisBrick(Color.blue);
        c.putSelfInGrid(gr, new Location(0, 6));
        blocks.add(c);
    }
}

The first problem I'm having is in TetrisGame.  The last method, to be precise.  The grid.length statement is refusing to compile, and when I added a Grid grid = new Grid(); statement, it said it was abstract method and couldn't be instantiated.  And compiling any of them give me a compiler warning,

\GridworldTetris\TetrisGame.java uses unchecked or unsafe operations.
Recompile with -Xlint:unchecked for details

The second problem is with the rotate method in TetrisBlock.  I am not sure whether it works or not since the TetrisGame wont compile.  I cant test it, but a friend of mine keeps telling me it's wrong, though IDK whether to believe him.  Some validation would be nice.
Anyway, I have no real time limit on this, but I'd really like to be done with it.  Thanks.
~Keelen
UPDATE:  Thanks to user3580294 I solved the grid problem.  But I found another, GRID DOESNT HAVE A LENGTH METHOD...  I know what I was trying to do WOULD work, but cant find a way to do it, besides grid.length, which is invalid.  Could someone make me a method that'd successfully remove completed rows?  I really am stuck here... And I want to move to the next project...

A: For your removeCompleteRows() method try this in your if statement:
if (columnsFilled == 10) {
    for(int col = 1; col < grid.getNumCols() - 1; col++){
        grid.get(new Location( row,col )).removeSelfFromGrid();
    }
    columnsFilled = 0;
}

I think the World remove() method might work, but generally you won't have access to the World your Actor is on, so using Grid's removeSelfFromGrid() is safer.
Also, I assume you only want to remove the Blocks not your walls so you only want to iterate through Locations your Blocks might occupy, 1 through getNumCols() - 1.


text:
Q: How do I get my Nav menu to dissapear after I click one of the links? this is my first time asking a question here so forgive me if it's confusing. I did an online tutorial on youtube from DevEd where he shows you how to code a responsive animated nav bar. The original video can be found here...
https://www.youtube.com/watch?v=gXkqy0b4M5g&list=PLbt4Kgx40Ie0bXokczYmcdxLD_KvYDXv9&index=5&t=101s&ab_channel=DevEd
What I want to know is how you alter the js so that the nav menu dissapears when you click on a link as well as when the burger button is clicked. Here's the HTML...

The Nav

Home

About

Work

Projects

and here's the js...
const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');
    const navLinks = document.querySelectorAll('.nav-links li');
//toggle nav
    burger.addEventListener('click', () => {
        nav.classList.toggle('nav-active');

//animate links
    navLinks.forEach((link, index) => {
            if (link.style.animation) {
                link.style.animation = ''
            } else {
                link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;

            }
        });
//burger animation
    burger.classList.toggle('toggle');

    });

}

navSlide();

I'm a relative newbie at this so please go easy.
Thanks in advance!

A: Go to the point in function where you want to hide the navbar and do:
document.getElementsByTagName("nav")[0].style.display = "none";

A: After a little digging I found a similar problem and here's the solution:
  const closeNav = () => {
    nav.classList.toggle('nav-active');
    burger.classList.toggle('toggle');
  }
  navLinks.forEach(link => link.addEventListener('click', closeNav));
}

added to ajvascript just after burger.classList.toggle('toggle'); });


text:
Q: how can i access scanner and scan document using java, jquery or javascript How can i access scanner and scan document using java, jquery or javascript.Please give me a solution..
I have tried with aspire scanner.js .But while using with chrome version 42, it shows like no longer support java extention.
I would like to implement scanning for web applications.
Please let me know if there any solution..
Thanks in advance

A: Chrome 42 is supported by Scanner.js. You may try out scanner.js's html5/JavaScript web browser based scanning demo here.
Scanner.js supports both NPAPI browsers (like Chrome 44 and lower, IE, Firefox, Opera) and Non-NPAPI browsers (Chrome 45+, Edge).
When running Scanner.js from NPAPI browsers, it attempts to use a Java applet so that no software is required to install. As for non-NPAPI browsers, scan app is required.

A: There are two ways to make JavaScript work for scanning documents:

*

*JavaScript API provided by web browser. For example, in ChromeOS, you can easily use JavaScript API to access scanner.

*Establish a communication mechanism between scanner service and web client JavaScript API. For example, Dynamic Web TWAIN runs a service to access document scanners and transfer document images to JavaScript via websocket.


text:
Q: brew install v8 not working I doubt this has to do with my os (OSX) but after running brew update && brew doctor I tried to run brew install v8
xerox:rewardsummit-rails home$ brew install v8
==> Downloading https://github.com/v8/v8/archive/3.25.30.tar.gz     Already downloaded:     /Library/Caches/Homebrew/v8-3.25.30.tar.gz
==> Patching
==> Cloning http://gyp.googlecode.com/svn/trunk
Updating /Library/Caches/Homebrew/v8--gyp--svn
svn: E175002: Unable to connect to a repository at URL 'http://gyp.googlecode.com/svn/trunk'
svn: E175002: OPTIONS of 'http://gyp.googlecode.com/svn/trunk': Could not read status line:     connection was closed by server (http://gyp.googlecode.com)
Error: Failed to download resource "v8--gyp"
Failure while executing: svn up -q --force /Library/Caches/Homebrew/v8--gyp--svn -r 1831

I know nothing about SVN.


text:
Q: Tab key is not working in firefox at key press event TAB Key is not Working in FireFox at key press event for this code
   $('.Number').keypress(function (event) {
    if (!/\d/.test(String.fromCharCode(event.which))) {
        $('#error').attr('class', 'errorMessage');
        $('#error').text("Enter Only Numbers");
        return false;
    }
    else {
        $('#error').attr('class', ' display: none;');
        $('#error').text("");
        return true;
    }
});

A: $('.Number').keydown(function (event) {

    var keycode = event.which;

    if (!/[\d\t\b]/.test(String.fromCharCode(event.which)) || event.shiftKey ) {
        $('#error').attr('class', 'errorMessage');
        $('#error').text("Enter Only Numbers");
        return false;
    } else {
        $('#error').attr('class', ' display: none;');
        $('#error').text("");
        return true;
    }
});

DEMO


text:
Q: How to add a reference to a file in xcodeproj without going through xcode I through the objective-c in the writeToFile: atomically: encoding: error: method to generate some .h and .m files, but after the file generation I have to xcode in add files to "projectName" this way into the file Project, there is no way in the document generation, to operate xcodeproj, xcodeproj the introduction of the document automatically added?
I compare tools through the beyond compare two xcodeproj documents found in the differences


text:
Q: Swift 3 Playground on XCode 8 "Ambiguous reference to member 'joined()' Error I have the Dictionary:
let alphabet: [Character: Int] = ["a": 0, "b": 1, "c": 2, "d": 3]

let validSet = CharacterSet.init(charactersIn: alphabet.keys.joined())

and that's when I get the error. How could I fix this and Why is it happening?
Any ideas?

A: If you don't want to change your key type to String as already suggested, then map the Characters to Strings:
let alphabet: [Character: Int] = ["a": 0, "b": 1, "c": 2, "d": 3]
let validSet = CharacterSet(charactersIn: alphabet.keys.map{String($0)}.joined())

A: The only thing you should change to make it work is the type of keys, from Character to String:
let alphabet: [String: Int] = ["a": 0, "b": 1, "c": 2, "d": 3]
let validSet = CharacterSet.init(charactersIn: alphabet.keys.joined())


text:
Q: The databind bind() function belongs to which class? The one-way databind Eval function belongs to DataBinder class and can be accessed in a page through TemplateControl.Eval method that calls the DataBinder.Eval method using the GetDataItem method to resolve the object reference that the expression is evaluated against, phew!
OK... so, how the two-way databind Bind function works? It belongs to which class?

A: I would like to  say ,Bind() method was nowhere to be found, even using Reflector.
---for read-write values such as TextBoxes (also known as "two-way databinding") you can use the Bind() statement. Where does that Bind() statement come from?
To be specifically, there isn't a bind method in ASP.NET! When ASP.NET parses your file and sees you're using a databinding expression (in the angle-bracket-percent-pound format, "<%# %>") it has special-case code to parse for the Bind syntax and generates some special code for it. When you use <%# Bind("Name") %> it's not a real function call.
If ASP.NET parses the code and detects a Bind() statement, it splits the statement into two parts. The first part is the one-way databinding portion, which ends up being just a regular Eval() call. The second part is the reverse portion, which is typically some code along the lines of "string name = TextBox1.Text" that grabs the value back out from where it was bound.
Non-Bind() databinding statements are literal code (we use CodeSnippetExpressions in CodeDom), so arbitrary code in the language of your choice is allowed. However, because ASP.NET has to parse Bind() statements, two-way databinding doesn't support anything other than Bind(). For example, the following syntax is invalid because it tries to invoke arbitrary code and use Bind() at the same time: <%# FormatNameHelper(Bind("Name")) %>
The only formats supported in two-way databinding are Bind("field") and Bind("field", "format string {0}"). There are some very minor variations of these syntax examples, such as allowing use of single quotes and not just double quotes. Since some languages supported by ASP.NET favor one format over the other, we have to support both formats, even though the language you're using may support only one.

A: As far as I could tell the "Bind" is not a method but rather a language construct.
Source and further reading: http://weblogs.asp.net/leftslipper/archive/2007/06/29/how-asp-net-databinding-deals-with-eval-and-bind-statements.aspx


text:
Q: How to use HostBuilder for WebJob? With .Net 2.0 was introduced the really usefull HostBuilder for Console App like we have with WebHostBuilder for Web Application.
My concern is now how to implement the HostBuilder with WebJob with a QueueTrigger?
Until now, I was using JobActivator:
        var startup = new Startup();
        var serviceProvider = startup.ConfigureServices(new ServiceCollection());
        startup.Configure(serviceProvider);

        var jobHostConfiguration = new JobHostConfiguration()
        {
            JobActivator = new JobActivator(serviceProvider),
        };

        var host = new JobHost(jobHostConfiguration);
        host.RunAndBlock();

For a full sample, here is my code:
https://github.com/ranouf/DotNetCore-CosmosDbTrigger-WebJob/tree/master/CosmosDbTriggerWebJob.App
Is there someone who already use HostBuilder for a WebJob with a QueueTrigger? Is it possible?
Thanks

A: Right then, I've figured this out. Firstly ensure that you've upgraded your packages to use the latest v3 versions of the appropriate WebJob packages.
I found that I needed the following:

*

*Microsoft.Azure.WebJobs

*Microsoft.Azure.WebJobs.Core

*Microsoft.Azure.WebJobs.Extensions.ServiceBus

Then you can use the builder in your Main method for the Console project as follows:
 static async Task Main()
    {
        var builder = new HostBuilder();
        builder.ConfigureAppConfiguration(cb =>
        {
            cb.AddJsonFile("appsettings.json");
        });
        builder.ConfigureWebJobs(b =>
        {
            b.AddServiceBus();
        });
        await builder.RunConsoleAsync();
    }

Note that I've enabled the language feature 7.1 to support async Main methods. You can use 'Wait()' instead if you prefer. Then I added an appsettings.json file to my project as follows:
{
   "ConnectionStrings": {
      "AzureWebJobsServiceBus": "Endpoint=sb://..."
    }
}

(EDIT: and ensured the file is copied always to the output folder)
And finally and most importantly I modified the trigger function to include the name of the Connection as follows:
    public static void ProcessQueueMessage([ServiceBusTrigger("[Your Queue Name]", Connection = "AzureWebJobsServiceBus")] string message, TextWriter log)
    {
        log.WriteLine(message);
    }

Even though the name of the Connection is the default I still seemed to have to define it in my function attributes. I tried the 'Values' approach too but I couldn't make that work. I then started receiving messages from the service bus.


text:
Q: Fair continuous election algorithm in a limited set of users I have an election method in mind, don't know if already exists but I think there must be.
It is used in a finite set of users and continuous.
Every round, somebody is picked randomly depending on the probability.
Initially everybody starts with equal probability.
But with every round, the selected user's re-election probability will decrease (but will still be available to be elected nonetheless).
If everything goes extremely fair and every user who has not been elected before is elected one after other, an then when everybody is elected once, the probabilities of them will be equal again.
Example: John, Max & Sarah are 3 users.
Scenario1:
Initially: [ P(J)=%33, P(M)=%33, P(S)=%33 ]

1st round, John is elected: [ P(J)=%10, P(M)=%45, P(S)=%45 ]

2nd round, Max is elected: [ P(J)=%5, P(M)=%5, P(S)=%90 ]

3rd round, Sarah is elected: [ P(J)=%33, P(M)=%33, P(S)=%33 ]

Scenario 2:
Initially: [ P(J)=%33, P(M)=%33, P(S)=%33 ]

1st round, John is elected: [ P(J)=%10, P(M)=%45, P(S)=%45 ]

2nd round, John is elected again: [ P(J)=%2, P(M)=%49, P(S)=%49 ]

3rd round, Sarah is elected: [ P(J)=%5, P(M)=%85, P(S)=%10 ]

4th round, Max is elected: [ P(J)=%10, P(M)=%45, P(S)=%45 ]

The probability values above are not based on a strict constant, just given for better understanding the question.
The main idea, needs to be accomplished is to give a user fair election chance and still protecting the re-election chance(but smaller as his election count gets bigger)
Thanks in advance

A: I have never heard of a scheme like this (although I am not a poli-sci or voting specialist). Your idea is very cool though and prima facie appears to be fair. From a proabilistic viewpoint, you may want to run some Monte Carlo simulations of your scheme with different methods of updating selection probabilities. This will allow you to verify that the long-run fraction of times each person is chosen is in fact equal, as well as the recurrence time for each person.
If you are of a theoretical bent, then you may find this paper interesting.

A: Very interesting! So your idea is that everyone who was elected should have a reduced election probability compared to those who weren't elected. So here is an equation that gives you election probabilities which satisfy these requirements.
Suppose we have $i=1,2,\ldots, I$ candidates. There is one election every $t=1,2,\ldots$, where exactly one candidate is chosen. Define the indicator $e_{it}$, which is equal to 1 if candidate $i$ got elected at $t$, otherwise it is 0. The election probability of candidate $i$ at $t$ is now
$$P_{it}=\frac{1+\sum_{x\neq i}\sum_{j=1}^{t-1} e_{xj}/(I-1)}{I+t-1}.$$
(The sum term in the numerator is the number of elections of all candidates but $i$. So if we sum this sum term over all candidates, then $\sum_i \sum_{x\neq i}\sum_{j=1}^{t-1} e_{xj}/(I-1)=t-1$, so the probabilities sum to 1.)
Intuitively, the more the other got elected, the higher is your probability to get elected.
Illustration: at $t=1$, we have $\sum_{x\neq i}\sum_{j=1}^{t-1} e_{xj}=0$, because nobody got elected yet, so $P_{i1}=1/I$, i.e., everybody has the same chance to get elected. At $t=1$, someone gets elected, so for the unelected at $t=2$ we have
$$P_{i2}=\frac{1+1/(I-1)}{I+1}$$
and for the elected candidate we have $P_{i2}=\frac{1}{I+1}$, i.e., less.
Two nice features about this equation. First, everybody who has the same number of elections at $t$ has the same probability to get elected (what can be fairer?). Second, as you required, whoever has more election wins at $t$ has a lower probability to get elected at $t$.
The question is of course whether this can be applied? After all, people vote, and elections are not just decided by random draws. Do you plan to do this?


text:
Q: how to make progress bar go back on click with go back button I'd like to click go back button and make the progress bar go back a step
function progress(){
var totalQuestions = 7;
var currentQuestion = 0;
var $progressbar = $("#progressbar");

$(".option").on("click", function(){
  if (currentQuestion >= totalQuestions){ return; }
  currentQuestion++;
  $progressbar.css("width", Math.round(100 * currentQuestion / totalQuestions) + "%");
});

}

Go back button is taking me to previous questions but is not changing progress bar

A: If you add an extra button on the page with an id of, for example, backButton you can do this:
$(".backButton").on("click", function(){
  currentQuestion--;
  $progressbar.css("width", Math.round(100 * currentQuestion / totalQuestions) + "%");
});

So you add an extra onClickListener to a different button which controls the same progressbar as you can put it in the exact same function and you declared the variables globally in the function.

A: i guess this could help with a button with class of backward:
function progress(){
var totalQuestions = 7;
var currentQuestion = 0;
var FinalCurrentQuestion = 0;
var $progressbar = $("#progressbar");

$(".option").on("click", function(){
  if (currentQuestion >= totalQuestions){ return; }
  currentQuestion++;
  FinalCurrentQuestion = currentQuestion;
  $progressbar.css("width", Math.round(100 * currentQuestion / totalQuestions) + "%");
});

$(".backward").on("click", function(){
  if (FinalCurrentQuestion == currentQuestion) {
  currentQuestion--;
  $progressbar.css("width", Math.round(100 * currentQuestion / totalQuestions) + "%");
  }
});

}


text:
Q: How to avoid getting error "duplicate entry '1' for key primary" when inserting one table into another? INSERT INTO tableA (SELECT * FROM tableB);

creates an error

"Duplicate entry '1' for key Primary".

tableA has field "Lid" which is primary, auto-increment and causing the error.
tableB has a set of records with identical fields to tableA. Field Lid is numbered 1-40.
I need ALL records from tableB to be appended to tableA every time a new user logs in to my system. Once copied to TableA, the records are updated with that users UserID. When tableB is appended to tableA, field tableA.Lid should autoincrement, not take the duplicate value from tableB.
The following works but I want to avoid specifying field names in code:
INSERT INTO tableA (field2, field3,...) SELECT field2, field3, ... FROM tableB

I skip field1 which is the "Lid" primary auto-increment field.
If I set tableB.Lid to null would this work?
I want to use INSERT INTO tableA (SELECT * FROM tableB) as this avoids specifying field names in code.

A: In tableB i changed field "Lid" to just be a regular INT field, not indexed, not primary, not auto-increment, default to Null. I am now able to "INSERT INTO tableA SELECT * FROM tableB" and all records in tableA are auto-incrementing correctly. As mentioned I preferred not to use field names in code so wanted to keep solution "generic".


text:
Q: Neo4j Client And Not Query How do I create this query using Neo4jClient.
MATCH (keanu:Person)-[:KNOWS*2]->(fof)
WHERE keanu.name = "Keanu Reeves"
AND NOT((keanu)-[:KNOWS]-(fof))
RETURN DISTINCT fof.name;

A: Assuming you have a class like:
public class Person
{
    [JsonProperty("name")]
    public string Name { get; set; }
}

Your query would look like this:
client.Cypher
    .Match("(keanu:Person)-[:KNOWS*2]->(fof)")
    .Where((Person keanu) => keanu.Name == "Keanu Reeves")
    .AndWhere("NOT ((keanu-[:KNOWS]-(fof)))")
    .ReturnDistinct(fof => fof.As<Person>().Name);

I'm answering mainly as I think the docs do lack a little around using NOT, but Stefan is right - the docs do contain most of the info you need - and you do need to show what you've tried, otherwise we're unsure as to what bit you're struggling with.


text:
Q: How to clean HornetQ messaging journal before/after performing a test? There's an Arquillian integration test using JMS HornetQ with persisted messages. Some test leave the messaging journal filled with unhandled messages that break other tests expecting no data.
Is there a way of telling JMS to clean its messaging journal before or after executing a test?

A: This does not exist in the JMS API itself, but there's a method 'removeMessages(filter)' in the HornetQ QueueControl management object. This method can be found in the JMX Bean for the Queue, but I wouldn't know how to get that in Arquillian.
Luckily, you can invoke management operations via the 'hornetq.management' queue. See http://docs.jboss.org/hornetq/2.2.5.Final/user-manual/en/html/management.html. In practice, the following should work:
     Queue managementQueue = HornetQJMSClient.createQueue("hornetq.management");
     QueueRequestor requestor = new QueueRequestor(session, managementQueue);
     Message m = session.createMessage();
     JMSManagementHelper.putOperationInvocation(m,
                                                "jms.queue.exampleQueue",
                                                "removeMessages","*");
     Message reply = requestor.request(m);
     boolean success = JMSManagementHelper.hasOperationSucceeded(reply);

A: If you're restarting the server, you could remove the paging and data folders (while keeping the bindings).


text:
Q: generate url after reload page and checkboxes jquery I generate a url after checked some checkboxes and I can go to the new url after click on a button,when the page load the options that was clicked are cheked until here all is fine, but what happend if I check in new optionf, the new url is wrong.
my checkboxes are like below:
<input type="checkbox" name="gender" value="women" data-facet="gender">
<input type="checkbox" name="gender" value="men" data-facet="gender">
<input type="checkbox"name="occasion" value="beach" data-facet="Occasion">
<input type="checkbox"name="occasion" value="street" data-facet="Occasion">
<input type="checkbox"name="color" value="blue" data-facet="color">
<input type="checkbox"name="color" value="red" data-facet="color">

And this is my script to generate the url:
$("a#filterLink").on("click", function(){
    var arr = [];
    $(":checkbox").each(function(){
        if($(this).is(":checked")){
            arr.push($(this).attr('name')+ '=' +$(this).val())
        }
    });
    var values = arr.join("&");
    var str = window.location.pathname +"?&" + values;

});

The button that generate the url is this:
<a id="filterLink" class="button ">
        Apply    </a>

After reload the page if some of the options was checked (gender men)and I checked the option like color redthe new url generated is like below:
/myproducts/?&Men=Men&Men=Men&gender=Men&Men=Men&Men=Men&gender=Men&color=red
How can I reset or get the new url without the problem of checked options?


text:
Q: AsUnit verses FlexUnit – which is "better"? I'm learning ActionScript/Flex at the moment, and it's come time for me to start unit testing.  My reading shows that there are two main frameworks out there: FlexUnit and AsUnit.
Is there any reason to learn one over the other? Is one, in some way, "better"?

A: I think it depends on the kind of ActionScript development you're doing. AsUnit has a wider set a supported versions.
FlexUnit looks as though it has a better backing through Adobe. If you're focusing on Flex development (or strictly AS3), I'd probably go with FlexUnit.

A: There is also fluint, which was created in order to address issues that developers were running into using FlexUnit.
Because of new FlexUnit tooling support in the upcoming FlashBuilder 4 release from Adobe, the fluint project and the FlexUnit project have merged to create a new unit testing suite now dubbed FlexUnit 4.0.  The FlashBuilder IDE will support FlexUnit 4.0 at the tool-level.  This new tooling support, coupled with some of the great new features of FlexUnit 4.0, make the new FlexUnit the clear choice for unit testing in ActionScript 3 and Flex code.

A: As a followup to this question, I have been using FlexUnit for the last bunch of months, and it (along with Drew Bourn's awesome hamcrest-as3) has been making me very happy.


text:
Q: Detect coded targets of concentric ring in image recognitionimage I have some images with coded targets of concentric ring (see picture below for an example). The targets are used in the drone survey.
Are there any software/algorithm to automatically detect it? I have googled, but only found it.

A: You should give a try to the custom detector of https://picterra.ch/.
Tutorial is available here https://picterra.ch/2019/02/21/build-your-own-ai-detector/
Hope that this helps :)
Disclosure: I work there, do not hesitate to let me know if you have any questions or issues


text:
Q: Dojo equivalent of $(document).scrollTop? As you know in jQuery $(document).scrollTop() is for checking the scroll position of the window. Can the same function be used in dojo? I used
dojo.query('html')[0].scrollTop()

But in webkit there is bug - it always returns 0

A: With dojo you have to do:
dojo.query('body')[0].scrollTop

and beware that scrollTop is a property not a function, or you will get the error:
TypeError: Property 'scrollTop' of object #<HTMLBodyElement> is not a function

UPDATE
The above code works fine with Dojo 1.8, Chromium 18.0, Rekonq 0.8 and Firefox 17.0 on Ubuntu 11.10.

A: If there is still someone interested by this in 2017.
you have to do:
dojo.query('body')[0].scrollTop = 0;

tested on IE11, Firefox 51.0.1 and Chrome 56.0.xx

A: Please try query("html")[0].scrollTop || query("body")[0].scrollTop.


text:
Q: Spotify: Getting metadata without a user logging in I would like to be able to get song metadata (song title, artist name, album title) from Spotify's Restful Web API. I've looked through the Spotify Web API Documentation and played around with their console, but I almost seems like a user needs to login to be able to get the OAuth token or to refresh the token. Is it possible to get song metadata from the Spotify Web API without the user logging in?

A: This is possible with the Client Credentials flow.


text:
Q: Connect Python to Teradata Connection Error I'm using sqlalchemy trying to connect to Teradata via ODBC as I need to be able to read/write to Teradata.
from sqlalchemy import create_engine
import sqlalchemy_teradata

user = 'user'
pasw='pasw'
host = 'host'

# connect
td_engine = create_engine("teradata://"+user+":"+pasw+"@"+host+"/?authentication=ODBC?driver=Teradata")

#execute sql
sql = "select * from table"
result = td_engine.execute(sql)

However I get the following error.
(teradata.api.DatabaseError) (0, '[28000] [Teradata][ODBC Teradata Driver] User Specified Mechanism for Logon is Not Available')
(Background on this error at: http://sqlalche.me/e/4xp6)
The link provided is not very informative unless I'm missing something.  The error is from Teradata but I'm not sure what it actually means.  It looks like it saying that I can't use ODBC? Any suggestions or alternatives?


text:
Q: Nested objects using WTForms (or FormEncode)? What's the best practice for creating a form with nested objects/fields?
I have a Team object, with a field "name", and a team can consist of 1 to many (lets say 12) members, each of whom has a name, an e-mail, age, t-shirt size etc.
I'd like to validate all of them in one go. So that I would post all the team members as an array.. the field names would be something like
members[0].name
members[1].name
or whatever the form validator would be able to parse.

A: Create one Form for the Team and one Form for a Member. In the Team-form, create a FieldList of FormFields:
class Member(Form):
    name = StringField("Name")
    ...

class Team(Form):
    ...
    members = FieldList(FormField(Member))


text:
Q: Query for datediff between rows where value was unchanged, grouped by the value I am looking to query an invoices table which also keeps track of which "program" customers were on at the time of their purchases (not the best way of storing that but it is what it is and I'm left to deal with it).
I would like to see how long each customer was on each program for.
For example, here's a history of purchases made by a couple of customers. We can see that the customers were on different programs at different dates. Note that program IDs are not actually sequential (maybe they start on a program with a higher ID than the next program).
invoices table:

cust_id, prog_id, datetime
1,       1,       2020-01-01      < cust 1 first seen on program 1
2,       1,       2020-01-05      < cust 2 first seen on program 1
1,       1,       2020-02-07
1,       2,       2020-02-08      < cust 1 seen on program 2 after 38 days
2,       1,       2020-02-10
2,       2,       2020-02-15      < cust 2 seen on program 2 after 41 days
1,       2,       2020-02-15
2,       2,       2020-02-15
1,       2,       2020-02-22
1,       3,       2020-02-28      < cust 1 seen on program 3 after 20 days
2,       2,       2020-03-05
2,       2,       2020-03-07
2,       3,       2020-03-15      < cust 2 seen on program 3 after 29 days
2,       3,       2020-03-17

I would like to see something like this (done in my head so hopefully the math checks out):
cust_id, prg_id, days_on_prog
1,       1,      38
1,       2,      20
2,       1,      41
2,       2,      29
2,       3,      2

Note that customer 1 was not seen on program 3 more than once, so we don't have a days_on_prog for them on program 3.
Can you help me build such a query?

A: It looks like aggregation should do the job:
select
    cust_id,
    prg_id,
    datediff(max(datetime), min(datetime)) days_on_prog
from invoices
having max(datetime) <> min(datetime)
group by cust_id, prg_id
order by cust_id, prg_id


text:
Q: OpenGL/GLUT keyboard managed with bool*: all values appear to be set to ints at second initialisation. Any ideas? Making a game with OpenGL/GLUT and C++.
I've heard the easiest way to manage keyboard stuff in GLUT is to use an array of bools.
So basically, here's what I have:
bool* keys = new bool[256];

...
void keyDown(unsigned char ch, int x, int y)
{
    keys[ch] = true;
}

void keyUp(unsigned char ch, int x, int y)
{
    keys[ch] = false;
}

Then if I want to know the state of a key, I just return keys[key].
I have a similar setup for the special keys. Now, in my game when you die, it resets all the values that need to be reset and starts the game again. Until just now, that included
keys = new bool[256];

and a similar declaration for the special keys array. What makes no sense to me is that occasionally, this supposed resetting of the arrays would cause some or all of the values in keys to become two- or three-digit integers (therefore always evaluating true and making the player character move uncontrollably until one or more of the keys that were apparently down were depressed). I have a suspicion that this happened because at time of endgame one of the keys was pressed down, thereby confusing C++ when it tried to make the whole array false and found that one thing was stuck true.
Man, that's confusing. The problem has been solved by eliminating all the extra initialisations of keys, as far as I can see. But I don't get it. Anyone got any ideas on how I managed to turn some bools into ints?

A: This statement
keys = new bool[256];

Allocates memory. It does not initialize that memory to any particular value. To do that, you could do a memset(keys, 0, sizeof(bool) * 256) to zero.
However, you shouldn't allocate memory (which is what new does) to reinitialize an array. You should actually reinitialize it, using memset or whatever feature you used to initialize it with "false" values.
Lastly, why are you allocating this array with new to begin with? Just make it a global array: bool keys[256]. Initialize it (with memset) before you use it, and everything will be fine.
I would have suggested a std::vector<bool>, but sadly, those are not usable. You could use a std::vector<char> though, with 0 meaning false. Or a std::bitset with 256 bits. All of these contain their allocations internally (thus being safe), and have ways to clear their memory to some value.

making a game with OpenGL/GLUT and C++.

As an aside, I wouldn't advise that. GLUT isn't a tool designed for the kinds of timings that most games need. GLFW allows you to control the main loop, rather than using callbacks, so it is a more appropriate tool for a game.

A: Because of CPU granularity you can only access things as a byte therefore bools always resolve to some kind of unsigned char type which are 1 byte in size. This way you can get from 0-255 range in values. What happens is that any non zero value is true and 0 is false. We can't implement bool as a single bit (except in C++ STL vector etc... where they are converted to bitfields) because of that granularity unless you decide to make an array and index bits in particular entries.

A: Since the size is small, data type (bool) is small, and array size is deterministic; I would have allocated it in stack (at class level, or global level - wherever keys are declared).
class GlutWrapper
{
    bool Keys[256];
...
};

And having a function, that would ResetKeys:
void GlutWrapper::ResetKeys()
{
   memset(Keys, 0, sizeof(Keys));
}


text:
Q: Difference between Scala Option's isDefined and nonEmpty method In Scala Option, what is the difference between its isDefined and nonEmpty method? Is there any performance difference between the two?

A: From Scala 2.13.x codebase, it's:
def isDefined: Boolean = !isEmpty
...
final def nonEmpty = isDefined

So, logically, no difference between the two.

A: They are literally the same. I believe nonEmpty is provided mostly for consistency with the Collection API.

A: Looking at the source, the definition of nonEmpty is:

final def nonEmpty = isDefined

A: You might look at it the other way around.
If Option didn't provide nonEmpty, it would be provided through the conversion to an Iterable, which invokes toList.
Do you want to turn your Option into a List just to check that property?  Of course not.
So the issue is not whether nonEmpty is more efficient vis-a-vis isDefined, but vis-a-vis the conversion.
If it relied on the conversion, it would wind up doing lengthCompare, which creates an iterator as overhead.
So the answer is that you may use whichever method you prefer.


text:
Q: Multithreading - Killing a Thread and all its child processes I am working on an analytics app. in Java.At the top i have a GUI which has START and STOP Buttons.On Clicking Start i create a Thread inside whose RUN method i call an API method which internally creates a Thread.i.e.
On Clicking "START"----->a Thread is Spawned---->in this thread's RUN method i use an API cal which creates a thread Internally...
Now,what i want is that when i click the STOP GUI button,the internal thread created by the API call should also die..
How can i achieve that??
Thanks

A: You'll have to implement some logic to the thread classes. First, they need some "kill switches" - you can't (shouldn't!!) stop them from outside. We usually define and set a flag on the thread instance so that it knows, when it has to terminate.
Then, we don't have a thread "hierarchy". A thread instances will need to its own list of child threads and, if it (the parent) receives the stop signal, it will have to send the same signal to its children.
public abstract class MyThread extends Thread {

   private List<MyThread> children = new ArrayList<MyThread>();
   private boolean stopNow = false;  // <- this is the stop flag

   public void stopNow() {
     for (MyThread thread:children) {
       thread.stopNow();
     }
     stopNow = true;
   }
 }

(This will not make a thread stop actually, we'll have to "monitor" the stopNow flag in the run method).


text:
Q: Custom image slider So I am trying to create my own basic image slider using javascript but it just won't work. I want it to rotate between my 3 images. Here is ym javascript:
var count = 1;

setInterval(function animate() {

var slides = document.getElementsByClassName("slide");

for(var i=1; i <slides.length+1; i++) {
    if(i == count) {
        slides[i-1].width = "170px";
    } else {
        slides[i-1].width = "0px"
    }
}

if(count == 3) {
    count = 1;
} else {
    count++;
}

}, 1000);

And here is my html

All I want it to do is change the currently showing slides height to 170px and the others to 0px. But it stays on the first slide no matter what.

A: You should use slides[i-1].style.width = "0px" not slides[i-1].width = "0px"
jsfiddle: DEMO

A: It looks like this example is a little oversimplified, since you don't have image elements in it.  I am going to assume your HTML looks like this:

The problem then is that the size of the container div will not affect the size of its children, and they will just spill outside the div.  Here's a good blog post on how this works.  You can see this easily if you take a look at the DOM in a tool like Firebug.
One easy way of fixing this is to add the CSS property "overflow: hidden" to the .slide class.
.slide {
  overflow: hidden;
}

That should cause anything outside the div to disappear!

A:

    <meta charset="utf-8">
    <title>Banner Rotator Demo - Jssor Slider, Slideshow with Javascript Source Code</title>

        Image Slider


text:
Q: Pullback for Atiyah classes? In his paper "Complex analytic connections in fibre bundles" Atiyah defines his famous Atiyah class $\operatorname{at}(E) \in H^1(X,\operatorname{End}(E) \otimes \Omega^1_X)$ for a vector bundle $E$ on a complex manifold $X$ and he shows that the Chern classes of $E$ can be derived from $\operatorname{at}(E)$. But he also gives a definition for the Atiyah class of an arbitrary coherent sheaf $\mathcal F$ on $X$ which is an element $\operatorname{at}(\mathcal F) \in \operatorname{Ext}_X^1(\mathcal F, \mathcal F \otimes \Omega^1_X )$.
Now, for Chern classes it is well known that they behave functorial with respect to maps $f \colon X \to Y$, i.e.
$$
c_k(f^* E ) = f^* c_k(E)
$$
for any vector bundle $E$ over $Y$. The comparison of the Atiyah-class with Chern classes suggests that such functoriality should also hold for the Atiyah-class of a vector bundle.
But how is it with the Atiyah-class of a coherent sheaf? Say $f \colon X \to Y$ is a map of schemes/analytic spaces and $\mathcal F$ is a coherent sheaf on $Y$.
Question 1: How can we even define the pullback
$$
f^* \colon \operatorname{Ext}^1_Y(\mathcal F, \mathcal F \otimes \Omega^1_Y) \to
\operatorname{Ext}^1_X(f^* \mathcal F, f^* \mathcal F \otimes \Omega^1_X)?
$$
Question 2: With an appropriate definition of the above, do we indeed get
$$
\operatorname{at}(f^*\mathcal F) = f^*(\operatorname{at}(\mathcal F ))?
$$
Edit: I see that Question 1 has a straightforward answer in the category of sheaves of Abelian groups. There, the pullback functor $f^{-1}$ is exact. A short exact sequence
$$
0 \to \mathcal F \otimes \Omega^1_Y \to E \to \mathcal F \to 0
$$
is pulled back to a short exact sequence of sheaves of Abelian groups on $X$. Using Yoneda's definition of Ext, we get a notion of pullback. However, in the category of (quasi-)coherent sheaves, the pullback functor
$$
f^* \mathcal F := f^{-1} \mathcal F \otimes_{f^{-1} \mathcal O_Y} \mathcal O_X
$$
is not an exact functor anymore. So what can we do to remedy for that?