text:
Q: Node.js + mongo + express MVC API: how to use controllers? I'm writing my first MEAN app... To be correct, currently it is a MEN :-) app, since it's only the server-side API by now...
I'd like to follow an MVC pattern (or MC, since I have no views).
I want to choose a correct structure for my app, and I'm trying to understand how to use routes, model and controllers... In particular, it's not clear to me how to use controllers...
The first question is this: how and where do I define my class methods?
Currently:
I define a 'model' in "models/person.js".
Then, I add (class) methods in the same model file, this way:
personSchema.method.save = function(callback) {
  this.model('Person').savefind({ type: this.type }, callback);
}
module.exports = mongoose.model('Person', personSchema);

Then, in the routes ("routes/persons.js", for example), I require() the models I need, and implement the route methods.
If this is a correct and common approach, I do not understand how to use controllers... :-(
Maybe controllers are not needed in a server-side API exposing application?
Hope someone can shed some light on my MEAN understanding... :-)

A: Well, a controller is basically an adapter between your domain code and your view code, and that's what you are accomplishing with your routing code in Express. You might want to check out this MVC example by the express people to get a better idea, and this related SO answer speaking of routes vs controllers.
On the other side of the puzzle, you'll find Angular does have a component called controllers, which ideally would delegate the server-talking aspect to other Angular components like services but are arguably not exactly the kind of controllers you're probably thinking of in a typical MVC example.

A: Assuming you're using Express 4
https://www.terlici.com/2014/09/29/express-router.html
Create an app.js such as
var express = require('express')
  , app = express()

//we're loading in our 'controllers' as middleware
app.use(require('./controllers'))

app.listen(3000, function() {
  console.log('Listening on port 3000...')
})

then in /controllers create an index.js, that looks like:
var express = require('express')
  , router = express.Router()

router.use('/person', require('./person'))

//default routes here
//these could go in a separate file if you want
router.get('/', function(req, res) {
  res.send('Home page')
})

router.get('/about', function(req, res) {
  res.send('Learn about us')
})

module.exports = router

Next, your person controller will look something like this:
var mongoose = require('mongoose'),
    Person = mongoose.model('Person'),
    express = require('express'),
    router = express.Router()

// actual url will be /person/ since we're loading this in via index.js
router.get('/', function(req, res) {
  Person.find({}, function(err, results) { return res.send(results); } );
})

router.post('/', function(req, res) {
  //save logic here
})

module.exports = router


text:
Q: Ubuntu ignores eth0 I am having a very frustrating problem with Ubuntu 16.04 and my network interface.
First of all the ethernet card works: the computer is dualbooted with Windows and Windows connects perfectly to the internet. So no hardware and no cable problem.
In fact as soon as I power up the computer the leds on the ethernet card start blinking...but as soon as I boot up Ubuntu they shut down!
The OS complains about a "cable not plugged in" problem, but the situation is much worse.
The eth0 interface is recognized by ifconfig, but it is NOT listed under /etc/network/interfaces and sudo ifup eth0 complains about "unknown interface eth0"
Nmcli reports the interface as "unavailable" and dmesg | grep eth0 states that "link is not ready".
I have perused multiple forum entries, but nothing seems to work...any ideas?
Thanks!

A: After hours of breaking my face on the Internet I finally found out that the problem was related to the god-damned Realtek 8619 (or something like that) drivers that were probably installed in one of the latest updates.
I patched it with a workaround by adding:
sudo ethtool -s eth0 speed 1000 duplex full autoneg off

to /etc/rc.local
Now it works, even if it would probably be better to rollback to another driver as suggested elsewhere.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using java applet in c++ program I am doing a project in c++ where I need to embed a java applet/java program.( like we usually see on webpages). I was wondering what is the easiest way to do this. Right now, I am using Qt designer. Thanks.

A: If you use QWebPage in your application you can load a url that has the JApplet embedded.
Edit:
You may not have JRE installed on the target machine if it's not loading the applet. If you do something like below it should spit out a message if something goes wrong with Java. This is just an untested example to give you the basic idea of what I meant.
An example webpage:
<html>
<head>
<title>Java Applet</title>
</head>
<body>
<applet code="YourApplet.class" width=400 height=400>Java not supported or not installed</applet>
</body>
</html>

Save this as MyPageName.html
A simplistic example of using this in Qt:
// the QWebView has a QWebFrame and QWebPage to make it easy
QWebView* webView = new QWebView(parentWidget); // MainWindow or whatever as parent
webView->load(QUrl("MyPageName.html")); // local page or valid URL
webView->show();

Hope that helps a bit more

A: In version 4.8 of Qt, java applets are not supported.


text:
Q: what is the command to be able page up/down a long text? i keep forgetting and I am not sure how to look this up
if for example i want to see the ls commands --help, its very long
i remember there's a command that allows you to  go up and down on the output text - how do i do that?
i tried nano but for some reason it doesn't work as well as i thought it did
(also PS
the command i am looking for ls is to see hidden files, if u want you could tell me what that is on the way)

A: I'm not sure if I understand what you mean but when you do
man ls

you can use following commands:
space to advance one page
d to advance half a page
b to go back one page
u to go back half a page
arrow keys to go up/down with one line at a time

A: Pipe the output into less, for example
ls --help | less

Use q to quit less.

A: You can simply use Shift+PgUp and Shift+PgDn to scroll the output in your terminal.
Or you can pipe your output to less, e.g.:
ls --help | less

then you can scroll with cursor up/down.
And the command you are actually looking for is ls -A to show all files.


text:
Q: Unable to run flutter project on Android connected with USB I am trying to run my flutter project on Android connected with USB Debugging Enabled , i tried running flutter doctor it saying everything is OK flutter doctorbut while running the project it stucks on gradle task assembling gradle assembling, also my device is authorised with my PC and all other commands like push pull working fine
Edit
running flutter run -v gives an Error
[   +6 ms] Exception in thread "main" java.util.zip.ZipException: error in opening zip

file
[   +2 ms] [!] Gradle threw an error while downloading artifacts from the network.Retrying to download...

[+7209 ms] Exception: Gradle task assembleDebug failed with exit code 1


text:
Q: python,django, solr, haystack: arg_parse error when editing solr_build_schema BaseCommand.add_argument() Please help....i am trying use solr, pysolr and haystack on my django site search. I have edited the haystack build_solr_schema script to use BaseCommand.add_argument(), removing the default options_list. Below are my versions used;
Python 3.5.2
Django 1.11.11
solr-7.3.0
django-haystack 2.4.0
pysolr 3.7.0
# encoding: utf-8

from __future__ import absolute_import, division, print_function, unicode_literals

import sys
from optparse import make_option
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand
from django.template import Context, loader
from haystack import constants
from haystack.backends.solr_backend import SolrSearchBackend

class Command(BaseCommand):
    help = "Generates a Solr schema that reflects the indexes."

    def add_arguments(self, parser):
        # positional arguments
        parser.add_argument("-f", "--filename", action="store", type="string", dest="filename",
                help='If provided, directs output to a file instead of stdout.',),
       # optional positional arguments
       parser.add_argument("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS,
                help='If provided, chooses a connection to work with.')

      """
       base_options = (
       make_option("-f", "--filename", action="store", type="string", dest="filename",
                help='If provided, directs output to a file instead of stdout.'),
       make_option("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS,
                help='If provided, chooses a connection to work with.'),
       )
      option_list = BaseCommand.option_list + base_options
      """
     def  handle(self, **options):
         """Generates a Solr schema that reflects the indexes."""
         using = options.get('using')
         schema_xml = self.build_template(using=using)

         if options.get('filename'):
            self.write_file(options.get('filename'), schema_xml)
         else:
             self.print_stdout(schema_xml)

    def build_context(self, using):
        from haystack import connections, connection_router
        backend = connections[using].get_backend()

        if not isinstance(backend, SolrSearchBackend):
            raise ImproperlyConfigured("'%s' isn't configured as a SolrEngine)." % backend.connection_alias)

        content_field_name, fields = backend.build_schema(connections[using].get_unified_index().all_searchfields())
        return Context({
            'content_field_name': content_field_name,
            'fields': fields,
            'default_operator': constants.DEFAULT_OPERATOR,
            'ID': constants.ID,
            'DJANGO_CT': constants.DJANGO_CT,
            'DJANGO_ID': constants.DJANGO_ID,
        })

    def build_template(self, using):
        t = loader.get_template('search_configuration/solr.xml')
        c = self.build_context(using=using)
        return t.render(c)

    def print_stdout(self, schema_xml):
        sys.stderr.write("\n")
        sys.stderr.write("\n")
        sys.stderr.write("\n")
        sys.stderr.write("Save the following output to 'schema.xml' and place it in your Solr configuration directory.\n")
        sys.stderr.write("--------------------------------------------------------------------------------------------\n")
        sys.stderr.write("\n")
        print(schema_xml)

    def write_file(self, filename, schema_xml):
        schema_file = open(filename, 'w')
        schema_file.write(schema_xml)
        schema_file.close()

The error is gives is given below as
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 275, in run_from_argv
    parser = self.create_parser(argv[0], argv[1])
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 249, in create_parser
    self.add_arguments(parser)
File "/home/tochie/virtual_django/myblog_env/mysite/venv/lib/python3.5/site-packages/haystack/management/commands/build_solr_schema.py", line 22, in add_arguments
    help='If provided, directs output to a file instead of stdout.',),
File "/usr/lib/python3.5/argparse.py", line 1344, in add_argument
    raise ValueError('%r is not callable' % (type_func,))
ValueError: 'string' is not callable

Please help if there is any other way of solving this issue,without having to edit haystack's build_solr_schema or any other solution to this problem..Thanks

A: The problem is with the type argument. As the name suggests, it needs to be the python type str and not the python string 'string' . Meaning this is what you need
def add_arguments(self, parser):
    # positional arguments
    parser.add_argument("-f", "--filename", action="store", type=str, dest="filename",
                        help='If provided, directs output to a file instead of stdout.', )
    # optional positional arguments

    parser.add_argument("-u", "--using", action="store", type=str, dest="using",
                        default=constants.DEFAULT_ALIAS, help='If provided, chooses a connection to work with.')

When you do pass type as a string, and not the type str, argparse assumes you are supplying a callable for execution. See https://docs.python.org/3/library/argparse.html#type

type= can take any callable that takes a single string argument and
  returns the converted value:

def perfect_square(string):
    value = int(string)
    sqrt = math.sqrt(value)
    if sqrt != int(sqrt):
        msg = "%r is not a perfect square" % string
        raise argparse.ArgumentTypeError(msg)
    return value

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('foo', type=perfect_square)
parser.parse_args(['9'])

parser.parse_args(['7'])


