text:
Q: TypeORM - Cannot read property 'retryAttempts' of undefined on Docker I've had a problem with starting nestJS app in docker container, after run nest start i've got this error, and I have no idea what to fix this:
worker | [31m[Nest] 29   - [39m07/07/2022, 5:25:37 PM   [38;5;3m[ExceptionHandler] [39m[31mCannot read property 'retryAttempts' of undefined[39m[38;5;3m +11ms[39m
worker | TypeError: Cannot read property 'retryAttempts' of undefined
worker |     at Function.<anonymous> (/dist/node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:195:63)

can someone help me with this error?
package.json
"@nestjs/typeorm": "^8.1.4",
"typeorm": "^0.3.6",

  "engines": {
    "node": "16.11.1"
  }

Dockerfile:
FROM node:16.3.0-alpine as builder

WORKDIR /dist

COPY package*.json ./
RUN npm install --force

COPY . .
RUN  npm run build

EXPOSE 8080

CMD [ "npm", "run", "dev"]

locally i can't reproduce this error


text: Q: Pagination Django Rest Framework POST I'm trying to send a POST request through an endpoint with generic APIVIEW class. The response rendered through this post request needs to be paginated. The limit and offset parameters for pagination are passed in the same POST request body. How can same be implemented using the LimitOffsetPagination. I have seen seen various examples of pagination in GET requests but no luck on POST request.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is tmp\kotlin-classes folder empty and path not found during compile stage of kotlin module build in Android Studio? The module (not the main app) won't build because it fails this step:
:compileDebugKotlin
ERROR MESSAGES:
e: java.lang.IllegalStateException: Backend Internal error: Exception during code generation
Cause: [Path-deleted-for-SO-post]\message-classes\build\tmp\kotlin-classes\debug\com[Path-deleted-for-SO-post]\ble\aux\AlarmResponseTypes.class (The system cannot find the path specified)
File being compiled at position: file://[Path-deleted-for-SO-post]/message-classes/src/main/java/com/[Path-deleted-for-SO-post]/ble/_aux/AlarmResponseTypes.kt

Does it have anything to do with the "_aux" in src path vs "aux" in build path?
When I look in tmp\kotlin-classes folder, it's empty. The rest of the parent path back to C drive that I deleted for this post is correct.  Even when I try to make the folder path, it gets deleted as soon as build runs of course.
Things I've tried many times:
Clean - rebuild - restart - etc.
Invalidate - restart - etc.
Updated kotlin plugin, Android Studio, Gradle versions, etc.
Only building this module and not entire app.
Always comes back to same error.
AND, it did build properly (although I did not run or build into apk file after that) before updating kotlin plugin -- but not sure that had anything to do with it.
Versions, etc.:
AS - 3.1.3
kotlin_version = '1.2.50'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Full build.gradle:
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        minSdkVersion 23
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
 "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    // project configuration
    sourceSets {
        androidTest.java.srcDirs += 'src/androidTest/kotlin'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

A: SOLVED: Windows does not allow folder name of "aux" (this is a legacy reserved word)...
Therefore, code modules that worked on Macs failed to build when incorporated into a different project on the Windows machine I was using.
As soon as a folder is placed on the file system in Windows via unzip, etc., with the name "aux" then Windows automatically changes the folder name to "_aux" w/o telling the user.


text:
Q: How can I show all tags from product table in laravel, when all tags are in products table? This is an eCommerce project, and I stored product tags in the product table.
In the database, all tags are stored separated by commas. But how can I show all tags in view using groupBy ??

A: If the database was normalized, the tags would be in their own table. But since you have them like this, I assume you're getting the products with something like:
$products = Product::get();

If so, you can still get all different tags by using some collection methods.
$tags_en = $products->map(fn($product) => explode(',', $product->product_tag_en))
                    ->flatten()
                    ->unique()   // avoid repeating tags
                    ->sort()     // optional
                    ->values();

$tags_bn = $products->map(fn($product) => explode(',', $product->product_tag_bn))
                    ->flatten()
                    ->unique()   // avoid repeating tags
                    ->sort()     // optional
                    ->values();

A: It's not really practical to store your tags this way if you want to perform any form of meaningful query on them.
Rather, you should look to moving your tags to a separate table, either as one to many relationship (a product has many tags), or a many to many relationship, where you share tags between products. This will allow you to perform all sorts of aggregate queries like the grouping you wanted.
One To Many

tags

id

product_id

name

Many to Many

tags

id

name

product_tag

product_id

tag_id

The answer by @IGP is also equally valid, depending on where you want to aggregate to occur, either in the PHP client, or the actual database query.


text:
Q: When is system scheduled for reboot? Where can I find information about if there is an reboot scheduled and in that case: when, why and by who?

I got this in my terminal:
Broadcast message from root@my-server (Tue 2017-11-07 09:00:00 CET):

The system is going down for reboot at Wed 2017-11-08 02:00:00 CET!

So in a couple of hours the system will be rebooted, that's good. But after working for a while and the message is scrolled out of visibility or if the terminal is closed:
How can I get hold of the reboot time?
If I again login to the server I only get the message:
*** System restart required ***

There is no information about the upcoming reboot. I have tried to see if there is any shutdown processes running, but could not find any.
I know I could produce a similar message by issuing a command like this:
sudo shutdown -r 02:00

So, how do I find information about any upcoming reboots?

A: As started with sudo shutdown -r 02:00 it's not a file / setting / system variable / crontab entry. The shutdown is a process and if it's still pending, you should see it.
$ ps -ef | grep shutdown
root      3155  2941  0 12:04 pts/4    00:00:00 sudo shutdown -r 02:00
root      3156  3155  0 12:04 pts/4    00:00:00 shutdown -r 02:00
esa       3158  2937  0 12:04 pts/3    00:00:00 grep shutdown

If it's cancelled with external command sudo shutdown -c or by pressing ^C in pts/4, the process will show a message Shutdown cancelled. and exit. So if it's not there:

*

*someone has cancelled the shutdown after the message.

*the message was produced with shutdown -k (Don't really shutdown; only send the warning messages to everybody. In some versions this also prevents new logins.)

*you are running ps with a user account that doesn't see processes of other users.

A: On my Ubuntu machines, the 'reboot required' message upon login comes from the file at /var/run/reboot-required. This file is removed during the update/reboot process.
The reboot time is set with Unattended-Upgrade::Automatic-Reboot-Time in the /etc/apt/apt.conf.d/50unattended-upgrades file.
As Esa stated, the broadcast message was most likely produced by something else executing shutdown -k, which only prints the message and exits. I also observe the broadcast messages, but afterwards, sudo ps faux shows me no shutdown processes that are running.
It's worth noting that even though no shutdown process stays running, something does seem to keep track of when the original shutdown time was scheduled. Even when I change the value for reboot time, subsequent broadcast messages still show me the originally configured time.

A: On an Ubuntu 18.04 machine shutdown is managed by systemd. On my machine I have enabled automatic reboots via unattended upgrades:
$ grep Automatic-Reboot /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";

The scheduled automatic reboot time is stored in /run/systemd/shutdown/scheduled.
$ cat /run/systemd/shutdown/scheduled
USEC=1563976800000000
WARN_WALL=1
MODE=reboot

You can convert this to a human readable time using the following command:
$ date -d "@$( awk -F '=' '/USEC/{ $2=substr($2,1,10); print $2 }' /run/systemd/shutdown/scheduled )"
Thu Jul 25 02:00:00 NZST 2019


text:
Q: Changing elements positions with sql database I have element with position property. So that you can select them with ORDER BY pos
item | pos
aaa  | 1
bbb  | 2
ccc  | 3

and change them to
item | pos
aaa  | 2
bbb  | 3
ccc  | 1

What is the common way to work with changing positioning?
I am using PHP+SQLite, but I think it doesn't matter.
All I can think about is changing them step by step, swapping every two adjusted things. But it will be messy if they are not adjust, for example, changing element with position x to position 1.
What is the common practices for this? Or what are the keywords for googling it?

A: Just found http://jqueryui.com/sortable/ . It can be used to rearrange and then bulk update database values. Sounds like a solution, I will try it.
It has nice serialize( options ) for passing a new order to a server script.


text:
Q: Is it possible to force rmarkdown use "html" instead of "html4"? It is hardcoded in pandoc.R by some reasons (unknown for me). I tried to specify html5 in YAML section:
---
title: "My title"
date: "`r Sys.time()`"
output:
  html_document:
    fig_width: 8
    fig_height: 6
    toc: true
    theme: null
    mathjax: null
    highlight: "pygments"
    md_extensions: -autolink_bare_uris
    self_contained: FALSE
    template: journal.html5
    pandoc_args: ["--to=html"]
---

but when I render it (by rmarkdown::render("file.rmd"), I don't use RStudio), console output looks like:
/usr/bin/pandoc +RTS -K512m -RTS table_to_graph.utf8.md --to html4 --from
markdown+tex_math_single_backslash-autolink_bare_uris+smart --output file.html
--email-obfuscation none --to=html --standalone --section-divs --table-of-contents
--toc-depth 3 --template journal.html5
--highlight-style pygments --lua-filter

You can see both arguments. The goal is to have just --to html. When I put -t html in YAML, I'm getting an error:
Unknown writer:  html
Error: pandoc document conversion failed with error 1

In pandoc manual there are variants --to=html and -t html.
So for now I have to manually patch the pandoc.R file every rmarkdown update (quite often). If anybody knows how to force html(5) via YAML please answer.
Update: pandoc info
$ pandoc -v
pandoc 2.7.3
Compiled with pandoc-types 1.17.5.4, texmath 0.11.2.2, skylighting 0.8.1
Default user data directory: /home/***/.local/share/pandoc or /home/***/.pandoc
Copyright (C) 2006-2019 John MacFarlane
Web:  http://pandoc.org
This is free software; see the source for copying conditions.
There is no warranty, not even for merchantability or fitness
for a particular purpose.
$ eix -I pandoc
[I] app-text/pandoc-bin [1]
     Доступные версии:      2.6^m 2.7.3^p
     Установленные версии:  2.7.3^p(10:40:08 13.11.2019)
     Домашняя страница:     https://pandoc.org https://github.com/jgm/pandoc
     Описание:              An universal document converter

[1] "local_overlay" /usr/local/portage


text:
Q: Materialize tabs not scrolling I am using Materialize v0.98.0 (local copy) and have the following code. I've message around with CSS settings in Chrome console, but can't seem to figure it out.
<link type="text/css" rel="stylesheet" href="../_css/materialize.css"  media="screen,projection,print"/>

#roll_tabs {
    webkit-box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14),0 3px 1px -2px rgba(0,0,0,0.12),0 1px 5px 0 rgba(0,0,0,0.2);
    box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14), 0 3px 1px -2px rgba(0,0,0,0.12), 0 1px 5px 0 rgba(0,0,0,0.2);
}

EX-33-04-01

EX-33-05

EX-33-06

EX-33-07

FS-040

EX-33-01

CL-400

EX-34-01

FS-PA-01-9

FS-PA-02-17

EX-33-02

FS-SOL-01

Ex-33-03

EX-34-02

EX-33-04-02

$(document).ready(function() {
    $('.tabs').tabs({
        onShow: function(event, ui) {
        formID = $('ul.tabs li a.active').html();
        }
    });
});

A: On using swipeable : true you can achieve scrolling(to be more precise swiping not scrolling). You've used a class of col, this doesn't work like that, you need to give the size of the grid too.
CodePen Demo of Tabs Swiping
And Use the newest versions of materialize cdnjs/minified scripts -

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">


text:
Q: Finding the number of days between two dates? How can I calculate the number of days between two dates in Google Sheets? I tried this: =DAYS(11/11/2018, 11/08/2018) and it gives 0, which is definitely not right. I also couldn't seem to get it to work with =DATEDIF() or =MINUS()...

A: For all those functions, you need to put dates in quotes; otherwise they are treated like (very small) fractions, giving the odd results you found.
So for your original function, structure it like this instead: =DAYS("11/11/2018", "11/08/2018") (which, correctly, returns the number 3).


text:
Q: Overwriting a field's method in Python I have a custom class which I instantiate twice in a second class:
[EDIT: The old code wasn't really capturing what my issue is, I'm rewriting to make it clearer. Foo is going to process network events (and I need multiple connections, hence why Bar will have multiple Foo fields and can't just inherit) by using a callback function. In the Bar class, i want to overwrite the callback to do something different. Rewriting callb in Foo won't work, because I do inherit from it in other instances]
class Foo(object):
    def __init__(self, x):
        self._x = x
        #When an event happens, call callb()
        self.on_certain_event(callback=callb)

    def callb(self):
        print self._x

    def run(self):
        waitForEventsInfinitely() #

class Bar(object):
    def __init__(self):
        self._foo = Foo(5)
        #OVERWRITE THE EXISTING CALLBACK METHOD IN THE Foo CLASS!
        self._foo.callb = self.callb

    def callb(self):
        print self._x * 10

    def run(self):
        waitForEventsInfinitely() # Not going to actually write t

f = Foo(2)
f.run()
b = Bar()
b.run()

[When run() is called in a Foo, it works correctly. However, I cannot overwrite the callb method of Foo from Bar - the self._x which should be referred to by Foo is trying to call from Bar]
However, when running the code, I receive the error "Bar has no attribute '_x'" rather than my expected value of 50. Obviously, the self in Bar's test is still referring to Bar, not the Foo which is actually calling the method. I would have expected it to be the internal Foo self._foo field in Bar.
I suspect my problem has something to do with name mangling, but I haven't been able to find a descriptive source when I have fields on self having their methods overwritten. Most examples seem to be when I'm inheriting from a different class.

A: it seems that in Bar.test you want :
print self._foo._x * 10

A: Ok short lesson on how classes in Python work: Any function stored on a class object (a "method") is automatically fetched by a descriptor (which describes how to getl attributes from objects) that binds the methods to the class or instance you used to get it.
For example:
Foo.test

is a unbound method of class Foo: This is a object created by the descriptor on Foo that knows it was fetched from a class object
Foo().test

is a bound method of a instance of class Foo: This method stores the instance of Foo used to fetch the function. This instance is automatically passed as the first argument when you call the resulting object and that's why you write self as the first parameter when you define a method.
So, what you are trying to do is this:

*

*Get the raw function test from class Bar (not through a descriptor)

*Bind this function to a instance of Foo

*Store this function on the foo instance

So, this is how you do it:
import types

class Bar(object):
    def __init__(self):
        self._foo = Foo(5)

        raw_function = Bar.test_Bar.__func__                        # 1)
        bound_to_foo = types.MethodType(raw_function, self._foo)    # 2)
        self._foo.test = bound_to_foo                               # 3)

    def test(self):
        print self._x * 10

See this question for more details on descriptors.

A: If you look at your code, when you call b.test, you are calling the method directly on an instance of Bar; no instance of Foo is mentioned at all. b doesn't have a member named _x, hence the error. To get the behaviour you expect, you must call b._foo.test. This will give you your expected result of 50.
If you want to be able to call b.test directly, change self._x to self._foo._x. This way you don't have to change any methods of _foo. I'm not really sure why you would assign different methods to an object when you could use inheritance anyway.


text:
Q: How can I group the data in an array or JSON? I have a NODE script where I download some information that I need to "reparse", first it downloads a .txt, then I convert it to a CSV then to JSON and then I convert it to an XML, I do it this way since going from .txt to XML is impossible.
The problem is the JSON returns me an object similar to this:
  [{
    "id": "3435",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "3436",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "343534",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "343345",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "3433435",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    }]

I would like to group them by "product" like this
{
"root" : {
    "item": {
        "id": 3435,
        "nameProducto" : "Nombre del producto",
        "PriceProducto" : "19.000",
    },
    "item": {
        "id": 3436,
        "nameProducto" : "Nombre del producto",
        "PriceProducto" : "19.000",
    },
    "item": {
        "id": 34334,
        "nameProducto" : "Nombre del producto",
        "PriceProducto" : "19.000",
    },
    "item": {
        "id": 343345,
        "nameProducto" : "Nombre del producto",
        "PriceProducto" : "19.000",
    },
    "item": {
        "id": 3433455,
        "nameProducto" : "Nombre del producto",
        "PriceProducto" : "19.000",
    }

}}

If you have a solution for this I would be very grateful!

A: As mentioned in the comments, it's not possible in json/objects to generate the 'root' object with multiple keys named 'item'.
Below is an approach that could work using the index of the array of products in the keys of the object:

const inputJson =  [{
    "id": "3435",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "3436",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "343534",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "343345",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    },
    {
    "id": "3433435",
    "nameProducto" : "Nombre del producto",
    "PriceProducto" : "19.000"
    }]

 let outputJson = { "root" : {}}

 inputJson.forEach((item,index) => {
  outputJson.root[`item_${index}`] ={
    item
  }

})

console.log(outputJson)


text:
Q: How does CosmosDB change feed behave in the presence of multi-master replication? I have CosmosDB set up in multi-master mode replicated to several sites, and am utilizing the change feed API to read updates from the database. Currently I am reading from a single location, but soon I plan to read from multiple for failover redundancy. What isn't clear is how the change feed API is supposed to behave in this scenario. If the timestamp that change feed uses to poll for changes is copied directly from the originating site, I can imagine some timing situations where change feed would not see the changes since the Continuation Token is already in the future. I wouldn't expect any problems if the timestamp is updated on the replicated site. While I can test this myself to verify, I would prefer to know what is explicitly supported by the CosmosDB team.

A: All changes that happen in all regions are replicated to each region's Change Feed, so you should be able to read the Change Feed from any of the regions and obtain all the changes without issues.


text:
Q: Symfony 2 Bizarre behavior in the controller Symfony 2.3
I have two fields on the form with dates: the date_from and date_to.
The controller after submit performs its own validation. After automatic validatin is OK make my own validation of dates. Before adding the code below the form and submit displays after validation:
date_from 2015-10-01 and date_to 2015-10-02
and after adding the code form displays before submit:
date_from 2015-10-01 and date_to 2015-10-02
after submit:
date_from 2015-10-02 and date_to 2015-10-01
Dates are switched. So it writes to the database.
    $date_from = $entity->getDatefrom();
$date_to = $entity->getDateto();
$workdays = 0;
for ( $i = $date_from; $i <= $date_to; $i->setTimestamp(strtotime($i->format('Y-m-d') . " +1 day") )  )
{
    if ( !in_array($i, $freedays))
    {
        if ( date('N', strtotime($i->format('Y-m-d') ) ) < 6 )
        {
            $workdays++ ;
        }
    }
}

When i remove this code dates are not switched. But ofcourse i don't have count of working days.

A: You need to dereference the DateTime Object $date_from using clone before assigning it to $i.
http://php.net/manual/en/language.oop5.references.php
$date_from = $entity->getDatefrom();
$date_to = $entity->getDateto();
$workdays = 0;
for ( $i = clone $date_from; $i <= $date_to; $i->setTimestamp(strtotime($i->format('Y-m-d') . " +1 day") )  )
{
    if ( !in_array($i, $freedays))
    {
        if ( date('N', strtotime($i->format('Y-m-d') ) ) < 6 )
        {
            $workdays++ ;
        }
    }
}

PHP doesn't copy objects when assigning them to a new variable it just creates a reference.
$i = $date_from

In this for loop it updates the $i for each iteration
$i->setTimestamp(strtotime($i->format('Y-m-d') . " +1 day") )

Because it's only a reference its this same as
$date_from->setTimestamp(strtotime($i->format('Y-m-d') . " +1 day") )
// OR even
$entity->getDatefrom()->setTimestamp(strtotime($i->format('Y-m-d') . " +1 day") )

Using clone make a copy of the original so $i->setTimestamp(...) won't actually apply to $date_from


text:
Q: Programmatic Website Screen Shots I'm checking into the available methods for programmatically taking screenshots of an arbitrary website. For example,
Facebook:
http://clicktoverify.truste.com/pvr.php?page=validate&url=www.facebook.com&sealid=102
Salesforce.com:
http://clicktoverify.truste.com/pvr.php?page=validate&companyName=Salesforce.com,%20Inc.&sealid=102&internal=true
On that page you'll see they have a screenshot of the referenced site.
What are my options for getting these kinds of screenshots in an automated fashion?
I'm primarily working with PHP, but am open to all suggestions.
Thanks!

A: Truth of the matter is, the actual process is extremely non-trivial.  You can of course manage it but it is a very difficult matter.
That said, there are a ton of webservices that you can use that do exactly this.  One such example is http://www.thumbalizr.com/ although they are by no means alone in this.


text:
Q: local variables not available to the python debugger I am trying to find out what is causing my application to SEGFAULT and managed to track it down to a certain module. I have set a trace within a certain function of the module:
def algorithm_wrapper(*args, **kwargs):
    _version = version
    if "Version" in kwargs:
        _version = kwargs["Version"]
        del kwargs["Version"]
    algm = _framework.createAlgorithm(algorithm, _version)
    pdb.set_trace()
    _set_logging_option(algm, kwargs)

If I want to check local variables _version and algm I get the following error:
-> _set_logging_option(algm, kwargs)
(Pdb) _version
    NameError: name '_version' is not defined
(Pdb) algm
    NameError: name 'algm' is not defined

I'm at a loss, this is the first time I find this error. Please help!

A: I'm not an expert on pdb, and it might just be a typo in your sample code and not what you actually tried, but don't you need to type the following into pdb to print a variable?
(Pdb) p _version

Versus just plain
(Pdb) _version

Sorry if that's not what's going on, that's just the only thing I see amiss. Good luck!


text:
Q: Can ThreadLocal be used in Cucumber paralel tests using mvn surefire plugin In our e2e project we want to parallelise test scenarios execution. In few places we would like to have something stored per thread e.g. WebDriver, scenario specific state etc. My first approach would be to use ThreadLocal like:
private static ThreadLocal<WebDriver> driverHolder = new ThreadLocal<>();

But also keeping in mind issues using combination of ThreadLocal and thread pools (for example the ones mentioned here here) I am wondering if ThreadLocal can actually be used in this context.
I don't know the insights of cucumber or surefire implementation details so I don't know if that kind of setup is thread safe as I am not fully controlling how these thread spawned and how teared down, which means that I can't clean up the ThreadLocal in an appropriate moment.

A: I am using  courgette-jvm in conjunction with cucumber-guice to parallelize tests without ThreadLocal. It  enters scenario specific info from gherkin into the ui and doesn't require any ThreadLocal or pool . Also it doesn't require you to clean anything. This setup automatically creates separate webdriver instances per scenario and runs separate browsers in parallel. I use it with selenium hub and extend it to docker if needed
import courgette.api.CourgetteOptions;
import courgette.api.CourgetteRunLevel;
import courgette.api.CucumberOptions;
import courgette.api.testng.TestNGCourgette;
import org.testng.annotations.Test;

@Test
@CourgetteOptions(
        threads = 10,
        runLevel = CourgetteRunLevel.SCENARIO,
        rerunFailedScenarios = true,
        rerunAttempts = 1,
        showTestOutput = true,
        reportTitle = "Courgette-JVM Example",
        reportTargetDir = "build",
        environmentInfo = "browser=chrome; git_branch=master",
        cucumberOptions = @CucumberOptions(
                features = "src/test/resources/com/test/",
                glue = "com.test.stepdefs",
                //tags = {"@post or @get"},
                publish = true,
                plugin = {
                        "pretty",
                        "json:target/cucumber-report/cucumber.json",
                        "html:target/cucumber-report/cucumber.html"}
        ))
class AcceptanceIT extends TestNGCourgette {
}

relevant pom elements
</dependency>
      <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.14.3</version>
    <scope>test</scope>
</dependency>
      <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>6.9.1</version>
</dependency>
      <dependency>
    <groupId>io.github.prashant-ramcharan</groupId>
    <artifactId>courgette-jvm</artifactId>
    <version>5.11.0</version>
</dependency>
      <dependency>
  <!-- httpclient dpendendecy is to resolve courgette-jvm error -  NoClassDefFoundError: org/apache/http/conn/ssl/TrustAllStrategy -->
 <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

RemoteWebdriver config
protected RemoteWebDriver createDriver() throws MalformedURLException {

        String hubURL =
            "http://192.168.1.3:"+"selenium hub port here"+"/wd/hub";
             ChromeOptions options = new ChromeOptions();
             DesiredCapabilities capabilities = DesiredCapabilities.chrome();
             capabilities.setCapability(ChromeOptions.CAPABILITY, options);
             return (RemoteWebDriver) (driver = new RemoteWebDriver(new URL(hubURL), capabilities));

        }

        @Override
         public RemoteWebDriver getDriver() throws MalformedURLException {
                this.createDriver();
                return (RemoteWebDriver) driver;
        }

cucumber-guice related configs
    import io.cucumber.guice.ScenarioScoped;
    @ScenarioScoped
          public class Global {
          public RemoteWebDriver driver;

          public Global() throws MalformedURLException, IOException {
                driver = new DriverFactory().getManager();
               // getManager() should have driver from above createDriver()

          }
    }

Inject Global class in your stepdefs like below (do necessary imports). You can inject helper classes also and guice will have it available per scenario
 @Inject
   Global global;

  //then you can do
   global.driver.get(site);

pom for cucumber-guice
 <dependency>
      <groupId>io.cucumber</groupId>
      <artifactId>cucumber-guice</artifactId>
      <version>${cucumber.version}</version>
      <scope>test</scope>
    </dependency>


text:
Q: Trying to find end of array in RAM with ARM assembler I'm writing a CRC32 program in assembler on an ARM "beagleboard", and for it I need to find the end of a char array in memory. The program is given (from a C framework) a pointer to the start of the array, and we need to iterate over the array. It is not known beforehand how large the array will be, and I'm not sure I'm allowed to check that in C and give that to the function as a variable, or even how that would work. Normally if I was coding this in C I'd just look for'\0', but when accessing this from RAM in assembler, that's just going to look like a byte full of zeroes. Is that still useful? Is there another way to detect the end of the array?
Thanks in advance!

A: "A byte full of zeroes" is still useful! If the array is null terminated, then you just need to find those 8 bits set to zero.
The tricky part is that the word size (the number of bits used in basic instructions) is probably something like 32 or 64 bits, not 8. So you will need to be able to isolate (mask) each 8 bit chunk of the word to check if it is set to all zeroes.

A: *

*Normally if I was coding this in C I'd just look for'\0'

Why does asm have to be any different?  In any language I choose I can simply iterate through the bytes looking for a zero byte.  The language is irrelevant.  ASM is a language as is C or pascal or java, etc.  If it is a zero terminated C string then whatever language you simply look for a zero.
C, asm, etc ram is ram an address is an address, so here again it has nothing to do with it, you have a starting address you iterate through until you find the zero byte.
Am I misunderstanding the question?  Is your "string" not a C string, not zero terminated?  If it isnt then your string by definition has to have some well known (to both sides) termination and or length specification.  And then once you have defined that well known termination you simply implement that in whatever language you choose.


text:
Q: What is wrong this simple function? Here is a simple function I am creating for purpose of practice.  But receive the given error.
DELIMITER $$

CREATE FUNCTION Weighted_Average(n1 INT, n2 INT, n3 INT, n4 INT)
RETURNS INT
 DETERMINISTIC
 BEGIN
  DECLARE avg INT;
  SET avg = (n1 + n2 + n3*2 + n4*4)/8;
  RETURN avg;
 END;
 DELIMITER $$

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'n4*4)/8;   RETURN avg;  END' at line 6
I am comparing it to this post:
MySQL CREATE FUNCTION Syntax
Someone with experience can probably point out my mistake while I am getting no where.  I don't see what is wrong where the error is asking me to look.  Note: I am using workbench.

A: Are you sure you don't mean the following, mainly the bottom of it?
DROP FUNCTION IF EXISTS Weighted_Average;
DELIMITER $$
CREATE FUNCTION Weighted_Average(n1 INT, n2 INT, n3 INT, n4 INT)
RETURNS INT
 DETERMINISTIC
 BEGIN
  DECLARE avg INT;
  SET avg = (n1 + n2 + n3*2 + n4*4)/8;
  RETURN avg;
 END;$$
 DELIMITER ;

A DELIMITER is necessary for some client-side environments to delineate the beginning and end of blocks, and to change the end-of-lines for statements.
As the DELIMITER is defaulted to ; out of the box, we know how to end a sql line with it, and never think about it. Until ...
When it comes to specialty blocks like CREATE PROCEDURE , FUNCTION, EVENT, TRIGGER, there needs to be some protocol for the client and server to know where the whole thing ends.
So, for clients like MySQL Workbench and similar, we use DELIMITER blocks. We change it to something funny up top, code as usual, and do the ending as seen above. Setting the DELIMITER back to our normal ;
They are not needed for PHPMyAdmin. And presumably not so for SqlFiddle


text:
Q: node:events:304 Error: listen EADDRINUSE: address already in use :::5000 I tried to use concurrently to run sever and client at the same time, then I got this error, even though I have tried lots of solutions online,  checked that no 5000 ports running, deleted modules, yarn.lock, cleaned up cache, restarted my PC, etc., the error stills remains.
package.json
{
  "name": "SPACEX_LAUNCH_STATS",
  "version": "1.0.0",
  "description": "App that lists SpaceX launch missions",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "yarn start --prefix client",
    "dev": "concurrently \"yarn run server\" \"yarn run client\""
  },
  "author": "admin",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.21.1",
    "concurrently": "^6.2.0",
    "express": "^4.17.1",
    "express-graphql": "^0.12.0",
    "graphql": "^15.5.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

error
Temps-MacBook-Pro:SPACEX_LAUNCH_STATS tempuser$ yarn run dev
yarn run v1.22.10
warning ../../../../package.json: No license field
$ concurrently "yarn run server" "yarn run client"
warning ../../../../package.json: No license field
warning ../../../../package.json: No license field
$ yarn start --prefix client
$ nodemon server.js
warning ../../../../package.json: No license field
[0] [nodemon] 2.0.9
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching path(s): *.*
[0] [nodemon] watching extensions: js,mjs,json
[0] [nodemon] starting `node server.js`
$ node server.js --prefix client
[0] Server started on port 5000
[1] node:events:304
[1]       throw er; // Unhandled 'error' event
[1]       ^
[1]
[1] Error: listen EADDRINUSE: address already in use :::5000
[1]     at Server.setupListenHandle [as _listen2] (node:net:1286:16)
[1]     at listenInCluster (node:net:1334:12)
[1]     at Server.listen (node:net:1420:7)
[1]     at Function.listen (/Users/tempuser/Documents/React/spaceX/SPACEX_LAUNCH_STATS/node_modules/express/lib/application.js:618:24)
[1]     at Object.<anonymous> (/Users/tempuser/Documents/React/spaceX/SPACEX_LAUNCH_STATS/server.js:17:5)
[1]     at Module._compile (node:internal/modules/cjs/loader:1083:30)
[1]     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1112:10)
[1]     at Module.load (node:internal/modules/cjs/loader:948:32)
[1]     at Function.Module._load (node:internal/modules/cjs/loader:789:14)
[1]     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:72:12)
[1] Emitted 'error' event on Server instance at:
[1]     at emitErrorNT (node:net:1313:8)
[1]     at processTicksAndRejections (node:internal/process/task_queues:80:21) {
[1]   code: 'EADDRINUSE',
[1]   errno: -48,
[1]   syscall: 'listen',
[1]   address: '::',
[1]   port: 5000
[1] }
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[1] yarn run client exited with code 1

One thing suspicious is that i was able to kill all the ports but there's one is not killable. It says "No such process". I'm not sure if this is the running port hidden somewhere behind the scene. Here are the screenshots. Please help.
No such process

A: I changed   "dev": "concurrently \"yarn run server\" \"yarn run client\"" to     "dev": "concurrently \"npm run server\" \"npm run client\"", and everything runs fine now. I don't know why, but ports 3000 and 5000 can both run now


text:
Q: Windows 7 Dell 1545 rotate screen and change wallpaper I recently bought a second monitor and hooked it to my laptop. I like to put the monitor in portrait mode when coding and i can do this with igfx but i was wondering if there was a way to make a keyboard shortcut that will rotate my display 270 degrees and change my wallpaper to one that fits the 1050 X 1680 portrait resolution, and then have a key that rotates back to normal and resets my wallpaper? I have googled to no avail, I look forward to your answers.

A: On Intel, the default rotation keys are Ctrl-Alt-Up for normal landscape, -Down for upside down, -Left and -Right for portrait.
It's under Options and Support/Hot Keys Manager on the latest version of the Intel Control Panel. I don't remember what it was on the older version, but it was there, too.
That won't change your wallpaper, though, you'd have to set up an event in the Task Scheduler to watch for resolution changes to do that.

A: You can use UltraMon for this. In it you can create your display profiles, save them and assign hotkeys to them.


text:
Q: Subgraph isomorphism problem with linear map I am working on proving the NP-hardness of a problem by reducing it from the subgraph isomorphism problem. Currently, I can reduce it from the following problem:
Problem 1: Given two graphs $G=(V, E)$ and $H=(V', E')$, is there a subgraph $G_0$ of $G$ that is isomorphism to $H$ under a linear mapping of vertices?
But the original subgraph isomorphism problem is defined as:
Problem 2: Given two graphs $G=(V, E)$ and $H=(V', E')$, is there a subgraph $G_0$ of $G$ that is isomorphism to $H$ under a bijection of vertices?
Can anybody tell me how to further reduce Problem 1 from Problem 2?
Edit: say I have the following graphs where $A_i, b_j \in \mathbb{R}$, and I want to see if there is a linear function parameterized by $\beta$ in the form of $b_j=\beta A_i$ that can make
$G_0$ and $H$ isomorphism.
Note that the figure is just for demo and we don't know if $H$ is a complete graph.


text:
Q: How scan for return values in python? !/usr/bin/env python
import sys
import ToBuildOrNot
repoArray = ["MSS_sims","PCS_CCS"]
def main(argv):
    for repo in repoArray:
    needsBuild = ToBuildOrNot.ToBuildOrNot(repo)

    if needsBuild == True:
        print "\n",repo,"Needs To rebuilt\n"
        print "---------------------------------------------------------------"

    elif needsBuild == False:
        print "\n", repo,"does NOT Need to be Rebuilt\n"
        print "---------------------------------------------------------------"

    else:
        print "error"

if name == 'main':
    main(sys.argv[1:])

A: Use == for equality check not is, is is used for identity check.
if needsBuild == True:
    print "The MSS_sims Needs To rebuilt"

elif needsBuild == False:
    print "The MSS_sims does NOT Need to be Rebuilt"

else:
    print "error

Related : Is there a difference between `==` and `is` in Python?


text:
Q: How to check the distance to the top category in dbpedia in sparql I am using the following query to get dbpedia categories (i.e. skos:broader|dct:subject) of a given dbpedia URI.
all_urls = ['http://dbpedia.org/resource/Machine_learning', 'http://dbpedia.org/resource/Category:Machine_learning']

for url in all_urls:
    print("------")
    print(url)
    print("------")
    sparql.setQuery("""
        SELECT * WHERE {<"""
             +url+
            """>skos:broader|dct:subject ?resource
            }
    """)

    sparql.setReturnFormat(JSON)
    results = sparql.query().convert()

    for result in results["results"]["bindings"]:
        print('resource ---- ', result['resource']['value'])

The output is:
------
http://dbpedia.org/resource/Machine_learning
------
resource ----  http://dbpedia.org/resource/Category:Cybernetics
resource ----  http://dbpedia.org/resource/Category:Learning
resource ----  http://dbpedia.org/resource/Category:Machine_learning
------
http://dbpedia.org/resource/Category:Machine_learning
------
resource ----  http://dbpedia.org/resource/Category:Artificial_intelligence
resource ----  http://dbpedia.org/resource/Category:Learning

Now I want to check the distance of each category in the output to the top level of dbpedia's category system (according to my current understanding dbc:Contents is the top element in the skos:broader and dct:subject hierarchy). Is it possible to do it in sparql?
I am happy to provide more details if needed.


text:
Q: Bitnami spark docker containers - workes cannot allocate CPUs I am using the bitnami spark:3.3 images with docker-compose 3.6. I have a 3 node spark cluster (master and 2 workers). The workers use 2 cores and 1G memory. They connect as expected to master. I have a Scala Akka-HTTP server that holds a persistent spark connection but performs no work (for now). But when I run spark-shell, one of the workers produces an error that states "CPUs per task should be > 0". Following this, the spark-shell is unable to allocate an executor (producing Initial job has not accepted any resource). I have tried various combinations of spark conf parameters but with the same result.
Any suggestions?


text:
Q: PDO SQL error (While inserting) Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\recover\recover.php:47 Stack trace: #0 C:\xampp\htdocs\recover\recover.php(47): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\recover\recover.php on line 47

This is my code:
// This checks if variabes are not empty, and if username is less than 11 characters long.
if (!empty($username) && !empty($password) && !empty($message) && strlen($username) < 11) {

    // Shortcut for our ID generator function.
    $ID = generateID();

    // Now lets insert (register the account) these datas to our database.
    $insert = $connect->prepare("INSERT INTO users (username, password, message, date, time, id) VALUES (:username, :password, :message, CURDATE(), CURTIME(), :id");

    // Executing in array, because if we binded all these variables, it would look very bad.
    $insert->execute(array(
        ':username' => $username,
        ':password' => $password,
        ':message' => $message,
        ':id' => $ID
    ));

    if (!$insert->execute()) {
        print_r($insert->errorInfo());
    }
}

I am new to PHP, pretty much, and many people telling me to start using PDO, before mysql_ will be out dated.
So I started, and it seems really hard.
Trying to get used to it.
What did I do wrong?
Thanks!

A: VALUES doesn't have a closing bracket.

A: The date and time are keywords. Please escape them using backticks.

You are missing the parentheses for your VALUES clause.

The prepare statement should be:
$insert = $connect->prepare(
    "INSERT INTO users ( username, password, message, `date`, `time`, id )
        VALUES( :username, :password, :message, CURDATE(), CURTIME(), :id )"
);


text:
Q: add the division symbol on OpenOffice Writer (Word) on Mac OS X How can I add the division symbol on OpenOffice Writer (Word) on Mac OS X?
I cannot seem to find a way to add this symbol.

A: The division symbol ÷ can be written in any editor (OpenOffice, Word, Safari text fields, Pages, TextEdit etc) with the key combo Option-/


text:
Q: What server side happen when abort a XHR request in client? I wonder what server-side will happen when aborting an XHR request in the client,
will the serverside still running, e.g do a transaction in DB?

A: Generally in a request, fetch data and return it -scenario the server can only reliably notice that the client has dropped the connection when it will try to write data back to the client (due to how the TCP/IP protocol works).
This can easily cause a scenario where the client makes a request, the server performs expensive work only to find out the client is no longer there and the data is dropped. This is one reason why streaming results are preferable when possible. If you can avoid gathering all the data up front, instead returning them as they become available, you don't risk performing useless work (although the client can still abort mid-connection, but that's his choice).


text:
Q: Email Class : Codeigniter 3.0,Cant Send Email I have Been try to send Mail using Codeigniter 3.0 .
My Controller :
function index()
    {

              $ci = get_instance();
                $ci->load->library('email');
                $config['protocol'] = "smtp";
                $config['smtp_host'] = "ssl://smtp.gmail.com";
                $config['smtp_port'] = "465";
                $config['smtp_user'] = "sriramarvind95@gmail.com";
                $config['smtp_pass'] = "";
                $config['charset'] = "utf-8";
                $config['mailtype'] = "html";
                $config['newline'] = "\r\n";

                $ci->email->initialize($config);
                $ci->email->from('sriramarvind95@gmail.com', 'Blabla');
                $list = array('skarthikeyan1410@gmail.com');
                $ci->email->to($list);
                $this->email->reply_to('sriramarvind95@gmail.com', 'Explendid Videos');
                $ci->email->subject('This is an email test');
                $ci->email->message('It is working. Great!');
                $result=$ci->email->send();

                if($result){
                    $data['email']="sent";
                }
                else{
                    $data['email']="not Sent";
                }
        //echo $this->email->print_debugger();
        $this->load->view('welcome_message',$data);

my view
<?php
if ($email="not Sent"){
    echo $this->email->print_debugger();
}
else{
    echo "Sent";
}

?>
Other than this,i configured my gmail account to allow less apps to login into gmail.
yet i get this error :

220 smtp.gmail.com ESMTP p10sm8628622obk.11 - gsmtp  hello: 250-smtp.gmail.com at your service, [23.102.172.97] 250-SIZE 35882577
  250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN
  OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING
  250 SMTPUTF8 Failed to authenticate password. Error: 534-5.7.14 Please
  log in via your web browser and 534-5.7.14 then try again. 534-5.7.14
  Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754
  p10sm8628622obk.11 - gsmtp  Unable to send email using PHP SMTP. Your
  server might not be configured to send mail using this method.
  User-Agent: CodeIgniter Date: Mon, 11 Apr 2016 13:17:26 -0700 From:
  "Blabla"  Return-Path:
   To: skarthikeyan1410@gmail.com Reply-To:
  "Explendid Videos"  Subject:
  =?utf-8?Q?=54=68=69=73=20=69=73=20=61=6E=20=65=6D=61=69=6C=20=74=65=73=74?= X-Sender: sriramarvind95@gmail.com X-Mailer: CodeIgniter X-Priority: 3
  (Normal) Message-ID: <570c06564edde@gmail.com> Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_570c06564edf2"
This is a multi-part message in MIME format. Your email application
  may not support this format.
--B_ALT_570c06564edf2 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit
It is working. Great!
--B_ALT_570c06564edf2 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable
It is working. Great=21
--B_ALT_570c06564edf2--

Trying this is in hosted service , not in localhost.
i have no clue , i use plain text in my password field . is it correct or should i generate something.
Please help.

A: Change these
$config['smtp_host'] = "ssl://smtp.googlemail.com"; # Change
$config['smtp_port'] = "465";
$config['smtp_user'] = "sriramarvind95@gmail.com";
$config['smtp_pass'] = ""; # Your account password


text:
Q: How to get date time format from javascript? I want to display date of today according the current datetime format without displaying the seconds
Thanks for help

A: You have to write some code yourself to do it, or you could use a library like Date.js.
JavaScript "Date" object instances have methods like .getFullYear(), .getMonth(), .getDate(), and so on. (Be aware that .getMonth() returns numbers from 0 through 11, not 1 through 12.)


text:
Q: Eclemma: branches missed in a for-loop -- what does it mean? Testing my code I've encountered a thing that I can't interpret. Examining the code coverage with eclemma I've found a header of a for-loop that is highlighted in yellow with the message reading "1 of 2 branches missing".
The code line is as following:
    for (int i = maxIdx; i >= 0; i--) {

The body of the loop is highlighted as covered (and is actually executed), as well as the preceding and following statements, and the method works fine under all possible conditions. The headers of other for-loops, as far as I could notice, are highlighted in yellow with the same message only in cases if the body of the loop have never executed.
What is the sense of this message? What branch is missing?

A: Here is how for loop of the form
for (ForInit; ForCondition; ForUpdate)
  Body

is executed:

*

*ForInit is executed

*ForCondition is evaluated

*

*when false, then Body is not executed and execution continues after loop

*when true, then Body is executed, ForUpdate is executed and execution continues from step 2

"2 branches" correspond to the above two options for ForCondition.
"1 of 2 branches missing" means that happened only one of these options, either first one, or second one.

In absence of complete example that includes body of your loop, hard to answer your additional questions

But strange -- why then other loops that always executed at least once are green?
Yet it's rather strange -- why other loops are always green?

However given that Body of your loop was executed, possible that there is exit from the loop in the Body before ForCondition evaluates to false.
For example using latest as of today version 2018-12 of Eclipse IDE for Java that comes with EclEmma 3.1.1:

And maybe there is no such exits in your other loops:

This can also explain

Running this code with an empty StringBuilder paints it green.

and

Adding an artificially created situation with an empty StringBuilder (that's impossible in reality) colors the loop in green.

because of added case when ForCondition evaluates to false before execution of Body:

A: I'm guessing the missing branches refer to the condition i >= 0. Since i is initialized with a positive maxIdx (according to the comments), you should probably also add test cases for maxIdx of 0 and a negative maxIdx.
Note that since maxIdx is the length of a StringBuilder (according to the comments), this may not be possible, and you'd have to either live with the missing branch, or "artificially" refactor your code so that you can pass a negative maxIdx.


text:
Q: Flash off by one pixel in IE9 only I have a website with a Flash banner. This has worked fine in all major browsers (IE7/8, Firefox, Chrome, Safari, Opera) for some time, but when I upgraded to IE9, the banner is displayed with a 1 pixel shim on the right-hand edge, which is throwing the layout off.
I know past versions of IE would display line breaks as white space and I wonder if that's what's going on here. I'm using the AC_FL_RunContent() function to display the Flash file. I'm not sure where to look to debug this, but I'd like to fix it sooner rather than later. Any help is appreciated.

A: How are you embedding your flash piece? The best way to do it is to use something like SWFObject, which should take all browser idiosyncrasies into account. It uses JavaScript to generate the embed code depending on what browser you're using. Give that a shot and it may solve your problem!

A: Our solution to this problem was to make the object 1 pixel wider than what we wanted, then surround it by a div of the right side with overflow hidden.
So although the problem was still occurring it was hidden.


text:
Q: The 7-segment LED display is too dark when connect to an auto-dimming circuit I'm using the below circuit to build a auto dimming circuit. I was fine when I only use one 7-segment LED, but when I connect more 7-segment LEDs (parallel to L1) the light intensity is very low. How to make it brighter and function properly?

A: Connect a 7 segment driver to the output of the circuit. That IC will manage all current calculations. IC ULN2003 seems to be a good option for your need. However, if you're not able to find a suitable driver for your need to design a circuit using MOSFET and connect them parallel to the output of your circuit. Since Mosfet is Voltage controlled device, you can connect many MOSFET in parallel, they will all run the same intensity.

A: What you need here is an LDR-controlled Digit Voltage ( not current). If there are  segment current resistors to regulate the brightness dependant on supply voltage drop, this will work and change the brightness uniformly with Digit Voltage.  If not , it wont.
Unfortunately, with a BJT the current regulation with Resistors only affects the current limit.  As you add more current displays, all the resistors have to be scaled down to increase the limits. This is why a True resistance controlled designed current source works better.
However, the real problem is you are driving all the Common Segment voltages with a current source which means the LEDS go dim with more segments active.
Thus an Emitter Follower of LDR bias voltage might work, not a Common Emitter


text:
Q: Working out the probability of the intersection of two events I can't get the probability of the intersection of two events to work out.
First, the sample space
$$
S = \{1, 2, 3\}
$$
Then we define two events
$$
A = \{1, 2\}
$$
$$
B = \{2, 3\}
$$
All of the outcomes are equally likely. So the probability of A is $\frac23$ and the probability of B is $\frac23$.
The events are independent, so the probability of the intersection of both events should be given by
$$P(A \cap B) = P(A)P(B)$$
The result is $\frac49$. However, intuitively, this is not what I expect. The set from the intersection of both events is $\{2\}$ and so I expect the probability to be $\frac13$.
What am I missing?

A: The events, as you have demonstrated, are not independent.
Place three numbered marbles in a bag.  I pick one, look at the number and tell you whether or not is one of $\{2,3\}$ or not (just "yes/no").   Clearly your measure of the probability that I have picked one of $\{1,2\}$ will be affected by knowing this.
$$\begin{align}
\mathsf P(A) & = \mathsf P(x\in\{1,2\})
\\[1ex] & = 2/3
\\[2ex]
\mathsf P(A\mid B) & = \mathsf P(x\in\{1,2\}\mid x\in\{2,3\})
& = \frac{\mathsf P(x\in \{2\})}{\mathsf P(x\in\{2,3\})}
\\[1ex] & = 1/2
\\[2ex]
\mathsf P(A\mid B^\complement) & = \mathsf P(x\in\{1,2\}\mid x\notin\{2,3\})
& = \frac{\mathsf P(x\in \{1\})}{\mathsf P(x\in\{1\})}
\\[1ex] & = 1
\end{align}$$


text:
Q: Leveraging Browser Caching Not Working I know my htaccess file is being read correctly by Google Pagespeed (it correctly reads I have enabled compression, and when I delete the file it says I have not enabled compression), but it is not able to read that I have enabled browser caching.  I have the following bit of code in my htaccess file. Why is it not working?
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

Thanks!

A: You have to enable enable mod_expires. Type this command and restart apache server:
sudo a2enmod expires
Enabling module expires.
Run '/etc/init.d/apache2 restart' to activate new configuration!


text:
Q: How to check if Class is castable to class How can I check if Class<Object> stores class that can be casted to another class, e.g. String? I tried to use clazz.isInstance(String.class), but this check always return true, because e.g. String is instance of Object.
Note that I cant use instanceof.

A: You're looking for isAssignableFrom
A String is an Object but an Object is not necessarily a String. So Object is assignable from String, but not the other way around.
class Scratch {
    public static void main(String[] args) {
        System.out.println(Object.class.isAssignableFrom(String.class)); //true
        System.out.println(String.class.isAssignableFrom(Object.class)); //false
    }
}


text:
Q: Does Groovy respect @PostConstruct? Consider a bit of Groovy code like:
def trainingCorpus = new CorpusNexmlReader(ignoreMissingTags: true,
                                           model: model, source: corpus,
                               abideByUse: true, useListSource: true,
                               listSourceDir: corpus + "/all/",
                               listSource: corpus + "/all/split_all.txt",
                               tagMap: tagMap
                               )

This helpfully uses the no-args constructor to make the object, and then makes calls
to all the setters corresponding to the named parameters. Now, if I add an @PostConstruct,
will Groovy call it after all those setters?

A: No, it won't. The @PostConstruct is used only for spring beans (instantiated by the spring context, and not by you)

A: From the javadocs on the @PostConstruct annotation:

"The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection"

Groovy is not a dependency injection framework. It will not do any processing of annotations directed toward DI frameworks. If you were building your bean as a Spring bean using Groovy's spring builder, then it should respect that annotation.
Alternately, you could read and process that annotation yourself.


text:
Q: Downloading amazon.co.uk webpage using only python, html exactly as firebug sees it I noticed that using urllib to download a webpage:
http://www.amazon.co.uk/Darkness-II-Limited-PC-DVD/dp/B005ULLEX6
the content that I get back using urlopen( url ).read() is different from what firebug sees.
Example:
If you point firebug to the page's image area, it tells you a div id="prodImageCell" exists, however when looking through what python has opened, there is no such thing, therefore beautifulsoup doesn't find anything.
Is this because the images are generated using javascript?
Question:
If so is there a way of downloading pretty much the exact same thing firebug sees using urllib (and not using something like Selenium instead).
I am trying to fetch the source url of one of the images programmatically, example here is the div with prodImageCell has src=http://ecx.images-amazon.com/images/I/51uPDvJGS3L.AA300.jpg which is indeed the url to the image.
Answer:
can't answer properly because I don't have the reputation :(
Found the solution thanks to @huelbois for pointing me in the right direction, one needs to use user-agents headers.
Before
>>> import urllib2
>>> import re
>>> site = urllib2.urlopen('http://www.amazon.co.uk/\
Darkness-II-Limited-PC-DVD/dp/B005ULLEX6').read()
>>> re.search( 'prodImageCell', site )
>>>

After
>>> user_agent = "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101\
Firefox/7.0.1"
>>> headers = {'User-Agent':user_agent}
>>> req = urllib2.Request(url=url,headers=headers)
>>> site = urllib2.urlopen(req).read()
>>> re.search( 'prodImageCell', site )
<_sre.SRE_Match object at 0x01487DB0>

hurrah!

A: Just tested it right now with wget (will work like urrlib).
You HAVE to include User-Agent header to get the requested part:
wget -O- --header='User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1' http://www.amazon.co.uk/Darkness-II-Limited-PC-DVD/dp/B005ULLEX6
returns the html page with the requested part.
oops: just saw right now you succeeded with my previous advice. Great!


text:
Q: datatable request database on every row I have a connection class laki this:
 public static OleDbConnection connection = new OleDbConnection();
    public string sorgu;
    public static string server;
    public static string userId;
    public static string catalog;
    public static string password;
    public DataSet ds = new DataSet();

    public bool Open()
    {
        try
        {
            if (connection.State != ConnectionState.Open)
            {

                connection.ConnectionString = "Provider=SQLOLEDB.1" +
                                               ";Password=" + password +
                                               ";Persist Security Info=True" +
                                               ";User ID=" + userId +
                                               ";Initial Catalog=" + catalog +
                                               ";Data Source=" + server;

                connection.Open();
                return true;
            }
            else
            {
                return true;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Sistem Mesajı:" + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }

    }

    public void CloseConnection()
    {
        if (connection.State == ConnectionState.Open)
        {
            connection.Close();
        }

    }

    public DataTable Dt(string query)
    {

        DataTable dt = new DataTable();
        if (Open())
        {
            OleDbDataAdapter da = new OleDbDataAdapter(query, connection);
            try
            {
                da.Fill(dt);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Sistem Mesajı:" + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //baglanti.Close();
        return dt;

    }

and this is my code which I get the values in a windows form
ConnectionClassOleDb cc = new ConnectionClassOleDb();
sorgu = " SELECT * FROM tblFiyatlandirma WHERE " +
                    " musteriNo=" + musteriNo +
                    " AND musteriTipId=" + musteriTipId;

            nudSiparisMetresi.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["siparisMetresi"]);
            nudKar.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["kar"]);
            nudKumasEni.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["kumasEni"]);
            nudMamulFire.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["mamulFire"]);
            nudMamulKumasKari.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["mamulKumasKar"]);
            nudNakliyeUcreti.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["nakliye"]);
            nudKomisyon.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["komisyon"]);
            nudTarakEni.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["tarakEni"]);
            nudTarakNo.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["tarakNo"]);
            nudTarakGecisi.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["tarakGecisi"]);
            nudAtkiFiyat.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["atkiFiyati"]);
            nudAtkiSikligi.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["atkiSikligi"]);
            nudAnalizNo.Value = Convert.ToDecimal(cc.Dt(sorgu).Rows[0]["analizNo"]);

the codes are work but in every cc.Dt(sorgu).Rows[0] row cc clas is going to connection class again and doing a new query. what is wrong?

A: Because every time you call 'Dt' you create a new datatable and adapter and fill the datatable with the adapter. This will cause the query to be executed on each call.
You should store the returned DataTable in a local variable and do your operations like 'Rows' on that instead of calling your DB class every time.
So:
DataTable dt = cc.Dt(sorgu);

and then use
dt.Rows[0]["siparisMetresi"]

instead of
cc.Dt(sorgu).Rows[0]["siparisMetresi"]

A: I have found DataAdapters horribly unpredictable, and I bet that is your problem.
I would instead wrap up your DataTable from the connection by getting a reader and converting to a table.  I found this code on the net about 5 years ago, and still use it every time (ConvertSqlDataReaderToDataTable).  The code below shows how to call it.  You should be able to modify to your needs very easily.  However, if you only pass through once, don't create the DataTable, but just use the DataReader instead.

        public static DataTable ConvertSqlDataReaderToDataTable(SqlDataReader reader)
        {
            ArrayList alColumns;
            DataColumn dcColumn;
            DataRow drRow;
            DataTable dtTemp;
            DataTable dtReturn;
            Int32 i;

        // create dataset to match the reader using reader's schema
        alColumns = new ArrayList();
        dtReturn = new DataTable();
        dtTemp = reader.GetSchemaTable();
        for (i = 0; i < dtTemp.Rows.Count; i++)
        {
            dcColumn = new DataColumn();
            if (!dtReturn.Columns.Contains(dtTemp.Rows[i]["ColumnName"].ToString()))
            {
                dcColumn.ColumnName = dtTemp.Rows[i]["ColumnName"].ToString();
                dcColumn.Unique = Convert.ToBoolean(dtTemp.Rows[i]["IsUnique"]);
                dcColumn.AllowDBNull = Convert.ToBoolean(dtTemp.Rows[i]["AllowDBNull"]);
                dcColumn.ReadOnly = Convert.ToBoolean(dtTemp.Rows[i]["IsReadOnly"]);
                alColumns.Add(dcColumn.ColumnName);
                dtReturn.Columns.Add(dcColumn);
            }
        }

        // read data into the dataset
        while (reader.Read())
        {
            drRow = dtReturn.NewRow();
            for (i = 0; i < alColumns.Count; i++)
            {
                drRow[alColumns[i].ToString()] = reader[alColumns[i].ToString()];
            }
            dtReturn.Rows.Add(drRow);
        }
        return dtReturn;
    }

    public static DataTable GetTable()
    {
        DataTable dtReturn;
        SqlConnection connection = new SqlConnection(global::Project.Properties.Settings.Default.DBConnection);
        SqlCommand command;
        SqlDataReader reader;

        try
        {
            connection.Open();

            command = new SqlCommand("SELECT * FROM Table", connection);
            command.CommandType = CommandType.Text;
            reader = command.ExecuteReader(CommandBehavior.SingleResult);
            dtReturn = ConvertSqlDataReaderToDataTable(reader);
            dtReturn.TableName = command.CommandText;
            reader.Close();
        }
        catch (Exception e)
        {
            // ADD ERROR HANDLING HERE
            dtReturn = new DataTable();
        }
        finally
        {
            connection.Close();
        }

        return dtReturn;
    }


text:
Q: Java functional programming way to justify text Stream I am trying to print out a long list of numbers so that each line is about the same length, i.e. never more than say 80 characters wide. I'm trying to learn the functional aspects of Java so thought I would convert my procedural version to use streams and lambdas etc. It seems difficult to get it right at the end because I don't know when I'm processing the last entry. Is this doable? And is it a reasonable thing to try to do this way? (suspecting not)
Here is my procedural version:
private static void printWholeListLimitedWidth(List<Integer> list, int width) {
    final int maxWidth = width;
    int lineWidth = 0;
    StringBuilder line = new StringBuilder(width);
    for (Integer n : list) {
        String toPrint = String.format("%d, ", n);
        if (line.length() + toPrint.length() > width) {
            System.out.println(line.toString());
            line.delete(0, line.length());
        }
        line.append(toPrint);
    }
    if (line.length() > 0) {
        System.out.println(line.toString());
    }
}

And here is my attempt at a functional version:
private static void printWholeListLimitedWidthFunctional(List<Integer> list, int width) {

    list.stream().forEach(new Consumer<Integer>() {
        StringBuilder line = new StringBuilder(width);
        public void accept(Integer j) {
            String toPrint = String.format("%d, ", j);
            if (line.length() + toPrint.length() > width) {
                System.out.println(line.toString());
                line.delete(0, line.length());
            }
            line.append(toPrint);
        }
    });
}

The functional version runs, but leaves off the last few numbers. I realize it is because I don't have anything equivalent to the if statement after the loop in the procedural version, but don't see a better way to know where the end than processing the list twice.

A: As @ernest_k mentioned, avoid creating instances inside iteration, moving StringBuilder outside will help to achieve your result, also take the full advantages of lambda expression for concise code
   //StringBuilder should be outside the lambda scope, do not create instance everytime
    StringBuilder temp = new StringBuilder();
    list.stream().forEach(i -> { //using as lambda
         //your toPrint is always of length 3, no need create extra variable
         if(temp.length() + 3 > width){
              System.out.println(temp.toString());
              temp.delete(0, temp.length());
          }
          //directly append it
           temp.append(i).append(", ");
     });
     //finally you can manually check and print pending
     if(temp.length() > 0){
         System.out.println(temp);
     }

A: You can use a collector in this case, something like this
private static void printNumbersLimited(List<Integer> numbers, int width) {
    System.out.println(numbers.stream()
            .map(number -> String.format("%d ", number))
            .collect(() -> new NumberFormatter(width), NumberFormatter::append, NumberFormatter::merge).complete());
}

private static class NumberFormatter {
    private final int width;
    private int length;
    private final StringBuilder builder = new StringBuilder();

    public NumberFormatter(int width) {
        this.width = width;
    }

    public String complete() {
        return (builder.toString());
    }

    public void append(String s) {
        if (length + s.length() > width) {
            length = 0;
            builder.append('\n');
        }
        builder.append(s).append(" ");
        length += s.length();
    }

    public void merge(NumberFormatter other) {
        throw new UnsupportedOperationException();
    }
}


text:
Q: I need to make a scatterplot from a csv file containg date on the x axis and time on the y axis, how do i code this? I need to create a scatterplot that contains the Date on the X axis and the Time on the Y axis. The date looks like (4/10/2019) and the time looks like (23:55:00) if this matters.
I have tried the following code.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("Crimes_-_2001_to_present.csv")
plt.scatter(df["Date_1"],df["Time_1"])
plt.xlabel('Date', fontsize=16)
plt.ylabel('Time', fontsize=16)
plt.title('Occurence of Crime in Relation to Time',fontsize=20)
plt.show()

My error message:

====================== RESTART: F:\scatter plot code.py ======================
Traceback (most recent call last):
  File "F:\scatter plot code.py", line 6, in <module>
    df = pd.read_csv("Crimes_-_2001_to_present.csv")
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\parsers.py", line 429, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\parsers.py", line 895, in __init__
    self._make_engine(self.engine)
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\parsers.py", line 1122, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\io\parsers.py", line 1853, in __init__
    self._reader = parsers.TextReader(src, **kwds)
  File "pandas\_libs\parsers.pyx", line 387, in pandas._libs.parsers.TextReader.__cinit__
  File "pandas\_libs\parsers.pyx", line 705, in pandas._libs.parsers.TextReader._setup_parser_source
FileNotFoundError: [Errno 2] File b'Crimes_-_2001_to_present.csv' does not exist: b'Crimes_-_2001_to_present.csv'

I am totally lost, I appreciate any help!
I expected a scatterplot.

A: You can also try including the full path of your csv file.
df = pd.read_csv("THE FULL PATH TO YOUR FILE")

A: First, check your .csv file name is correct;
Then try put your .csv file "Crimes_-_2001_to_present.csv"  and your .py code in the same folder;
Run;
if not ok: change your .csv file name to simple way, such as "Crimes2001.csv";
.py file change by: df = pd.read_csv(r"Crimes2001.csv");
Run again, then  it must be ok!


text:
Q: Best way to debug rspec integration tests with capybara? I have an rspec test failing, but in development, when I perform the actions myself, the page renders correctly.
Here's the snippet:
describe "sign up process" do

let (:admin1) { FactoryGirl.create(:admin) }

describe "with valid information"

  before do
    visit new_admin_registration_path
    fill_in "Email", with: admin1.email
    fill_in "Password", with: admin1.password
    fill_in "Password confirmation", with: admin1.password_confirmation
    click_button "Sign up"
  end

  it { should have_selector('div.alert') }
end

It's not finding that selector at all, but I confirmed it exists when viewing the source using the development environment.
What I'd like to be able to do is inspect the page that's rendering to see what I'm missing.  Is there a way to do that?

A: Capybara has a method save_and_open_page which will open a new browser window with the current state of the page (it requires the launchy gem).
For example:
  before do
    ...
    click_button "Sign up"
    save_and_open_page
  end

A: this is as easy as using the debugger or something different like pry in your spec.
i personally prefer pry, cause installing the debugger was kind of a hassle everytime i tried it with ruby 1.9...
with pry you would just add a require "pry" in your spec_helper.rb and then write a binding.pry the line before the problem occurs. you then have an irb session attached to your test.


text:
Q: How to extract only the latest or today attachment I would like to extract only the latest or today attachment.
I can only get one attachment and it is always the first (oldest) email.
Sub Download_Attachments()
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("nflow")

    Dim msg As Outlook.MailItem
    Dim fo As Outlook.Folder
    Dim at As Outlook.Attachment

    Set fo = Outlook.GetNamespace("MAPI").Folders("XXXXX").Folders("Inbox").Folders("Ad Hoc").Folders("XXXX")
    'Set fo = Outlook.GetNamespace("MAPI").Folders("XXXX@XXXX.com").Folders("Inbox").Folders("test")

    'Filter folder
    '    Set oOlInbFiltered = fo.Items.Restrict("[UnRead] = True AND [Subject] = 'TEST SUBJECT' AND [ReceivedTime]>='" & Format(Date, "DDDDD HH:NN") & "'")

    Dim lr As Integer
    Dim count As Integer

    count = 0

    For Each msg In fo.Items
        lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))

        sh.Range("A" & lr + 1).Value = msg.Subject
        sh.Range("B" & lr + 1).Value = msg.Attachments.count

        If count = 0 Then
            For Each at In msg.Attachments
                If VBA.InStr(at.Filename, ".xlsx") > 0 Then
                    at.SaveAsFile sh.Range("G1").Value & "\" & at.Filename
                End If
            Next
        'count = count + 1
        End If

A: Use the (commented out) line of your code that calls Restrict(). You can also call oOlInbFiltered.Sort to sort on the received time.


text:
Q: Table of conversion of ISO-639/ISO-3166 based language/country locale name to Windows ones and back I want to convert POSIX locale names like en_US, de_DE that use
ISO-639-1 and ISO-3166 codes
to Windows ones English_United States, German_Germany and back.
I had found following tables on MSDN site:

*

*Languages http://msdn.microsoft.com/en-us/library/39cwe7zf(v=VS.71).aspx

*Countries http://msdn.microsoft.com/en-us/library/cdax410z(v=VS.71).aspx
However they are very partial. For example these tables miss Arabic, Hebrew and many other locales that I know are supported Hebrew_Israel.
Where can I find fully updated tables of Windows locale names and ISO 639/3166 codes.
Note: I need it to work from Windows 2000 or at least XP to Windows 7, so I don't want to relay on
fact that Vista and 7 support BCP-47 style locale names.
Edit: I have an ISO-639 language codes and ISO-3166 country/territory codes.  But I need to know what languages/countries are supported and how they are actually named under MSVC should I use.

A: I think I had found the answer: http://msdn.microsoft.com/en-us/library/cc233965.aspx
This documents includes locale ids, their names and ISO codes...