text:
Q: BLE Beacon Scanning with Luch I am playing around with the BLE beacon scanner library Luch in Kotlin.
To scan for beacons I did the following (which is working):
   val beaconScanner = BeaconScanner.Builder(context)
        .setBeaconParser(beaconParser)
        .setBeaconBatchListener { beacons ->
            for (beacon in beacons) {
                val beaconPower = beacon.txPower
            }
        }
        .setRangingEnabled()
        .build()

    beaconScanner.start()

However, to calculate the distance for one beacon, one has to use the Ranger class. The code example is:
val ranger = beaconScanner.getRanger()
val distance = ranger.calculateDistance(beacon)

Since the beaconScanner object is a listener, I don't know how to reference the beacon list outside. I tried to save the returned beacons-list and to access it after starting the scanning but this does not seem to work. Inside the setBeaconBatchListener I cannot call the calculateDistance function because it is part of the Ranger class which I don't have access to inside the listener.
Can someone please help me and tell me how this works with listeners?


text:
Q: Python converting a list of strings to unicode I have a list of strings that originally was a list of unicode element. And so, some string contains some character accent in unicode formate.
 list=['Citt\xe0','Veszpr\xe9m','Publicit\xe0']

I need to get a new list that looks like this:
 new_list=[u'Citt\xe0',u'Veszpr\xe9m',u'Publicit\xe0']

Each element of the new_list has to carry both the u and the accent.
Is there a way to do it iterating on each element?

A: new_list=[unicode(repr(word)) for word in old_list]

>>> print new_list
[u"'Citt\\xe0'", u"'Hello'", u"'Publicit\\xe0'"]

Is that what you want?


text:
Q: Use regex to change all matching values in a multiindex column I am trying to follow this:
https://medium.com/swlh/reshaping-in-pandas-with-stack-and-unstack-functions-bb169f64467d
The author shows how to change the column values containing 'Inc' but when I run the code
I get:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
Code is below.  (1) is the authors code which generates the SettingWithCopyWarning.
I tried (2), which runs without error, but the df loses all other columns and I end up with this:
Student A  Labs    100
           Prj     100
Student B  Labs    100
           Prj      80

Code:
arrays = [['Week 1', 'Week 1', 'Week 2', 'Week 2', 'Week 3', 'Week 3', 'Week 4', 'Week 4'],
          ['1. Python', '2. Github', '3. Matplotlib', '4. SQL', '5. Pokemon', '6. OPP', '7. Pandas', '8. Stats']]

ar2 = [['Student A', 'Student A', 'Student B', 'Student B'],
       ['Labs', 'Prj', 'Labs', 'Prj']]

data = [['Incomplete', 70, 80, 80, 60, 90, 70, 80],
        [100, 70, 70, 70, 60, 80, 70, 80],
        ['Inc01a', 90, 60, 70, 80, 70, 70, 80],
        [80, 90, 70, 80, 90, 80, 100, 90]]
data = np.array(data)

df = pd.DataFrame(data, index=ar2, columns=arrays)
print(df, '\n')

# Clean up 'Incomplete' type entries.
# (1) df['Week 1']['1. Python'].replace(to_replace=r'^([Ii]nc).*', value=100, regex=True, inplace=True)
# (2) df = df['Week 1']['1. Python'].replace(to_replace=r'^([Ii]nc).*', value=100, regex=True)
print(df, '\n')

A: Ahh ... figured it out.  Had to use loc():
df.loc[:, ('Week 1', '1. Python')].replace(to_replace=r'^([Ii]nc).*', value=100, regex=True, inplace=True)

Found it here:  https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy


text:
Q: react-google-charts click event not working According to the documentation, you can Set the chart-specific events you want to listen to and the corresponding callback. The example is given uses select which works fine (I've setup an example here. The problem comes when I try to use any other chart type.
From the google charts documentation, for a bar chart, I should be able to use a click event:

When I add a click event like so:
  {
    eventName: "click",
    callback({}) {
      console.log("clicked");
    }
  }

Nothing happens, but the select event still works. I've setup a code sandbox here to demonstrate this behavior. This also happens for animationfinish, onmouseover, and every other event I've checked.

A: Looks like rakannimer already answered this in #263 on the GitHub repository, but figured I'd answer this anyway in case anyone else was having this issue.
As this stack overflow answer does a great job of explaining, the ready event must be fired before chart events (like those in the screenshot) can be triggered. Therefore, if you want to use any other event, you have to initiate them in a callback like this:
<Chart
  chartType="ScatterChart"
  width="80%"
  height="400px"
  data={data}
  options={options}
  legendToggle
  chartEvents={[
    {
      eventName: "ready",
      callback: ({ chartWrapper, google }) => {
        const chart = chartWrapper.getChart();
        google.visualization.events.addListener(chart, "onmouseover", e => {
          const { row, column } = e;
          console.warn("MOUSE OVER ", { row, column });
        });
        google.visualization.events.addListener(chart, "onmouseout", e => {
          const { row, column } = e;
          console.warn("MOUSE OUT ", { row, column });
        });
      }
    }
  ]}
/>

A: Please check below code snippet for adding click event:
import * as React from "react";
import { Chart } from "react-google-charts";

const chartEvents = [
      {
        callback: ({ chartWrapper, google }) => {
          const chart = chartWrapper.getChart();
          chart.container.addEventListener("click", (ev) => console.log(ev))
        },
        eventName: "ready"
      }
    ];

const data = [
  ["age", "weight"],
  [8, 12],
  [4, 5.5],
  [11, 14],
  [4, 5],
  [3, 3.5],
  [6.5, 7]
];

const options = {
  title: "Age vs. Weight comparison",
  hAxis: { title: "Age", viewWindow: { min: 0, max: 15 } },
  vAxis: { title: "Weight", viewWindow: { min: 0, max: 15 } },
  legend: "none"
};
const ExampleChart = () => {
  return (
    <Chart
      chartType="ScatterChart"
      data={data}
      options={options}
      graphID="ScatterChart"
      width="100%"
      height="400px"
      chartEvents={chartEvents}
    />
  );
};

export default ExampleChart;

A: In addition to the solution provided by @jake, the chartWrapper is no more available in the callback event. In my case, replacing it with wrapper works. Like
<Chart
  chartType="ScatterChart"
  width="80%"
  height="400px"
  data={data}
  options={options}
  legendToggle
  chartEvents={[
    {
      eventName: "ready",
      callback: ({ wrapper, google }) => {
        const chart = wrapper.getChart();
        google.visualization.events.addListener(chart, "onmouseover", e => {
          const { row, column } = e;
          console.warn("MOUSE OVER ", { row, column });
        });
        google.visualization.events.addListener(chart, "onmouseout", e => {
          const { row, column } = e;
          console.warn("MOUSE OUT ", { row, column });
        });
      }
    }
  ]}
/>```


text:
Q: Flyway DB migration for multiple code base in a single db I have 3 code bases:
1) db_product1
2) db_product2
3) db_common
db_common contains code that goes into both products, while db_product1 and db_product2 are the code bases for 2 separate databases.
ie, the Product1 database gets db_product1 and db_common
the Product2 database gets db_product2 and db_common
The versioning across products will not be shared, nor will common.  So, we could be at v1.3.5 for product1, v9.3.1 for product2, and v6.2.4
Thus, I am trying to figure out how to manage 2 code bases into a single database schema.  Relying on versions will not be sufficient, due to the conflicting ordering.
In looking through the documentation, I'm guessing that I can use two separate metadata tables.  Ie during the init or migrate commands, use Flyway.table=schema_history_common and Flyway.table=schema_history_product1, depending on which code base I'm installing.
Does this seem reasonable?  Am I missing something?

A: Yes, that seems reasonable. Ideally you would want to go to a schema per product, as this will provide you with clean namespacing and avoid any conflicts.


text:
Q: Count twurl's retrieved tweets with a specific hashtags In progress from the previous question, managed to request Tweets from a specific hashtag using the following command
twurl "/1.1/search/tweets.json?q=#HASHTAG"

Let's say we want to know the Tweets using the hashtag "jesus", then we do
twurl "/1.1/search/tweets.json?q=#jesus"

This gives the following JSON

Check here the get the full JSON (couldn't place it here because question's Body is limited to 30000 characters).
How can I count the number of Tweets retrieved (using Standard search API)?

A: One can count the number of Tweets by going to Notepad++ > Pasting the JSON there > CTRL + F > {"created_at": > Count

There's 24 matches, which means 24 tweets.

A: There are several ways to do this, for example you could use jq to filter and count the number of results. https://gist.github.com/andypiper/32bdb4c7f0b8d65385fc7c8fa3988083
twurl "/1.1/search/tweets.json?q=%23london&count=100" | jq '[.statuses[]] | length'


text:
Q: Returning a unique value across documents in couchDB usings views I have a series of documents each containing a date and a list of letters. I need the output to be a single, unique letter per key with the latest date for each letter as a value.
With a simple mapping function that looks like:
{
   "_id": "_design/output",
   "_rev": "1-c7b904b0e93709113c49127efb40187a",
   "language": "javascript",
   "views": {
       "output": {
           "map": "function(doc) {\n  emit(doc.args.report.updated_partitions, doc.timestamp);\n}",
           "reduce": "function(key, value, reduce) {\n  return (value)\n}"
       }
   }
}

I get the following result:
{"total_rows":2,"offset":0,"rows":[
{"id":"8e561dd15fd33acfc7c4502c58008c2a","key":["a","b"],"value":1403818824},
{"id":"8e561dd15fd33acfc7c4502c5800a212","key":["a","c","d"],"value":1403818700}
]}

The output I'm looking for should look like:
{"total_rows":2,"offset":0,"rows":[
{"id":"8e561dd15fd33acfc7c4502c58008c2a","key":["a"],"value":1403818824},
{"id":"8e561dd15fd33acfc7c4502c58008c2a","key":["b"],"value":1403818824},
{"id":"8e561dd15fd33acfc7c4502c58008c2a","key":["c"],"value":1403818824},
{"id":"8e561dd15fd33acfc7c4502c5800a212","key":["d"],"value":1403818700}
]}

A: I actually found a simpler method. The basic steps are:

*

*Map each individual letter to the date

*Reduce the result by returning the maximum value from an array of all dates by key.

The map looks like:
function(doc) {
  var files = doc.args.report.updated_partitions;
  var timestamp = doc.timestamp;

  for (i=0; i<files.length; i+= 1){
    var file_name = files[i];
    emit(file_name, timestamp);
  }
}

And the reduce looks like:
function(key, value, reduce) {
  return (Math.max.apply(null, value))
}

The result will be a unique key for each letter with the latest date from all docs as a value.
The use case for this is when each couch document has a list of files that were modified and the date the modification took place, but you would like to know the latest modification date for each individual document.


text:
Q: R programming - FindRoot of equation of the form f(x)=0 I am trying to perform FindRoot operation as in Mathematic using uniroot in R programming. My equation is of the form f(x)=0, which I am not able to specify. I got some output, which is continuously changing based on the initial estimate in uniroot function. Below is that piece of code. Kindly suggest.
Code is below :
sumTc <- 3365955
 n <- 136
 tn <- 88682

fun_b <- function(b){
    c <- 1
    1/b -1/(exp(b*(tn^c))-1) - sumTc/n
 }
uniroot(fun_b, c(-2,1))$root

This gives a values of 2.396734e-05
uniroot(fun_b, c(-1,1))$root

This gives a value of 9.414755e-05
Not sure if the way I am solving the equationis correct.


text:
Q: How to make WordPress live customizer select choices to update automatically via Ajax? If I want to use select option with different choices in my WordPress theme customizer, how can I make that choice to change on live on the theme.
So, I have a section in my functions.php file like this:
$wp_customize->add_setting(
    'menu_type',
    array(
        'transport' => 'postMessage',
        'default' => 'choice1',
    )
);

$wp_customize->add_control(
    'menu_type',
    array(
        'type' => 'select',
        'label' => 'Select your menu type:',
        'section' => 'header_section',
        'choices' => array(
            'choice1' => 'Choice 1',
            'choice2' => 'Choice 2',
            'choice3' => 'Choice 3',
            'choice4' => 'Choice 4',
        ),
    )
);

And in my ajax file I have a section like this:
wp.customize( 'menu_type', function( value ) {
    value.bind( function( newval ) {
        $('.someclass').css('border', '1px solid #111');
    } );
} );

Code in the ajax file changes css to ALL the choices. So what do I need to add in my ajax file, so I can make change for "choice1" ONLY instead?

A: Ok, heres the answer:
wp.customize( 'menu_type', function( value ) {
    value.bind( function( newval ) {
        if ( newval == 'choice1' ) {
            $( '.someclass' ).css('border', '1px solid #111');
        } else if ( newval == 'choice2' ) {
            $( '.someclass' ).css('border', '1px solid #222');
        } else if ( newval == 'choice3' ) {
            $( '.someclass' ).css('border', '1px solid #333');
        }
    } );
} );


text:
Q: if statement crashing my Android application I need help with using an if statement in java, here is my code :
if(ans==1)
{

txtans.setText("This is a Prime Number");

}
else
{
txtans.setText("This is NOT a Prime Number");
}

if I remove the setText methods in both statements my program works, but when I leave them there and the program finds ans, then it quits, I'm wondering whats wrong with the statements? or is it not possible to use the setText method within if statements..if so how do I overcome this? What I want to do is print a string to the TextView layout when the ans = 1, any suggestions?

A: Yes, you can run txtans.setText() in an if statement just as well as you could run it if it wasn't in an if statement.  You likely just don't have txtans initialised properly.
A quick google search brought up this as a way to print text to a textview.

A: Check your code, this erros usually comes when use findViewById() method in a wrong view.
In the activity you use like this findViewById(), maybe you need to call yourView.findViewById();
(If you post your class we can help you with more detailed answear.)

A: txtans might be NULL and you are trying to access a member of a NULL object.

A: Also note that it is not allowed to call methods from Views from another Thread which created them. But a LogCat output including the Error will enlight us for shure :)


text:
Q: Datetime objects not showing correct in bar plot I tried to read something about this, and I think I maybe already have solved my issue, but then again, it does not work how I want it to work.
I have a list called Year with years from 1945 to 2014; it contains years like:
['1945', '1946', '1946', '1947', '1947', ...] # yes, some are the same.

I have converted these to datetime (using datetime.datetime.strptime(item, '%Y')) so I can use them in my bar plot:
[datetime.datetime(1921, 1, 1, 0, 0), datetime.datetime(1925, 1, 1, 0, 0), ...]

If I then plot my datetime_year as the x-axis, it should show the years from 1945 to 2014.
When I plot these and try to show the plot, there is nothing on the X axis at 1921 to 2014 which maybe should be?
Instead I got something out on 710000.
Code of my plot:
from matplotlib import pylab as plt
import numpy as np

plt.bar(datetime_year, sorted_ratings2)
plt.suptitle('Ratings based on years', fontsize=14)
plt.ylabel('Rating', fontsize=12)
plt.xlabel('Year', fontsize=12)
plt.show()

And image of my plot:

A: Your code works as is:
from datetime import datetime
from matplotlib import pylab as plt
import numpy as np

Year = map(str, np.random.randint(1945, 2014, size=400)) # <-- put your data here
x = np.array([datetime(int(year), 1, 1) for year in Year])
y = np.random.random(x.shape) # <-- put your data here

plt.bar(x, y)
plt.suptitle('Ratings based on years', fontsize=14)
plt.ylabel('Rating', fontsize=12)
plt.xlabel('Year', fontsize=12)
plt.show()


text:
Q: How to use flint in Breath of the Wild? So I haven't been able to find a way to use the flint other than laying it next to a pile of wood and hitting the flint with a sword. Is there a better way to light ? I would have thought it would be like cooking and there would be an action when you walk up to wood...

A: That's the intended way to use flint. I believe you must hit it with a metal weapon for it to generate a spark to light wood.

A: Hitting a pile of wood with any fire weapon (sword, spear... includig fire arrows) will also start a bonfire.
Where to get a fire weapon:

 Top-right of the map theres a maze on an island you can reach flying. Going through one of the doors on the left will lead you to a bramble, once burned it down you can climb to a litle corridor where you will find a two-handed fire sword. There are a couple of Guardians at the start of the maze but you can easily avoid them.

I have the impression that theoretically it would be possible to start a fire with a lightning, but those come together with rain what makes impossible to set fire to anything.
Although it seems too obvious I have to say that you can light a fire bringing it from another one with a torch or a wooden weapon/arrow/shield.
As you said, flint is used to set fire, you can create your own bonfire hitting the flint with an iron weapon, light a food rack or set fire to a whole field of grass. Keep in mind that in bonfires you can still cook basic ingredients such as meat. It's also useful to make the time pass and to get warm in cold zones like high mountains or to melt ice.
Flint altogether with other materials can be used to improve some armors or forge some weapons. (Need to check this for more precise information)
There's also a guy in a horse house (sorry for the poor translation) close to the Orni town who will give you a reward in exchange for 52 flints. (Will improve this part of the answer once I can put my hands on the game)


text:
Q: Eclipse CDT: indexer reports error on automatic duration conversion while compiler is happy I am using Eclipse CDT (2018-12 (4.10.0)) for a C++ project (cross compiling with gcc 4.9.2).
In the following code the indexer got a problem with f(std::chrono::seconds(33));
#include <chrono>

void f(std::chrono::milliseconds) {
}

int main() {
    f(std::chrono::seconds(33));
}

The diagnostic says

Invalid arguments
  Candidates are
  void f(std::chrono::duration>)

The compiler processes the file without any problem though.
If I create a simple x86_64 project the indexer is happy.
What setting is incorrect in my project? Apparently both compilers can do the job and the indexer, too.
Under C/C++ General->Preprocessor Include Paths, Macros etc.->Providers->CDT GCC Built-In Compiler Settings->Command to get the compiler specs
I use the following command:
arm-v7a-linux-gnueabihf-g++ ${FLAGS} -E -P -v -std=c++11 -dD "${INPUTS}"

Is there any setting I can change to make the indexer happy?


text:
Q: Nested loops in Knockout.js with if:clause I am having a problem with nested foreach statements in KO.
The following statements work fine on their own but when I combine them the inner one doesn't work and doesn't throw an error either.
Ideally I would like the inner join to be conditional but I have tried it without the if clause and still no luck.
Experts have a property array of all ExpertRoles assigned to the particular user. The outer loop is meant to print all ExpertRoles and the inner loop is meant to print the Experts that match the Expert role of the outer loop
1st foreach: WORKS

2nd foreach: WORKS

combined with if clause: inner loop doesn't work, throws no error

 0, attr: { 'data-cid': ConnectionId, 'title': Username }">

no if clause: inner loop doesn't work, throws no error

EDIT:
Let me add that I have tried container-less syntax (

A: When you are using foreach in a nested loop you can access only properties of a parent model. Experts is not a property of an item from the ExpertRoles. It is a property of viewModel model. That's why it doesn't work. Try using $root:

= 0, attr: { 'data-cid': ConnectionId, 'title': Username }">


text:
Q: How to search for a particular word from a non iterable json object I'm working on resume parser. Now I am trying to add dynamism to code. So lets consider there are two resumes in a folder, I'm parsing them and returning required information as below in a json format in my API.
[
  {
    "dob": [],
    "education": [
      [
        "MCA",
        "2009"
      ]
    ],
    "email": "Id:abcd@gmail.com",
    "mobile_number": "+911234567",
    "name": "abcd",
    "personal_website": [
      "abcd@gmail.com",
      "http://www.arthavidhya.com",
      "http://www.myhealthwatcher.com",
      "http://www.i-southernworld.com/",
      "http://www.i-chiletravel.com/"
    ],
    "skills": [
      "Bootstrap",
      "Javascript",
      "Js",
      "Jquery",
      "Interactive",
      "My-sql",
      "Css",
      "Ajax",
      "Apache",
      "Php",
      "Codignator"
    ]
  },
  {
    "dob": [],
    "education": [
      [
        "Btech",
        "2018"
      ]
    ],
    "email": "xyz@gmail.com",
    "mobile_number": "+91987654321",
    "name": "xyz",
    "personal_website": [
      "xyz@gmail.com",
      "https://github.com/xyz"
    ],
    "skills": [
      "Sqlite",
      "Tensorflow",
      "C++",
      "C",
      "Php",
      "Android",
      "Mysql",
      "Flask",
      "Nlp",
      "Javascript",
      "Css",
      "Keras",
      "Machine learning",
      "Python"
    ]
  }

Now lets say I am passing input as 'Keras' then only the second file should be displayed. What logic can be used here? The difficulty I'm facing here is that my output is not iterable. Can someone give me hint on how to tackle this?
Please comment if my question is not clear or require any more details.

A: I think you can do something like this
def function1(json_object, name):
    match = []
    for dict in json_object:
        for key, value in dict.items():
            if (isinstance(value, str) and value == name) or (isinstance(value, list) and name in value):
                match.append(dict)
    return match

def main():
    print(json.dumps(function1(DATA, "Keras"), indent=2))

Basically we are checking if the value in dict is a string or list and trying to match with the string or list items.
Up to you to make it case insensitive or whatever change you want

A: Your output is very much iterable because it is a list.
What you can do is, loop through each resume, check if the required skills exists in the skill part of the resume, if it does, add it to the list of resumes that have the same skill. Finally, return the list in json. I hope the code snippet below will make it more clear!
import json
#resumes is the json data you have, skill is a string of the skill you're looking for.
def match_skill(resumes, skill):
  resumes_with_skill = []
  for resume in resumes:
    if skill in resume['skills']:
      resumes_with_skill.append(resume)
  return json.dumps(resumes_with_skill)

match_skill(data, 'Keras')


text:
Q: How to implement filter on dual ListView selection system? I have two ListView controls that I need to be able to move items back and forth between.  The moving is done by double-clicking an item in either list.
I also have a search field that will filter items from the Available list. This is where my trouble comes in.
I get an UnsupportedOperationException' when trying to remove an item from theListView's items. My current method of filtering the list seems to convert theListView's list to anAbstractList` which cannot be edited.
How do I allow filtering while keeping the underlying list editable?
Main Class
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

FXML Layout:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox fx:id="vboxMain" alignment="center" spacing="10" xmlns="http://javafx.com/javafx/9.0.1"
      xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">

    <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
    </padding>
    <children>
        <HBox spacing="10.0">
            <children>
                <VBox fx:id="vboxAvailableSearchTags" spacing="5.0">
                    <children>
                        <Label style="-fx-font-weight: bold;" text="Available"/>
                        <TextField fx:id="txtSearch" prefWidth="100.0"/>
                        <ListView fx:id="lvAvailable" prefHeight="200.0" prefWidth="100.0"/>
                    </children>
                </VBox>
                <VBox prefHeight="200.0" prefWidth="100.0" spacing="5.0">
                    <children>
                        <Label style="-fx-font-weight: bold;" text="Seleted"/>
                        <ListView fx:id="lvSelected" prefHeight="200.0" prefWidth="100.0" VBox.vgrow="ALWAYS"/>
                    </children>
                </VBox>
            </children>
            <padding>
                <Insets top="10.0"/>
            </padding>
        </HBox>
    </children>

</VBox>

Controller Class:
public class Controller {

    @FXML
    private TextField txtSearch;
    @FXML
    private ListView<String> lvAvailable;
    @FXML
    private ListView<String> lvSelected;

    private ObservableList<String> availableList = FXCollections.observableArrayList();
    private ObservableList<String> selectedList = FXCollections.observableArrayList();

    @FXML
    private void initialize() {
        // List of available strings
        availableList.addAll(
                "One",
                "Two",
                "Three",
                "Four",
                "Five"
        );

        // Initialize the search function
        // Wrap the list in a filtered list (initially showing all items)
        FilteredList<String> filteredList = new FilteredList<>(availableList.sorted());

        // Set the filter predicate whenever the filter changes
        txtSearch.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredList.setPredicate(availableItem -> {
                // If filter text is empty, show all items
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // Compare the tag name and search tags with the filter text
                String query = newValue.toLowerCase();

                if (availableItem.toLowerCase().contains(query)) {
                    return true;    // Query matches the available item
                } else return availableItem.contains(query);
            });

        });

        // Wrap the filtered list in a SortedList
        SortedList<String> sortedList = new SortedList<>(filteredList);

        lvAvailable.setItems(FXCollections.observableList(sortedList));
        lvAvailable.setPlaceholder(new Label("No results"));

        // Add the double-click listeners to move selected tags between the two lists
        lvAvailable.setOnMouseClicked(mouseEvent -> {
            if (mouseEvent.getButton().equals(MouseButton.PRIMARY) &&
                    mouseEvent.getClickCount() == 2) {
                addItem(lvAvailable.getSelectionModel().getSelectedItem());
            }
        });
        lvSelected.setOnMouseClicked(mouseEvent -> {
            if (mouseEvent.getButton().equals(MouseButton.PRIMARY) &&
                    mouseEvent.getClickCount() == 2) {
                removeItem(lvSelected.getSelectionModel().getSelectedItem());
            }
        });
    }

    private void addItem(String item) {

        // If the tag is not already in the Selected list...
        if (item != null && !lvSelected.getItems().contains(item)) {

            // Add the tag to the Selected list
            lvSelected.getItems().add(item);

            // Remove it from the available list
            lvAvailable.getItems().remove(item);

        }
    }

    private void removeItem(String item) {

        // If the tag is not already in the Selected list...
        if (item != null && !lvAvailable.getItems().contains(item)) {

            // Add the tag to the Available list
            lvAvailable.getItems().add(item);

            // Remove it from the Selected list
            lvSelected.getItems().remove(item);

        }
    }
}