text:
Q: Why .\Turorial.exe can run but Tutorial.exe not on PowerShell? I'm new for cmake, and try run the cmake example.
Compiling process is all normal, but when I run Tuturial.exe 5 on powershell, got error as follows:

Suggestion [3,General]: The command django-admin was not found, but
does exist in the current location. Windows PowerShell does not load
commands from the current location by default. If you trust this
command, instead type: ".\django-admin". See "get-help
about_Command_Precedence" for more details.

But run .\Tutorial.exe 5, everything is ok.
So I want know why this error happens, and if I want learn more what things should I learn?
Note: run Tuturial.exe 5 on cmd is also normal.

A: Say you have a malicious command named foo in the current directory, unbeknownst to you, and you also have the command foo installed on your system. If you tried to run the (system) command foo, it would instead run the malicious program. So, in a nutshell, it is for security reasons, as it protects you from running unintended programs, and this is the reason that PowerShell (and almost all of Linux, as HolyBlackCat pointed out) forces you to use a ./ or .\ in front of your program name.
This is pointed out and explained in this question.


text:
Q: How should I model a nested comment thread? Hi
I'm implementing a forum with nested post threads (reddit style)
threads and comments can be voted on.
threads can be tagged
threads have titles, comment don't
my views will usually need to generate only a subset of 3 levels of the whole comment tree.
i'm wondering if I should create a separate and table model for threads, or use only table where root = 0 if it's a thread record
in the latter option i'm thinking of creating a tabless model which will represent a thread (the id will be the id of the root comment
what will be the easiest way to implement it ?
Edit:
this is what i'm thinking about the second option. what relations should thread and post have ? should thread be a resource?
class Thread
  include ActiveModel::Validations

  attr_accessor :root_post_id, :depth
end

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
  #belongs_to :thread ?????

  acts_as_tree

  acts_as_taggable_on :topics
end

A: One way to implement is to have both the thread and replies in the same table.
ID | THREADID

The ID field can be auto generated. The THREADID field takes the ID of the thread post which will always be the first post in a thread and all other replies will inherit that same ID.
Therefore a root post is one where the ID == THREAD and replies are those where ID != THREADID.


text:
Q: Scikit train_test_split by an indice I have a pandas dataframe indexed by date. Let's assume it from Jan-1 to Jan-30. I want to split this dataset into X_train, X_test, y_train, y_test but I don't want to mix the dates so I want the train and test samples to be divided by a certain date (or index). I'm trying
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
But when I check the values, I see the dates are mixed. I want to split my data as:
Jan-1 to Jan-24 to train and Jan-25 to Jan-30 to test (as test_size is 0.2, that makes 24 to train and 6 to test)
How can I do this? Thanks

A: you should use
X_train, X_test, y_train, y_test = train_test_split(X,Y, shuffle=False, test_size=0.2, stratify=None)

don't use random_state=None it will take numpy.random
in here its mentioned that use shuffle=False along with stratify=None

A: Try using TimeSeriesSplit:
X = pd.DataFrame({'input_1': ['a', 'b', 'c', 'd', 'e', 'f'],
                  'input_2': [1, 2, 3, 4, 5, 6]},
                 index=[pd.datetime(2018, 1, 1),
                        pd.datetime(2018, 1, 2),
                        pd.datetime(2018, 1, 3),
                        pd.datetime(2018, 1, 4),
                        pd.datetime(2018, 1, 5),
                        pd.datetime(2018, 1, 6)])