A: First, you should use
lvAvailable.setItems(sortedList);

instead of
lvAvailable.setItems(FXCollections.observableList(sortedList));

A SortedList (and a FilteredList) are unmodifiable (because allowing modifications would violate the contract that they are sorted and/or filtered). You should modify the underlying lists instead:
private void addItem(String item) {

    // If the tag is not already in the Selected list...
    if (item != null && !selectedList.contains(item)) {

        // Add the tag to the Selected list
        selectedList.add(item);

        // Remove it from the available list
        availableList.remove(item);

    }
}

private void removeItem(String item) {

    // If the tag is not already in the Selected list...
    if (item != null && !selectedList.contains(item)) {

        // Add the tag to the Available list
        availableList.add(item);

        // Remove it from the Selected list
        selectedList.remove(item);

    }
}


text:
Q: Simple grep for anything year I know I'm doing something boneheaded here, but a regex cheat sheet given to us in my Unix/Linux class implied (by my reading) that this should find lines in a text file that contain years (numbers from 0000 to 9999):
grep \d{4} file.txt

Why does it find nothing instead? This is using bash, with the same result over PuTTY on Windows and in Terminal on Mac. I've tried variations with parentheses and quotation marks with no effect. Searching [0-9][0-9][0-9][0-9] works, but nothing with \d or {4} seems to function as I expect.
On a related note, why does .\+ have the effect I would expect .+ to have, while .+ just plain "doesn't work"? (I know that it tell grep to look for something but I don't know what.) Namely, it seems to be the way to ask for "one or more characters here" and not "one character followed by the plus sign". (It was the correct way to do an assignment, and the teacher could explain to my why it was that way) And how would one search for "one character followed by the plus sign"?

A: Your cheat-sheet may state that \d{4} is a valid regex meaning "four digits"; and it may state that grep searches a file for a regex. Taken separately, both of these statements are true. But taken together, they're highly misleading, since grep PATTERN FILE expects one kind of regular expression (POSIX "Basic Regular Expressions", BREs), whereas \d and {4} are notations from a different kind of regular expression (sometimes called "Perl Compatible Regular Expressions", PCREs, after the Perl programming language).
Many versions of grep support a -P flag to indicate that the pattern is a PCRE rather than a BRE; you can try:
grep -P '\d{4}' file.txt

(Note the single-quotes around \d{4}. These are necessary, because otherwise Bash will take \d as a sort of shorthand for 'd', so the actual pattern passed to grep will be d{4}, meaning "four d's" instead of "four digits". Alternatively, you could write grep -P \\d{4} file.txt, which solves the same problem in a different way.)

Edited to add: Sorry, I failed to cover the second part of your question, about +. So, according to the relevant specs,1 this:
grep .+ file.txt

uses . to mean "any character besides NUL" and + to mean "an actual plus-sign". So it really should print the lines of file.txt that contain a non-initial plus-sign; if you're seeing different behavior, then your shell and/or grep must be nonconformant.
Furthermore, this:
grep .\+ file.txt

is the same as the above, because a conforming POSIX shell (such as Bash) will treat \+ as a fancy way of writing +, so grep will see the same arguments as before. (grep will have no way of knowing that you typed .\+ rather than .+.)
Lastly, this:
grep '.\+' file.txt

(where the \ is actually passed through to grep) has undefined behavior: a given grep implementation can take it to mean the same thing as .+, or it can take \+ to be a special notation meaning "one or more" (or something else), or it can give an error message. The GNU implementation, as it happens, takes the "one or more" interpretation, but others may differ.
Footnotes:

*

*Namely the grep spec, and the BRE and ERE spec (which the grep spec links and refers to). Also relevant is the shell spec, since it's the shell decides the actual arguments that get passed to grep.

A: By default, grep uses  the POSIX regex flavor, which doesn't include \d. To use your expression, you need to switch to PCRE (arg -P)
grep -P \\d{4} file.txt

This will return every instance of 4-digit strings in file.txt.

A: If your version of grep happens to not support -P, the following will work:
grep "\d\{4\}" file.txt

As to your other questions, using the same flavor of regular expressions, .+ will match any character followed by a + sign.  .\+ will match one or more of any character.


text:
Q: Django queryset filter on boolean not working I have a model:
class mymodel(models.Model):
    order_closed = models.BooleanField(default=False)

I added this field to my development mysqllite db manually since its a new field for a model/table that already existed. I then tried:
mymodel.objects.filter(order_closed=False) #and with True

and its producing incorrect or unpredictable results. I saw some mention that is could be a sqllite thing but I'm not sure? The templates seem to understand whether its a true or false value but python code doesn't. To clarify with some examples:
{{mymodel.order_closed}} will print 0 after I set the default to 0 in sqllite. but using .filter(order_closed=value) will still return every record.

A: I think you make some mistake in wrirting SQL . If you have db which have some important informations use
south

http://south.aeracode.org/
When you will have it you can easly upgrate/edit your database .
If you dont wanna install new 'plugins' try that .
1. Delete this field from DB manualy .
2. write : python manage.py sql 'name of app'
It will return the CREATE TABLE SQL statements for the app.
Then you can upr your database manualy with some of CReate command.


text:
Q: How to populate custom header/footer view when using RxDatasources for datasource I am using RxDatasources to create my datasource. Later on, I configure cells in my view controller. The thing is, cause headers/footers has nothing with datasource (except we can set a title, but if we use custom header footer, this title will be overriden).
Now, this is how I configure my tableview cells:
private func observeDatasource(){

    let dataSource = RxTableViewSectionedAnimatedDataSource<ConfigStatusSectionModel>(
        configureCell: { dataSource, tableView, indexPath, item in
            if let cell = tableView.dequeueReusableCell(withIdentifier: ConfigItemTableViewCell.identifier, for: indexPath) as? BaseTableViewCell{
                cell.setup(data: item.model)
                return cell
            }

            return UITableViewCell()
        })

    botConfigViewModel.sections
        .bind(to: tableView.rx.items(dataSource: dataSource))
        .disposed(by: disposeBag)
}

now cause
dataSource.titleForHeaderInSection = { dataSource, index in
            return dataSource.sectionModels[index].model
}

... won't work, cause I want to load a custom header and populate it with data from RxDatasource, I wonder what would be a proper way to:

*

*get data from my datasource which is defined in my view model

*populate header, based on a section (I have multiple sections) with correct data, in the way that is always up to date with a datasource.

Here is my view model:
 class ConfigViewModel{

        private let disposeBag = DisposeBag()
        let sections:BehaviorSubject<[ConfigStatusSectionModel]> = BehaviorSubject(value: [])

        func startObserving(){

            let observable = getDefaults()

            observable.map { conditions -> [ConfigStatusSectionModel] in
                return self.createDatasource(with: conditions)
            }.bind(to: self.sections).disposed(by: disposeBag)
        }

        private func getDefaults()->Observable<ConfigDefaultConditionsModel> {

            return Observable.create { observer in
                FirebaseManager.shared.getConfigDefaults { conditions in

                    observer.onNext(conditions!)

                } failure: { error in
                    observer.onError(error!)
                }
                return Disposables.create()
            }
        }

        private func createDatasource(with defaults:ConfigDefaultConditionsModel)->[ConfigStatusSectionModel]{

            let firstSectionItems = defaults.start.elements.map{ConfigItemModel(item: $0, data: nil)}
            let firstSection = ConfigStatusSectionModel(model: defaults.start.title, items: firstSectionItems.compactMap{ConfigCellModel(model: $0)})

            let secondSectionItems = defaults.stop.elements.map{ConfigItemModel(item: $0, data: nil)}
            let secondSection = ConfigStatusSectionModel(model: defaults.stop.title, items: secondSectionItems.compactMap{ConfigCellModel(model: $0)})

            let sections:[ConfigStatusSectionModel] = [firstSection, secondSection]

            return sections
        }
    }

Now what I was able to do, is to set a tableview delegate, like this:
tableView.rx.setDelegate(self).disposed(by: disposeBag)

and then to implement appropriate delegate method(s) to create / return custom header:
extension BotConfigViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView,
                   viewForHeaderInSection section: Int) -> UIView? {
        guard let header = tableView.dequeueReusableHeaderFooterView(
                            withIdentifier: ConfigSectionTableViewHeader.identifier)
                            as? ConfigSectionTableViewHeader
        else {
            return nil
        }
        return header
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }

}