y = np.array([1, 0, 1, 0, 1, 0])

Which results in X being
           input_1  input_2
2018-01-01       a        1
2018-01-02       b        2
2018-01-03       c        3
2018-01-04       d        4
2018-01-05       e        5
2018-01-06       f        6

tscv = TimeSeriesSplit(n_splits=3)
for train_ix, test_ix in tscv.split(X):
    print(train_ix, test_ix)

[0 1 2] [3]
[0 1 2 3] [4]
[0 1 2 3 4] [5]


text:
Q: Python join element i with i+1 I have a list of dates
dates = [date1, date2, date3, date4, ...]

where each date is of the form '2010-01-01' for example
and I want to create an array:
ranges = [date1+'-'+date2, date2+'-'+date3, date3+'-'+date4,...]

I can get this with a for loop that throws up an error:
ranges = []
for i, t in enumerate(result):
    ranges.append(t+"-"+result[i+1])

which obviously crashes out at the final i because I am referencing i+1. I can't think how to do this neatly.

A: my_ranges = []
for i range(len(dates)-1): #go til the second to last element
    my_ranges.append(dates[i] + "-" + dates[i+1])

Or if you want to do it in one line with a list comprehension:
my_ranges = ["-".join( (dates[i],dates[i+1])) for i in range(len(dates)-1)]

And even shorter with the zip and map.
map("-".join, zip(dates, dates[1:]))

A: Use the pairwise recipe:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

Demo:
In [77]: dates =["date1", "date2", "date3", "date4"]

In [78]: from itertools import izip, tee

In [79]: map("-".join, pairwise(dates))
Out[79]: ['date1-date2', 'date2-date3', 'date3-date4']

for python3 replace izip with zip:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

And call list on map if you want to get a list or use a list comp:
In [5]: from itertools import  tee

In [6]: list(map("-".join, pairwise(dates)))
Out[6]: ['date1-date2', 'date2-date3', 'date3-date4']

Or roll your own:
def pairs(l):
    it = iter(l)
    prev = next(it)
    for ele in it:
        yield "{}-{}".format(prev, ele)
        prev = ele

Demo:
In [10]: list(pairs(dates))
Out[10]: ['date1-date2', 'date2-date3', 'date3-date4']

All the approaches avoid indexing or making extra copies of the data.
You can also use enumerate checking the index:
print(["{}-{}".format(dte,dates[i]) for i, dte in enumerate(dates, 1) if i < len(dates)])

Which gives you the same:
['date1-date2', 'date2-date3', 'date3-date4']


text:
Q: Send message from popup to content script? Suppose I want to run a content script when I click a button in the popup page in a google chrome extension?
I have tried the following:
//popup.js
document.addEventListener('DOMContentLoaded', function () {
  document.querySelector('button').addEventListener('click', clicked);
  main();
});