How to populate my custom header with data from my datasource? I don't want to do things like switch (section){...}, cause then its completely not in sync with a datasource, but rather manually, and if datasource changes, it won't affect on header configuration automatically.
Here are my model structs:
typealias ConfigStatusSectionModel = AnimatableSectionModel<String, ConfigCellModel>

struct ConfigItemData {
    let conditionsLink:String?
    let iconPath:String?
}

struct ConfigItemModel {

    let item:OrderConditionModel
    let data:ConfigItemData?
}

struct ConfigCellModel : Equatable, IdentifiableType {

    static func == (lhs: ConfigCellModel, rhs: ConfigCellModel) -> Bool {

        return lhs.model.item.symbol == rhs.model.item.symbol
    }
    var identity: String {
        return model.item.symbol
    }
    let model: ConfigItemModel
}

I tried to use this but I wasn't able to make it work completely, cause I guess I wasn't providing custom header in a right way/moment.

A: The fundamental issue here is that tableView(_:viewForHeaderInSection:) is a pull based method and Rx is designed for push based systems. Obviously it can be done. After all, the base library did it for tableView(_:cellForRowAt:) but it's quite a bit more complex. You can follow the same system that the base library uses for the latter function.
Below is such a system. It can be used like this:
source
    .bind(to: tableView.rx.viewForHeaderInSection(
        identifier: ConfigSectionTableViewHeader.identifier,
        viewType: ConfigSectionTableViewHeader.self
    )) { section, element, view in
        view.setup(data: element.model)
    }
    .disposed(by: disposeBag)

Here is the code that makes the above possible:
extension Reactive where Base: UITableView {
    func viewForHeaderInSection<Sequence: Swift.Sequence, View: UITableViewHeaderFooterView, Source: ObservableType>
    (identifier: String, viewType: View.Type = View.self)
    -> (_ source: Source)
    -> (_ configure: @escaping (Int, Sequence.Element, View) -> Void)
    -> Disposable
    where Source.Element == Sequence {
        { source in
            { builder in
                let delegate = RxTableViewDelegate<Sequence, View>(identifier: identifier, builder: builder)
                base.rx.delegate.setForwardToDelegate(delegate, retainDelegate: false)
                return source
                    .concat(Observable.never())
                    .subscribe(onNext: { [weak base] elements in
                        delegate.pushElements(elements)
                        base?.reloadData()
                    })
            }
        }
    }
}

final class RxTableViewDelegate<Sequence, View: UITableViewHeaderFooterView>: NSObject, UITableViewDelegate where Sequence: Swift.Sequence {
    let build: (Int, Sequence.Element, View) -> Void
    let identifier: String
    private var elements: [Sequence.Element] = []

    init(identifier: String, builder: @escaping (Int, Sequence.Element, View) -> Void) {
        self.identifier = identifier
        self.build = builder
    }

    func pushElements(_ elements: Sequence) {
        self.elements = Array(elements)
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier) as? View else { return nil }
        build(section, elements[section], view)
        return view
    }
}


text:
Q: Type 1 conditional for past or Type 2 condition Please help me understand the type of sentence below. Is it "Type 1 conditionals for past" or "Type 2"?

"If we didn't have lectures the next day, we would usually stay up late talking or watching TV"

I read this sentence in Oxford verb and tense book under " Type 0 and  Type 1 conditionals for past".
To me it looks like type 2 condition as it matches type 2 condition structure: If + past tense + would.

A: As you said,  the tenses match the 2nd type so this is a 2nd type conditional sentence although I think it would be more natural if type 0 was used here, something like:
" - If we don't have lectures the next day, we usually stay up late."
So it would be better to use type 0 conditional as it states a normal habit. If the sentence is put under "type 0 and type 1" section,  then I think it must be a typo as I said that it'd be better to use type 0 conditional and that is what should have been used in this section.


text:
Q: How to remoltly access my local home ubuntu machine from outside my local netwok usign VNC I want to remotely access my home ubuntu machine using VNC. I have followed the link here How To Configure Remote Access To Your Ubuntu Desktop
Now, I can remote access using the internal network.  I enabled port forwarding on my spectrum home router from port 5900 to internal ip address of the ubuntu machine and port # 5900 as shown in the screenshot below. However, when using vnc to connect to (mypublicaddress::5900), I was not able to log in. What should I do to be able to remotly access using the public address of my home router


text:
Q: How to find grid in picture or array [python] I'm stuck at my approach to find the grid in the following picture:

I have either a 8-Bit png file or a 2d-array of its intensities to work with.
I tried to find the grid via a local minima algorithm, but because of the intensity gradient and the noise it didn't quite work well. Also, I tried using OpenCV but I'm not very familiar with it, and it only found the two bald lines and some weird non-perpendicular diagonal lines.
My question would be, if there is a way/algorithm/library to find such fine lines, so that I can define their distance from each other. Thanks. (If more Info is needed I sure can give some, i just didn't wanted to overload this question)

A: You could convolve your image with a filter (matrix). Some matrix produces the result you are looking for( Prewitt filter, Sobel filter or Canny). Check https://en.wikipedia.org/wiki/Edge_detection
After performing a convolution it will be easy to tack the local maximum or minimum.
Also look at CNN (https://en.wikipedia.org/wiki/Convolutional_neural_network) which could do the job ^^

A: Usually canny edge detection and afterwards hough transformation is a good way to find straight lines in pictures.
image = np.array(Image.open('picture.jpg'), dtype=np.uint8)
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(im, xx, yy)

lines = cv2.HoughLines(edged,1,np.pi/180,threshold=pp)


text:
Q: Applying on click/on hover functions to multiple element classes in JS I have this code that I repeat for three different elements:
$container.on('click', '.item-content', function (event) {
  //some code

});

$container.on('click', '.item-content2', function (event) {
  //some code

});

But the same functionality of the function itself. Is there a way I can concatenate these into one  statement? Like:
$container.on('click', ['.item-content','.item-content2'], function (event) {
  //some code

});

A: You can add multiple elements like this
HTML
<button class="item-content">Button 1 </button>
<button class="item-content1">Button 2 </button>
<button id="item-content2">Button 3 </button>
<button class="item-content3">Button 4 </button>

JS
$('body').on('click','.item-content,.item-content1,
              #item-content2,.item-content3',function(event){
              alert(event.target.innerHTML)
})

WORKING MODEL
NOTE: Since I am not sure about $container i used body to deletegate the event.You can make changes as required.
Hope this will be useful

A: You can apply selector by comma separated like ".class1,.class2"
$(function(){
      $(document).on("click",".item-content,.item-content2",function(e) {
              alert('clicked');
      });
});


text:
Q: Show 1387 is a base 2 pseudoprime and is also composite using Miller's test My attempt:
1387 is a base 2 pseudoprime if $2^{1386} \equiv 1 \bmod 1387$. We note $1387=19 \cdot 73$ and $1386=18 \cdot 7 \cdot 11$, and by Fermat's Little Theorem(FLT), $2^{18} \equiv 1 \bmod 19$, so $(2^{18})^{77} \equiv 1 \bmod 19$.
Applying FLT again,  $2^{72} \equiv (2^{18})^4 \equiv 1 \bmod 73$. I would then like to imply $2^{18} \equiv 1 \bmod 73$, is this justified?  Then by the Chinese Remainder Theorem, $2^{1386} \equiv 1 \bmod 1387$.
A number is composite if it does not pass Miller's test for some base. Here, we use base 2. $2^{1386/2} = 2^{693} \equiv 512 \bmod 1387$, thus $2^{1386/2}$ is not congruent to $1$ or $-1$ mod 1387, therefore 1387 is composite. Here, I have calculated $2^{693} \equiv 512 \bmod 1387$ using a calculator, as $693 = 3\cdot 3 \cdot 7 \cdot 11$ so I couldn't use the Chinese remainder theorem. Is there a way to calculate it by hand?

A: You can use $$2^{18}\equiv 1\mod 1387$$
First of all, how to get this result ?
$2^{18}\equiv1\mod 19$ follows from Fermat's little theorem.
Since $73$ divides $2^9-1$ , we also have $2^{18}\equiv 1\mod 73$.
Chinese remainder theorem shows $2^{18}\equiv 1\mod 1387$.
Therefore, you can reduce the exponent $693$ modulo $18$ giving $9$, hence $2^{693}\equiv 2^9=512\mod 1387$

A: You can render $2^{18}\bmod 73$ efficiently with the repeated squaring method.  The exponent $18$ has the binary representation $10010$ so we have:
$2^{18}\equiv ((((2^2)^2)^2×2)^2\bmod 73$
The multiplication by the base $2$ after three squarings corresponds to the second $1$ being three positions after the initial $1$ in $10010_2$.  Working from the inner parentheses outward you get $2^{18}\equiv 1$ with little trouble, and you get $2^9\equiv 1$ (before the last squaring) too.


text:
Q: GNU Make seems to skip prerequisites I've got a basic, minimal makefile to compile C++ source; a stripped-down version looks like this:
TARGET = main

OBJ = $(patsubst %.cpp,%.o,$(wildcard *.cpp))
CPPFLAGS = -std=c++11 -Wall

build: $(TARGET)

$(TARGET): $(OBJ)
    @echo "$? --> $@"
    g++ $(CPPFLAGS) -o $@ $?
    @echo

%.o: %.cpp
    @echo "$< --> $@"
    g++ $(CPPFLAGS) -c $<
    @echo

When building from scratch, everything works as expected:
clock.cpp --> clock.o
g++ -std=c++11 -Wall -c clock.cpp

main.cpp --> main.o
g++ -std=c++11 -Wall -c main.cpp

clock.o main.o --> main
g++ -std=c++11 -Wall -o main clock.o main.o

After a change in one of the source files, make rebuilds the corresponding object file, but for some reason skips the existing (unchanged) object file when trying to link (clock.o --> main instead of clock.o main.o --> main):
clock.cpp --> clock.o
g++ -std=c++11 -Wall -c clock.cpp

clock.o --> main
g++ -std=c++11 -Wall -o main clock.o

When running make again, without changing any file, the linking works as expected:
clock.o main.o --> main
g++ -std=c++11 -Wall -o main clock.o main.o

What's the reason for this behavior, and how could it be prevented?
I'm running GNU Make 4.1 on i686 Linux 4.4

A: You use wrong automatic variable in g++ $(CPPFLAGS) -o $@ $? recipe.
https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html:

$?
The names of all the prerequisites that are newer than the target,
  with spaces between them.

So Make does exactly what you ask it to do: link main target from all updated prerequisites and skip untouched prerequisites.
g++ $(CPPFLAGS) -o $@ $^ recipe will fix the problem.


text:
Q: What is the density of consecutive primes which have gaps too small or too large from the average ? Let $p_i$ denote the $i$-th prime number and $g_i$ the $i$-th gap $g_i=p_{i+1}-p_{i}$.
By the PNT we know that the average gap is $g_i \approx \ln p_i$.
A gap $g_i$ is considered "too small" iff $\frac{g_i}{\ln p_i} \leq \frac{1}{2}$ and is considered "too large" iff $\frac{g_i}{\ln p_i} \geq 2$
Now i want to know the $\#$ of gaps that are "too small or too large", this is defined below :
Let $T(i) = 1$ iff $\frac{g_i}{\ln p_i} \leq \frac{1}{2}$ or $\frac{g_i}{\ln p_i} \geq 2$.
Define $\#(n) = \frac{1}{n}\sum \limits_{i=1}^{n} T(i)$
For instance :
$\#(10)=0.1$ , $\#(100) = 0.27$, $\#(1000) =0.354 $, $\#(10000) =0.3474 $.
Now its trivial to bound $0 \leq \#(n) \leq 1$, but is there a better lower and upper bound ?
Edit : one can assume R.H. or any conjecture in number theory that could help make the bounds stricter even if the conjecture is not solved.
Thanks in advance.

A: For clarity I put my (corrected) comments here :

*

*I doubt there are many useful proven results.

*I would look at the random model (*) underlying Cramer's conjecture :  $X_n=1_{n \text{ is prime}}$ is a sequence of independent random variables with $P[X_n=1]=\frac{1}{\log n}$ so that $G(k)$ the $k$-th gap follows approximately a geometric distribution of parameter $1−\frac{1}{\log k}$.   $({}^*)$ of course this is just a model, not the truth)
We obtain that the mean and standard deviation of $G(k)$ is $\log k$, thus about  $\text{erf}(1/\sqrt{2}) \approx 0.68$ of gaps are within $[\frac{\log k}{2},\frac32 \log k]$ (under this model).

*The PNT almost doesn't prove anything about gaps (they could all fall  in $[0,200]$ or $[o(\frac{k}{\log^m k}),2\, o(\frac{k}{\log^m k})]$) and the RH only improves $o(\frac{k}{\log^m k})$ to $o(k^{1/2+\epsilon})$

*About the series we are interested in $\sum_{k=1}^\infty (-1)^k \frac{k}{p_k}=\sum_k \frac{k g_{k}-p_k}{p_kp_{k+1}}$ I'd say its convergence depends on how fast the observed values of $\frac{g_k-\log k}{ \log k}$ converges in distribution to a centered Gaussian of variance $\sigma$ (the model predicts $\sigma=1$)


text:
Q: при подключении БД SQLite к Активити не виден класс создан класс TestDataBaseHelper extends SQLiteOpenHelper. В MainActivity в методе onCreate() делается попытка создания объекта этого класса, но Андроид студия ругается, что не видит этого класса и предлагает создать. почему так происходит?
вот кусок кода класса TestDataBaseHelper:
public class TestDataBaseHelper extends SQLiteOpenHelper {

    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "test.db";

    TestDataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE TEST (_id INTEGER PRIMARY KEY AUTOINCREMENT,"+"NAME TEXT);");
        insertTest(db,"Alexandr");
        insertTest(db,"Peter");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onCreate(db);
    }

   private static void insertTest(SQLiteDatabase db, String name){
       ContentValues testValues = new ContentValues();
       testValues.put("NAME", name);
       db.insert("TEST", null, testValues);
   }
}

кусок кода MainActivity:
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SQLiteOpenHelper testDataBaseHelper = new TestDataBaseHelper(this);
        SQLiteDatabase db = testDataBaseHelper.getWritableDatabase();
    }

A: Скорее всего у вас класс TestDataBaseHelper храниться в другом пакете.
добавьте модификатор к вашему конструктору.
    public TestDataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


text:
Q: Check who / when EC2 instance was assigned a security group I'm pretty new to EC2 so apologies if this is trivial but I can't seem to find an answer from Google.  I have a EC2 instance that was in a security group it should not have been in.  Whilst I have fixed the groups I would like to know which user assigned the group and when it was done, Is it possible to get this info or is it not logged anywhere?

A: What you need is called AWS CloudTrail https://aws.amazon.com/cloudtrail/
CloudTrail will create log files with (almost) all API calls in your AWS environment, including instances/security group modifications. Going through those logs might be challenging and time-consuming, but that's the only way.

A: AWS Config is another service that could help with this. I'm not 100% sure it will go to the level of detail you need, but it's worth considering / looking at. It seems to have a better UI than CloudTrail.
There are likely services or products that will help understand CloudTrail logs. They may be commercial.


text:
Q: Why is the base class of `plugin` between Play 1 and Play 2 so different? The plugin base class in Play 1, is play.PlayPlugin, which has a lot of methods (fields):
index : int
onLoad()
compileSources()
runTest(Class<BaseTest>)
bind(String, Class, Type, Annotation[], Map<String, String[]>)
bind(RootParamNode, String, Class<?>, Type, Annotation[])
bind(String, Object, Map<String, String[]>)
bindBean(RootParamNode, String, Object)
unBind(Object, String)
getMessage(String, Object, Object...)
getStatus()
getJsonStatus()
enhance(ApplicationClass)
onTemplateCompilation(Template)
rawInvocation(Request, Response)
serveStatic(VirtualFile, Request, Response)
beforeDetectingChanges()
loadTemplate(VirtualFile)
detectChange()
detectClassesChange()
onApplicationStart()
afterApplicationStart()
onApplicationStop()
beforeInvocation()
afterInvocation()
onInvocationException(Throwable)
invocationFinally()
beforeActionInvocation(Method)
onActionInvocationResult(Result)
onInvocationSuccess()
onRequestRouting(Route)
afterActionInvocation()
onConfigurationRead()
onRoutesLoaded()
onEvent(String, Object)
onClassesChange(List<ApplicationClass>)
addTemplateExtensions()
addMimeTypes()
compileAll(List<ApplicationClass>)
routeRequest(Request)
modelFactory(Class<? extends Model>)
afterFixtureLoad()
postEvent(String, Object)
onApplicationReady()
compareTo(PlayPlugin)
overrideTemplateSource(BaseTemplate, String)
willBeValidated(Object)

And Play 2's is play.api.Plugin, which is very simple:
onStart(): Unit
onStop(): Unit
enabled: Boolean

Why are they so different? And I think the methods in plugin class of Play 1, are defined as extension-points, aren't they not needed anymore for Play 2?

A: Play 2.0 differentiates global settings and plugins.
Global settings are specific to an application and allows to customize some behavior of the framework (e.g. what should be done if no action were found for a request). Actually most of the extension points of Play 1.x plugins are now in Play 2.x global settings.
Plugins are modules which may need to be aware of the application lifecycle to perform initialization/cleaning operations.


text:
Q: Show a winform over the notification area I want to show a winform in the very right down corner just above the system tray,
How do I do that? Here is my code:
public static void Notify()
{
    Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
    Form fm = new Form();
    fm.ClientSize = new Size(200, 200);
    int left = workingArea.Width - fm.Width;
    int top = workingArea.Height - fm.Height;
    fm.Location = new Point(left, top);
    fm.ShowInTaskbar = false;
    fm.ShowIcon = false;
    fm.MinimizeBox = false;
    fm.MaximizeBox = false;
    fm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
    fm.Text = "Test";
    fm.TopMost = true;
    fm.Show();
}