function clicked(){
    chrome.tabs.getCurrent(
        function(tab){
            console.log(tab);
            chrome.tabs.sendMessage(tab.id, "doSomething");
        }
    );
}

And in the content script:
chrome.extension.onMessage.addListener(
    function(message, sender, sendResponse){
        console.log("hello world");
    }
);

The problem is that the tab in the callback from chrome.tabs.getCurrent( ) is undefined.

A: Have you given permissions for tabs in manifest.json as shown here.
 "permissions": [
    "tabs"
  ],

Moreover tab.id which the following code returns is of popup view (NOT A CONTENT SCRIPT TAB.ID)
chrome.tabs.getCurrent(
        function(tab){
            console.log(tab);
            chrome.tabs.sendMessage(tab.id, "doSomething");
        }
    );

If you want to send message to tab you are browsing use following code's tab.id, it gives correct results
chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tabs){
     console.log(JSON.stringify(tabs[0]));
     console.log(tabs[0].id);
});

Let me know if you need more information

A: The answer provided by @Sudarshan is valid and works fine, but I just found another solution to my problem. Just thought i put it here:
function clicked() {
    chrome.tabs.executeScript(null,
      {code:"console.log('hello world');"});
}

It will inject and execute the script.


text:
Q: Json.Net DeserializeObject failing with OData.Delta - integers only This problem is affecting my ASP.Net WebApi Patch method which looks a lot like this:
public MyModel Patch(int id, [FromBody]Delta<MyModel> newRecord){/*stuff here*/}