A: I just tried this and it worked for me (note: this code must appear after the form has been displayed for the first time -- for example, you can put it in the form's Load event handler, or simply include it after any call to Show):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
int left = workingArea.Width - this.Width;
int top = workingArea.Height - this.Height;

this.Location = new Point(left, top);

Whether to use WorkingArea or Bounds depends on what you mean by "over": if you mean "in front of," then use Bounds, as it includes the area covering the entire screen (including that space occupied by the system tray); if you mean "above," then use WorkingArea, which just includes the user's desktop.
Also let me just clarify that you want your actual form displayed down there, right? If you wanted an icon in the notification area, that's what the NotifyIcon component is for.

A: You forgot this one:
        fm.StartPosition = FormStartPosition.Manual;

What you'll have to work on next is putting the taskbar at, say, the left side of the screen and running the code on a machine that has the video DPI setting at a different value (like 125).  You can only position the form accurately in its Load event.  Don't set the client size.

A: If you wanted to position the form over/infront of the taskbar:
Set the forms TopMost property to true. You can use Screen.PrimaryScreen.Bounds to get the screen resolution then set your forms position appropriately.

If you just want to position the form just above the taskbar in the bottom right then you can do as follows:
In the form designer, goto Properties->Events and add the Load event to your form.
Add the following:
private void Form1_Load(object sender, EventArgs e)
{
    this.StartPosition = FormStartPosition.Manual;
    int x = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
    int y = Screen.PrimaryScreen.WorkingArea.Height - this.Height;
    this.Bounds = new Rectangle(x, y, this.Width, this.Height);
}


text:
Q: Caused by: java.io.NotSerializableException: org.apache.kafka.clients.producer.KafkaProducer I try to send the java String messages with kafka producer. And String messages are extracted from Java spark JavaPairDStream.
JavaPairDStream<String, String> processedJavaPairStream = inputStream.mapToPair
                 (record-> new Tuple2<>(record.key(), record.value())).mapValues(message -> message.replace('>', '#'));

String outTopics = "outputTopic";
String broker = "localhost:9092";

Properties properties = new Properties();
properties.put("bootstrap.servers", broker);
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<String, String>(properties);
processedJavaPairStream.foreachRDD(rdd -> rdd.foreach(tuple2 -> {

    ProducerRecord<String, String> message = new ProducerRecord<String, String>(outTopics, tuple2._1, tuple2._2);

    System.out.println(message.key() + " : " + message.value()); //(1)

    producer.send(message).get(); //(2)
}));

(1) line print the message string correctly. But when I send these messages with kafka producer like (2) line, it throws the exception like below,
Caused by: java.io.NotSerializableException: org.apache.kafka.clients.producer.KafkaProducer
Serialization stack:
    - object not serializable (class: org.apache.kafka.clients.producer.KafkaProducer, value: org.apache.kafka.clients.producer.KafkaProducer@10f6530d)
    - element of array (index: 1)
    - array (class [Ljava.lang.Object;, size 2)
    - field (class: java.lang.invoke.SerializedLambda, name: capturedArgs, type: class [Ljava.lang.Object;)
    - object (class java.lang.invoke.SerializedLambda, SerializedLambda[capturingClass=class com.aaa.StreamingKafkaDataWithSpark.streaming.SimpleDStreamExample, functionalInterfaceMethod=org/apache/spark/api/java/function/VoidFunction.call:(Ljava/lang/Object;)V, implementation=invokeStatic com/aaa/StreamingKafkaDataWithSpark/streaming/SimpleDStreamExample.lambda$3:(Ljava/lang/String;Lorg/apache/kafka/clients/producer/Producer;Lscala/Tuple2;)V, instantiatedMethodType=(Lscala/Tuple2;)V, numCaptured=2])
    - writeReplace data (class: java.lang.invoke.SerializedLambda)
    - object (class com.aaa.StreamingKafkaDataWithSpark.streaming.SimpleDStreamExample$$Lambda$941/0x000000010077e440, com.aaa.StreamingKafkaDataWithSpark.streaming.SimpleDStreamExample$$Lambda$941/0x000000010077e440@7bb180e1)
    - element of array (index: 0)
    - array (class [Ljava.lang.Object;, size 1)
    - field (class: java.lang.invoke.SerializedLambda, name: capturedArgs, type: class [Ljava.lang.Object;)
    - object (class java.lang.invoke.SerializedLambda, SerializedLambda[capturingClass=interface org.apache.spark.api.java.JavaRDDLike, functionalInterfaceMethod=scala/Function1.apply:(Ljava/lang/Object;)Ljava/lang/Object;, implementation=invokeStatic org/apache/spark/api/java/JavaRDDLike.$anonfun$foreach$1$adapted:(Lorg/apache/spark/api/java/function/VoidFunction;Ljava/lang/Object;)Ljava/lang/Object;, instantiatedMethodType=(Ljava/lang/Object;)Ljava/lang/Object;, numCaptured=1])
    - writeReplace data (class: java.lang.invoke.SerializedLambda)
    - object (class org.apache.spark.api.java.JavaRDDLike$$Lambda$942/0x000000010077c840, org.apache.spark.api.java.JavaRDDLike$$Lambda$942/0x000000010077c840@7fb1cd32)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:41)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:400)
    ... 30 more
Exception in thread "main" org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:393)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)
    at org.apache.spark.rdd.RDD.$anonfun$foreach$1(RDD.scala:926)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
    at org.apache.spark.rdd.RDD.foreach(RDD.scala:925)
    at org.apache.spark.api.java.JavaRDDLike.foreach(JavaRDDLike.scala:351)
    at org.apache.spark.api.java.JavaRDDLike.foreach$(JavaRDDLike.scala:350)
    at org.apache.spark.api.java.AbstractJavaRDDLike.foreach(JavaRDDLike.scala:45)
    at com.aaa.StreamingKafkaDataWithSpark.streaming.SimpleDStreamExample.lambda$2(SimpleDStreamExample.java:72)
    at org.apache.spark.streaming.api.java.JavaDStreamLike.$anonfun$foreachRDD$1(JavaDStreamLike.scala:272)
    at org.apache.spark.streaming.api.java.JavaDStreamLike.$anonfun$foreachRDD$1$adapted(JavaDStreamLike.scala:272)
    at org.apache.spark.streaming.dstream.DStream.$anonfun$foreachRDD$2(DStream.scala:628)
    at org.apache.spark.streaming.dstream.DStream.$anonfun$foreachRDD$2$adapted(DStream.scala:628)
    at org.apache.spark.streaming.dstream.ForEachDStream.$anonfun$generateJob$2(ForEachDStream.scala:51)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.streaming.dstream.DStream.createRDDWithLocalProperties(DStream.scala:416)
    at org.apache.spark.streaming.dstream.ForEachDStream.$anonfun$generateJob$1(ForEachDStream.scala:51)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at scala.util.Try$.apply(Try.scala:213)
    at org.apache.spark.streaming.scheduler.Job.run(Job.scala:39)
    at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler.$anonfun$run$1(JobScheduler.scala:257)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:62)
    at org.apache.spark.streaming.scheduler.JobScheduler$JobHandler.run(JobScheduler.scala:257)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

I can not understand this exception. I confirm the kafaka producer messages are <String,String> type with line (1). But why does line (2) throw this exception? Do I miss any process?

A: You need to create the producer for each RDD.
RDDs are distributed over multiple executors, and a Producer object cannot be serialized to be shared amongst them

Alternatively, look at the documentation of Structured Streaming and you could simply do this to write into a topic; no need to create and send records yourself
stream.writeStream().format("kafka")...

Note that if the goal is simply to map one topic into another, Kafka Streams API
is much simpler and less overhead than Spark


text:
Q: How to find the values of $\alpha$ for which the integral converges? $$\displaystyle\int_{0}^{1}\dfrac{\arctan^\alpha (x^2-x^3)}{(\ln x)^2\cos(\frac{\pi x}{2})^{2\alpha-1}}\,dx$$
i was trying to use taylor series expansion  to solve it , but having difficulty after some steps because it becomes to messy , any help will be appreciated thanks !

A: HINT:
Note that as $x\to 1$, $\log(x)\sim x-1$, $\arctan(x^2-x^3)\sim 1-x$, and $\cos(\pi x/2)\sim 1-x$.
And as $x\to 0$, $\arctan(x^2-x^3)\sim x^2$.


text:
Q: Linq to Entities Non-Equal Join I must perform the following SQL command using IQueryable:
SELECT * FROM myTable t1
    INNER JOIN myTable t2 ON t1.time = t2.time + 1
        OR t1.time = t2.time + 2
        OR t1.time = t2.time + 3;

Linq to Entities does not allow me to use IEqualityComparer, so I'm looking for some way to accomplish this Join.
Must use IQueryable and can not put conditions via Where as myTable has millions of records and implementation would be very slow:
qry = qry.Join(...).Where(...);

I need
qry = qry.Join(...);

Is there an alternative like IEqualityComparer for Linq to Entities?
Thank you!
Sorry my bad english!

A: I am not sure if this works with Lambda-Expression, but you can use Linq to achieve that:
var l = from i1 in conn.List1
    from i2 in conn.List2
    where
    (
        i1.time == i2.Time + 1
        || i1.time == i2.Time + 2
        || i1.time == i2.Time + 3
    )
    select new { i1, i2 }

Try also following:
var l = from i2 in conn.List2.Where(x =>  i1.time == x.Time + 1
                                    || i1.time == x.Time + 2
                                    || i1.time == x.Time + 3)
select new { i1, i2 }

A: Linq only supports equi-joins, so you will need to do this through a where clause.
That said, I would not expect a significant performance difference between a compound inner join and using a where clause - SQL should create similar (if not equal) plans for the following two queries:
SELECT *
FROM myTable t1
INNER JOIN myTable t2 ON t1.time = t2.time + 1
    OR t1.time = t2.time + 2
    OR t1.time = t2.time + 3;

SELECT *
FROM myTable t1 ,
myTable t2
WHERE t1.time = t2.time + 1
    OR t1.time = t2.time + 2
    OR t1.time = t2.time + 3;


text:
Q: Advanced custom fields doesn't show after custom post type, how can I make this work? I have multiple fields from Advanced Custom Fields (wordpress plugin) that work fine on the website. I have 1 custom post type that is displayed also perfectly fine. The problem is that after the custom post type, my Advanced Custom Fields field doesn't appear anymore. The plugin seems to collide with the custom post type. If I post the field to be displayed before the custom post type it works again, but that's not an option.

 <?php
        $query = array (
            'post_type' => 'dates',
            'order' => 'ID',
            'posts_per_page' => 8
        );

        $queryObject = new WP_Query($query);
        if ( $queryObject->have_posts() ): while ( $queryObject->have_posts() ): $queryObject->the_post(); ?>

        <?php $begindatum = get_post_meta( $post->ID, 'begindatum', true ); $begindatum = str_replace('(', '
(', $begindatum); echo str_replace(')', ')', $begindatum); ?>

 -

        <?php $einddatum = get_post_meta( $post->ID, 'einddatum', true ); $einddatum = str_replace('(', '
(', $einddatum); echo str_replace(')', ')', $einddatum); ?>

<?php $price = get_post_meta( $post->ID, 'price', true ); $price = str_replace('(', '
(', $price); echo str_replace(')', ')', $price); ?>

<?php $period = get_post_meta( $post->ID, 'period', true ); $period = str_replace('(', '
(', $period); echo str_replace(')', ')', $period); ?>

<?php endwhile; endif; ?>

Foto's

        <?php the_field('galerij-homepage'); ?>

This is the code. the $query is where my custom post type starts. The Advanced Custom Field that is not working is <?php the_field('galerij-homepage'); ?> I'm literally tied and I can't seem to fix this problem. is it just not possible or am I missing something?

A: The guy that posted under my comment solved it. I had to reset the query before the ACF field.
<?php wp_reset_query(); ?>

That was all.


text:
Q: Angular validation FormControl start input class as ngvalid but it's still unused After start FormControl to my form, they marked in green with ng-valid but didn't use it yet.
When writing text and clear the input it's go ng-invalid as needed and when the input is OK the ng-valid is back as needed.
How to start the fields without ng-valid ? No need any class in this input until it dirty.
Here is my html: (you can see validate need to work only after using one of the fields)
<form [formGroup]="mainForm">

              ID
              <input
              type="text"
              class="form-control"
              id="customerId"
              formControlName="customerId"
              (click)="validate()"
              placeholder="e.g 123456789">
              ID is important, numbers only!

              First Name
              <input
              type="text"
              class="form-control"
              id="firstName"
              name="firstName"
              formControlName="firstName"
              (click)="validate()"
              placeholder="First Name">
            First name invalid, try again