But it's not WebApi that's the problem - the failure is between Json.Net and OData.Delta.
The problem is JsonConvert.DeserializeObject does not see integers of OData.Delta objects and I'm wondering if there's a workaround or fix I can apply.
UPDATE: Have written code (see right down below) in the Json.Net library that will fix this.  Just need it to be included in the next update (if James Newton-King allows it)
UPDATE 2: After further testing, I've decided the best course of action is to stop using OData.Delta and write my own (see answer)
Unit tests to prove the problem exists (using statements moved below for clarity)
Test 1: Fails with an int (Int32):
class TestObjWithInt
{
    public int Int { get; set; }
}
[TestMethod]
public void IsApplied_When_IntIsDeserializedToDelta()
{
    string testData = "{\"Int\":1}";
    var deserializedDelta = JsonConvert.DeserializeObject<Delta<TestObjWithInt>>(testData);
    var result = deserializedDelta.GetChangedPropertyNames().Contains("Int");
    Assert.IsTrue(result);
}

Test 2: Succeeds with a long (Int64)
class TestObjWithLong
{
    public long Long { get; set; }
}
[TestMethod]
public void IsApplied_When_LongIsDeserializedToDelta()
{
    string testData = "{\"Long\":1}";
    var deserializedDelta = JsonConvert.DeserializeObject<Delta<TestObjWithLong>>(testData);
    var result = deserializedDelta.GetChangedPropertyNames().Contains("Long");
    Assert.IsTrue(result);
}

And just to be sure that deserialization works to begin with, these two tests both pass.
[TestMethod]
public void IsApplied_When_LongIsDeserializedToTestObject()
{
    string testData = "{\"Long\":1}";
    var deserializedObject = JsonConvert.DeserializeObject<TestObjWithLong>(testData);
    var result = deserializedObject.Long == 1;
    Assert.IsTrue(result);
}
[TestMethod]
public void IsApplied_When_IntIsDeserializedToTestObject()
{
    string testData = "{\"Int\":1}";
    var deserializedObject = JsonConvert.DeserializeObject<TestObjWithInt>(testData);
    var result = deserializedObject.Int == 1;
    Assert.IsTrue(result);
}

I found this OData bug report which sounds like a similar issue but its old and closed so probably not.
Any help would be great.
Using statements (from the top of the test file):
using System;
using System.Linq;
using System.Web.Http.OData;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

Solution if accepted by James Newton-King - change to release 6.0.6.
Replace JsonSerializerInternalReader.cs line 1581:
contract.TrySetMember(newObject, memberName, value);

with:
bool done = false;
while (!(done = done || contract.TrySetMember(newObject, memberName, value)))
{
    switch (reader.TokenType)
    {
        case JsonToken.Integer:
            if (value is long && ((long)value) <= Int32.MaxValue && ((long)value) >= Int32.MinValue)
                value = Convert.ToInt32(value);
            //Add else if (...) to cast to other data types here (none additional required to date).
            else
                done = true;
            break;
        default:
            done = true;
            break;
    }
}

A: OData.Delta<T> does not work with Json.Net for any number Types other than Int64.  The easiest approach is to write a replacement for OData.Delta<T> (which I've done on company time so I can't post it in its entirety sorry) containing methods like this:
private bool TrySetInt32(object value, PropertyInfo propertyInfo, bool isNullable)
{
    var done = false;
    if (value is Int32)
    {
        propertyInfo.SetValue(_obj, value);
        done = true;
    }
    else if (value == null)
    {
        if (isNullable)
        {
            propertyInfo.SetValue(_obj, value);
            done = true;
        }
    }
    else if (value is Int64) //Json.Net - fallback for numbers is an Int64
    {
        var val = (Int64)value;
        if (val <= Int32.MaxValue && val >= Int32.MinValue)
        {
            done = true;
            propertyInfo.SetValue(_obj, Convert.ToInt32(val));
        }
    }
    else
    {
        Int32 val;
        done = Int32.TryParse(value.ToString(), out val);
        if (done)
            propertyInfo.SetValue(_obj, val);
    }
    return done;
}

The class can be a dynamic generic like this:
public sealed class Patchable<T> : DynamicObject where T : class, new()

With a working variable like this:
T _obj = new T();

In the overridden TrySetMember method, we need to check the underlying type of the property using reflection and call the appropriate TrySet... method like this:
if (underlyingType == typeof(Int16))
    done = TrySetInt16(value, propertyInfo, isNullable);
else if (underlyingType == typeof(Int32))
    done = TrySetInt32(value, propertyInfo, isNullable);

If the value is set successfully we can add the property name to a list that we can then use for patching the original record like this:
if (done)
    _changedPropertyNames.Add(propertyInfo.Name);

public void Patch(T objectToPatch)
{
    foreach (var propertyName in _changedPropertyNames)
    {
        var propertyInfo = _obj.GetType().GetProperty(propertyName);
        propertyInfo.SetValue(objectToPatch, propertyInfo.GetValue(_obj));
    }
}

68 unit tests later, it all seems to work pretty well.  Here's an example:
class TestObjWithInt32
{
    public Int32 Int32 { get; set; }
    public Int32? SetNullable { get; set; }
    public Int32? UnsetNullable { get; set; }
}
[TestMethod]
public void IsApplied_When_Int32IsDeserializedToPatchable()
{
    string testData = "{\"Int32\":1,\"SetNullable\":1}";
    var deserializedPatchable = JsonConvert.DeserializeObject<Patchable<TestObjWithInt32>>(testData);
    var result = deserializedPatchable.ChangedPropertyNames.Contains("Int32");
    Assert.IsTrue(result);
    var patchedObject = new TestObjWithInt32();
    Assert.AreEqual<Int32>(0, patchedObject.Int32);
    deserializedPatchable.Patch(patchedObject);
    Assert.AreEqual<Int32>(1, patchedObject.Int32);
    Assert.IsNull(patchedObject.UnsetNullable);
    Assert.IsNotNull(patchedObject.SetNullable);
}

A: This is my implementation for this issue based on Rob solution:
public sealed class Patchable<T> : DynamicObject where T : class {
    private readonly IDictionary<PropertyInfo, object> changedProperties = new Dictionary<PropertyInfo, object>();
    public override bool TrySetMember(SetMemberBinder binder, object value) {
        var pro = typeof (T).GetProperty(binder.Name);
        if (pro != null)
            changedProperties.Add(pro, value);
        return base.TrySetMember(binder, value);
    }
    public void Patch(T delta) {
        foreach (var t in changedProperties)
            t.Key.SetValue(
                delta,
                t.Key.PropertyType.IsEnum ? Enum.Parse(t.Key.PropertyType, t.Value.ToString()) : Convert.ChangeType(t.Value, t.Key.PropertyType));
    }
}

I removed the requisite of an empty constructor in generic type parameter using the dictionary instead of a temporal object.
Thanks Rob ;)


text:
Q: Mouse movement lags flash game this was not happening before in a game I play (Realm of the Mad God), which was flash version 11.2.202.621, but now is happening in 11.2.202.626, The game runs through shockwave (swf).
If needed I have footage of the problem.
Problem still persists with flash 11.2.202.632
Edit: using flash player projector debugger from adobe, just recently it stopped the lag, but only for the projector, projector set in 11.2.202.626.
Edit: the problem does not seem to cause lag, but generally stop the game from running in general, data reception and distribution seem to stop when I move my mouse at a high rate.
Edit: This issue might be caused by firefox's cash.
Ubuntu 16.04 was also happening in 14.04.

A: The problem was solved after I changed the scan frequency of my mouse to 125hz, going through the mouse settings of my razer mouse I changed some of the settings and tested it by playing the game.


text:
Q: How to align paragraph with different chunks in iText I need help in to Justify the alignment of the below paragraph:
Font certifyFont = new Font(Font.TIMES_ROMAN, 16);
Paragraph certifyParagraph = new Paragraph();
certifyParagraph.setAlignment(Element.ALIGN_JUSTIFIED_ALL);

Chunk certifyText = new Chunk("This is to certify that  ", certifyFont);
certifyParagraph.add(certifyText);

Font nameFont = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
Chunk nameText = new Chunk("NAME ", nameFont);

Font workingFont = new Font(Font.TIMES_ROMAN, 16);
Chunk workingText = new Chunk("has been working in the company since the ", workingFont);

doc.open();
doc.add(certifyText);
doc.add(nameText);
doc.add(workingText);
doc.close();

I tried to align the paragraph to justify, center and right, but the alignment doesn't seem to be reflected in the PDF file.

A: In your code, you are creating a Paragraph object certifyParagraph and you are defining an alignment for it, but you are never adding it to the document. Instead you are adding three different Chunk objects, named certifyText, nameText and workingText.
I have adapted your code so that these three Chunk objects are added to the Paragraph object, and so that the Paragraph object is added to the document instead of the separate (alignment-less) chunks:
Paragraph certifyParagraph = new Paragraph();
certifyParagraph.setAlignment(Element.ALIGN_JUSTIFIED_ALL);

Font certifyFont = new Font(Font.TIMES_ROMAN, 16);
Chunk certifyText = new Chunk("This is to certify that  ", certifyFont);
certifyParagraph.add(certifyText);

Font nameFont = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
Chunk nameText = new Chunk("NAME ", nameFont);
certifyParagraph.add(nameText);

Font workingFont = new Font(Font.TIMES_ROMAN, 16);
Chunk workingText = new Chunk(" has been working in the company since the ", workingFont);
certifyParagraph.add(workingText);

doc.open();
doc.add(certifyParagraph);
doc.close();


text:
Q: HTML5 video css background color on iPad Is it currently possible to set the background color of HTML5 video elements effectively? About HTML5 Audio and Video points to the fact that you can style video tags with standard CSS, but in my experience this isn't fully working:

*

*On Chrome 23 (Snow Leopard) adding a poster image attribute to the video tag removes the background color, without a poster image it works as you might expect

*On Safari 5.1.7 everything works correctly

*Perhaps unsurprisingly Mobile Safari on an iPad running iOS 5 is a law until itself. The background color will always be black, no matter what I do. Occasionally I might get a flash of the set css background color before the poster / video load. But even with an empty video tag, the background color won't display.

Anyone had any success setting a background color on iPad?

A: Please refer to my question according HTML 5 on mobile safari.
Seems that it's impossible to control it, as video rendering is delegated to hardware through the browser, and is displayed "above", so controlling css properties of it would not affect anything.
My research was some ago, but don't think that since then anything changed.