</form>

Here is my component:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms'

@Component({
  selector: 'new-customer',
  templateUrl: './new-customer.component.html',
  styleUrls: ['./new-customer.component.scss']
})
export class NewCustomerComponent implements OnInit {
  mainForm = new FormGroup({
    customerId: new FormControl(),
    firstName: new FormControl()
  });

  constructor() {}

  ngOnInit(): void {

  }

  get customerIdInvalid(){
    return this.mainForm.get('customerId')?.invalid;
  }

  get firstName(){
    return this.mainForm.get('firstName')
  }

  validate(){
    this.mainForm.get('customerId')?.setValidators([Validators.required , Validators.pattern(/^-?([0-9]\d*)?$/) , Validators.minLength(6)]);
    this.mainForm.get('firstName')?.setValidators([Validators.required , Validators.pattern('^[a-zA-Z]+$') , Validators.minLength(2)]);

  }
}

A: I change my component to:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms'

@Component({
  selector: 'new-customer',
  templateUrl: './new-customer.component.html',
  styleUrls: ['./new-customer.component.scss']
})
export class NewCustomerComponent implements OnInit {

  mainForm = new FormGroup({
    customerId: new FormControl('',[Validators.required , Validators.pattern(/^-?([0-9]\d*)?$/) , Validators.minLength(6)]),
    firstName: new FormControl('',[Validators.required , Validators.pattern('^[a-zA-Z]+$') , Validators.minLength(2)])
  });

  constructor() {}

  ngOnInit(): void {

  }

  get customerId(){
    return this.mainForm.get('customerId');
  }

  get firstName(){
    return this.mainForm.get('firstName')
  }

  onSubmit(){
    console.log(this.mainForm.valid);
    if(this.mainForm.valid){
      console.log(this.mainForm.value);

    }
  }
}

So now all my css with .ng-invalid changed to .ng-dirty.ng-invalid
In that way I will assure only inputs that used will be mark red.


text:
Q: 2N7000 level shifter doesn't work under a certain voltage I need to convert a 1.8V UART line to 3.4V.
I don't have the 1.8V voltage reference available, but I have the 3.4V reference, so I'm using a voltage divider to get about 1.8V.
This is my circuit:

However, it doesn't work for Vcc = 3.4V. In fact, it only works for Vcc > ~5V.
Why's that?

A: The 2N7000 datasheet I just looked at shows a \$V_{GS(th)}\$ with a minimum of 0.8V and a maximum of 3.0V. When \$V_{TX1.8} = 0V\$, I'd imagine you'd want \$V_{GS} \ge 3.0V\$ so that you can expect the 2N7000 to be ON and pulling down on the 10k\$\Omega\$ output pull-up and presenting about 0V at the \$V_{TX3.4}\$ side of things. Then when \$V_{TX1.8} = 1.8V\$, I'd imagine you'd want \$V_{GS} \le 0.8V\$ so that you can expect the 2N7000 to be OFF and allowing the 10k\$\Omega\$ output pull-up to do its job and present about 3.4V at the \$V_{TX3.4}\$ side of things. Isn't that about it?
The problem is that you can't easily have both cases here, if you can only set the gate voltage with a resistor divider. You'd need to have \$V_G \ge 3.0V\$ in one case and \$V_G \le 2.6V\$ in the other case. So if I were stuck with the 2N7000 and planning on shooting for a circuit that will probably work okay, I'd probably give up and set \$V_G \approx 2.5V\$ and just go with that.
This brings up another thing. You've got a 10k\$\Omega\$ resistor going from the resistor divider node back to the \$V_{TX1.8}\$ node (source.) Why? This actually moves the gate closer to ground at a time when you'd like it further away, and visa versa. I think I'd dump that. It could just be that I'm ignorant (I'm just a hobbyist and have no formal training at all in electronics.) But it doesn't make any sense to me, right now. It actually seems to push things the wrong way -- to me, anyway.
So perhaps try something like this?

simulate this circuit – Schematic created using CircuitLab
Now:
\$V_{TX1.8} = 0V \rightarrow V_{GS} = 2.45V\$, transistor is \$\approx\$ ON
\$V_{TX1.8} = 1.8V \rightarrow V_{GS} = 0.65V\$, transistor is \$\approx\$ OFF
Which I think should do about what you want.

A: It looks like you are trying to implement the famous upside-down FET level shifter circuit. But there are some mistakes. Here is a link to where it is done correctly:

Note that they use the BSS138 which is definitely a better choice (works at lower voltages). They connect the source to the low-voltage side and the drain to the high voltage side (opposite of what you have drawn). The gate is directly connected to the low-voltage power rail (you connected to high side with voltage divider).
If you fix the mistakes, even the 2N7000 may work, but at 1.8V, it is definitely marginal.


text:
Q: Trying to upsize from Access tables to SQL Server linked tables. Code works fine with Access but gives a "ODBC call failed 3146" when connected to SQL Public Sub UpdateTermFeedbackAddlReqt(ByVal runid As Integer, ByVal BHTerm As String, ByVal username As String, ByVal currtime As Double)
    Dim db As DAO.Database
    Dim rs As DAO.Recordset

    DoCmd.SetWarnings False

    Set db = CurrentDb

    sql = "SELECT tbl_SCG_ExpectedTraffic.BHTerm, Sum(tbl_SCG_ExpectedTraffic.CurrSent2) AS SumOfCurrSent2, iif(Sum([CurrSent2]) = 0, 0, Sum([Accepted])/Sum([CurrSent2])) AS [Term Accept Rate], Sum(tbl_SCG_ExpectedTraffic.Accepted) AS SumOfAccepted, Sum(tbl_SCG_ExpectedTraffic.Rejected) AS SumOfRejected, Sum(tbl_SCG_ExpectedTraffic.Modified) AS SumOfModified, Sum(tbl_SCG_ExpectedTraffic.CurrCalledin) AS SumOfCalledin, Sum([ExpTotal])-Sum([CurrSent2]) AS [Need to Send]" & _
    " FROM tbl_SCG_ExpectedTraffic" & _
    " GROUP BY Date(), tbl_SCG_ExpectedTraffic.BHTerm, tbl_SCG_ExpectedTraffic.OptRunID" & _
    " HAVING (((tbl_SCG_ExpectedTraffic.OptRunID)=" & runid & ") And BHTerm= """ & BHTerm & """);"
    Set rs = db.OpenRecordset(sql, dbOpenDynaset, dbSeeChanges)
    DoCmd.RunSQL ("Update tbl_SCG_TerminalFeedback set [CurrentSend2] = " & rs![SumOfCurrSent2] & ", [Term Accept Rate] =" & rs![Term Accept Rate] & ", Accepted= " & rs![SumOfAccepted] & ", Rejected = " & rs![SumOfRejected] & ", Modified =" & rs![SumOfModified] & ", Calledin = " & rs![SumOfCalledin] & ", AddlReqst =" & rs![Need To Send] & _
    ",[Last Update User] =""" & username & """, [Last Update Time]= " & currtime & " , HrDiff = iif( isnull(DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID = " & runid & """)), 0, Round((" & currtime & " - DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID =" & runid & """)) * 24, 1))" & _
    " where OptRunID = " & runid & " And Term = """ & BHTerm & """")

    DoCmd.SetWarnings True

    rs.Close
    db.Close

End Sub


text:
Q: Sencha Ext.Loader.setPath() is undefined When I use sencha CMD (I have tried 4 and 5 with similar results), I get an error on loading app like:
Uncaught TypeError: Cannot read property 'setPath' of undefined

This error is referring to: Ext.Loader.setPath(), but also fires on Ext.application, and Ext.Loader.setConfig( if I re-order them.
There are no errors before or after this, it loads fine when loading without building, produces same results with production and development microloaders.
Any thoughts?
<!DOCTYPE HTML>

    <meta charset="UTF-8">


text:
Q: Weird output in tortoisehg log window I have two branches, the main branch(black) and a feature branch(yellow).
As you can see, since the feature branch was forked, it was kept up to date fetching changes from main:
alt text http://azkotoki.org/images/stackoverflow/tgh-reintegrate1.gif
When I reintegrate back the feature branch to the main one, the log window shows this ugly graph:
alt text http://azkotoki.org/images/stackoverflow/tgh-reintegrate2.gif
It shows each merge point as a new branch that was merged with the feature branch. If I had several feature branches this would became almost impossible to read. I also tried with hg view and the results are even weirder.
Regardless the picture shown above, the final merge results are fine, but the graph with the reintegrated branch annoys me.
Am I doing something wrong by merging to the feature branch too many times? Or I expect too much from tortoisehg's log window :) ?
Thanks in advance

A: The graph looks like this since the revisions are ordered by their revision numbers. The main repository has the revisions ordered and numbered like this:
0 Imported initial repo.
1 Trivial change to also echo b.
2 Added another echo for c.
3 Echo for d.
4 Echo for e.

This reflects the order in which the changesets were added to the repository. The feature branch repository has this order:
0 Imported initial repo.
1 Trivial change to also echo b.
3 Added another echo for c.
4 Automatic merge...
5 Echo for d.
6 Automatic merge...
7 Echo for e.
8 Automatic merge...

Again everything is ordered nicely. But when you pull the feature branch into the main repository only the missing changesets are added. The result in main is thus:
0 Imported initial repo.
1 Trivial change to also echo b.
2 Added another echo for c.
3 Echo for d.
4 Echo for e.
5 Refactored echos to print.
6 Automatic merge...
7 Automatic merge...
8 Automatic merge...

and the graph reflects this.
As you note, the repository is fine -- this is only an artifact of how the changesets are ordered on disk. If you want, you could swap the repository with the nice graph for the one with the ugly graph since they now contain the same changesets. Just remember to move any important settings from .hg/hgrc (copy the file from the clone with the ugly graph).
By the way, when I look at the graph in my clone of http://hg.intevation.org/mercurial/crew/ (the development branch for Mercurial) and compare it to the graph in a fresh clone of https://www.mercurial-scm.org/repo/hg (the main branch for Mercurial) I see the same phenomenon.

A: One way to get a "nicer" graph would be to use the pre 2.0 TortoiseHg which had a compact graph mode. In this mode your second repository would have just two columns of lines, similar to what is in your first screenshot.
Unfortunately this feature has not been ported from GTK to Qt, so it is not present in the current version (2.1.2) of TortoiseHg.

A: When you take a closer look you will see that the both graphs are (almost) identical, but the presentation is different. That, which looks like 3 different branches, is actually one branch, but presented slightly different.
I wrote "almost" because revision numbers have been reordered. And this is really strange...