text:
Q: Poco C++ websockets - how to use in non-blocking manner? I am using the Poco C++ libraries to setup a websocket server,  which clients can connect to and stream some data to their webinterface. So I have a loop which continuously sends data and I also want to listen if the clients closes the connection by using the receiveFrame() function, for the rest, the client is totally passive and doesn't send any data or whatsoever. The problem is that receiveFrame() blocks the connection, which is not what I want. I basically want to check if the client has not yet called the close() javascript function and stop streaming data if it has. I tried using
ws.setBlocking(false);

But now receiveFrame throws an exception every time it is called. I also tried removing receiveFrame entirely, which works if the connection is terminated by closing the browser but if the client calls the function close(), the server still tries to send data to the client. So how can I pull this off? Is there somehow a way to check if there are client frames to be received and if not to just continue?

A: You can repeatedly call Socket::select() (with timeout) in a separate thread; when you detect a readable socket, call receiveFrame(). In spite of the misleading name, Socket::select() call wraps epoll() or poll() on platforms where those are available.
You can also implement this in somewhat more complicated but perhaps a more elegant fashion with Poco::NotificationQueues, posting a notification every time when a socket is readable and reading data in the handler.

A: setBlocking() does not do what you would expect it to. Here's a little info on it:
http://www.scottklement.com/rpg/socktut/nonblocking.html
What you probably want to do is use setReceiveTimeout() on your socket to control how long it will wait for before giving you back control. Then test your response and loop everything if needed. The Poco docs have more info on how to use that part of the API. Just look up WebSockets.


text:
Q: Akka stream equivalent of flatmap operator in RxJava I have a background in RxJava and now I am getting started using Akka Streams.
When I need to compose a stream with the result of the first stream in RxJava, I usually do the following:
val fooBarObserable = fooObservable.flatmap { foo ->
   return barObservable.map { bar -> someOperation (foo, bar) }
}

In this example, fooObservableemits Foo type, barObservable emits Bar type and fooBarObserable emits FooBar type.
obs:

*

*Observable is very similar to Source in Akka Streams.

*barObservable will be a Flow

So what's the easy way to compose a stream like that in Akka?

A: you can use flatMapConcat, as follows :

  final case class Foo(a: String)
  final case class Bar(a: String)

  val fooSource = Source(List(Foo("q-foo"), Foo("b-foo"), Foo("d-foo")))
  val barSource = Source(List(Bar("q-bar"), Bar("b-bar"), Bar("d-bar")))

  private val value: Source[String, NotUsed] = fooSource.flatMapConcat(foo => {
    barSource.map(bar => {
      foo.a + bar.a
    })
  })

Running this : value.runWith(Sink.foreach(println)) will yield :
q-foo q-bar
q-foo b-bar
q-foo d-bar
b-foo q-bar
b-foo b-bar
b-foo d-bar
d-foo q-bar
d-foo b-bar
d-foo d-bar

A: Caveat: I'm not quite familiar with the RxJava so I may misunderstand what semantics it is you are after.
As a flow is not terminated you couldn't really combine its output with a source in the style of fooSource.operation(barFlow) as that wouldn't give you a reasonable graph of stages back - you'd first need to provide a barSource and combine the barFlow with that.
You could compose it the other way around though, for example like this:
val barFlow: Flow[Bar, Bar, NotUsed] = ???
val fooSource: Source[Foo, NotUsed] = ???

val fooToBarFooPairsFlow: Flow[Bar, (Bar, Foo), NotUsed] =
  barFlow.zip(fooSource)

Which would tuple up pairs of values of foo and bar let you later run it with a barSource.via(fooToBarFooPairsFlow).map { case (bar, foo) => op(bar, foo) }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity C#, Using LINQ on multiple target platforms Is there any way in Unity of defining resources for a particular platform that should be ignored by Unity when on another build platform?
I like to use LINQ, but when my target is the Web Player I get the error message:
error CS0234: The type or namespace name `Linq' does not exist in the namespace `System.Xml'. Are you missing an assembly reference?

I can solve this by copying the System.Xml.Linq.dll to my Plugins folder, and now Unity knows about LINQ.
Then when I switch target to Android I get the error message:
error CS0433: The imported type `System.Xml.Linq.XDocument' is defined multiple times

Which is resolved by deleting System.Xml.Linq.dll from the Plugins folder.
I'd like Unity to ignore System.Xml.Linq.dll when on Android and notice it when on Web Player target.
A solution for getting Unity to see LINQ when on Web Player platform without copying the DLL into the project, would also be fine.
Thanks in advance

A: there is this in the unity docs:
http://docs.unity3d.com/Manual/PlatformDependentCompilation.html


text:
Q: Bootstrap 3.0 col border issue This seems like a ridiculous issue, but I can't seem to resolve it.
In Bootstrap 3.0, I'm simply using columns with a 1 pixel border.  Sometimes the border shows, but other times you have change the browsers window to see the border.
Since all the columns are in percentages, adding 1px border seems to be causing an issue.
Any advice?


text:
Q: How to force Jest to exit a certain test file I have a few e2e tests, one of them hangs and we can't find out why, so we want to use --forceExit. But, we don't want to force exit all the tests just a particular one because we use github actions + npm script to run these e2e tests.
How would I do that?

A: Hard to help without further information on your part.
However, if you want to quit a running test, you can always use a return statement.
For example (all tests should pass):
describe("exit a test", () => {
  it("good test 1", () => {
    const aSum = 1;

    expect(aSum).toBe(1);
  });

  it("uses a flag and a return statement to prevent test from failing", () => {
    const flag = true;

    if (flag) {
      return;
    }

    expect(flag).toBeFalsy();
  });

  it("good test 2", () => {
    const aSum = 1;

    expect(aSum).toBe(1);
  });
});


text:
Q: python use the output of a class inside another class I have the structure of a code described below which is made of two classes. What I want to do is to use the returned value from  classname1 and all its methods inside the classname2.
I would appreciate your help.
class   classname1(someObject):

      def __init__(self, someInput1):
           self.someInput = someInput

      def someMethod (self):
          'code '
          return something

class  classname2(someObject):

       def init(self, someInput2)
            self.someInput2 = someInput2

       def AnotherMethod(self):

       use the returned value from the first class

A: Instead of returning the value to class-2, you can probably:
       create instance of class 2 in class 1 & pass return value as argument to function in class 2.
eg:
class   classname1(someObject):
      def __init__(self, someInput1):
           self.someInput = someInput
      def someMethod (self):
          'code '
          //here create instance/object of class 2
          //pass the return value to another method of class 2

class  classname2(someObject):
       def init(self, someInput2)
            self.someInput2 = someInput2
       def AnotherMethod(self):
        // here receive the return value (from class 1) as one of the arguments.

or you can do it vice-versa:
class   classname1(someObject):
      def __init__(self, someInput1):
           self.someInput = someInput
      def someMethod (self):
          'code '

class  classname2(someObject):
       def init(self, someInput2)
            self.someInput2 = someInput2
       def AnotherMethod(self):
        //here create instance/object of class 1
        //val num=class1Object.someMethod()

Good Luck!

A: To get all methods of Classname1, Inherit it by
class Classname2(Classname1):

For example
class A:

    def __init__(self, someInput1):
        self.someInput1 = someInput1

    def someMethod1(self):
        return "something1"

class B(A):

    def __init__(self, someInput2):
        self.someInput2 = someInput2

    def someMethod2(self):
        return "something2"

temp1 = B("ccc")
print(temp.someMethod1())
print(temp1.someMethod2())

#output
something1
something2

To call method of class A in class B
class B(A):

    def __init__(self, someInput2):
        self.someInput2 = someInput2

    def someMethod2(self):
        return self.someMethod1() # someMethod1 is method of A which is inherited to B

Hope this helps


text:
Q: How to send POST (json file with urls) request via chrome extension to deployed FLASK APP? my Flask app should read urls from news site (urls of articles), and analyze properties of articles (readibility indexes, html properties etc.).
I have no problem with running it locally. I'm using to save urls this Chrome extension (https://chrome.google.com/webstore/detail/tabstore-plugin/jngplpdonggccbjlmbphlbancacmpmpp?hl=en). After clicking on button Save it -it saves all urls of open tabs to json and and after that I run my flask LOCALLY, and it reads these urls from json saved in my PC (and after that I analyze text properties...).
But, in few weeks I would like to deploy my flask (on Heroku/PythonEverywhere/ i just haven't decided where ...) and I realize, it won't work like this, and I need to figure out   how can I send POST request (json file with urls) to Flask app running on server (not locally).
I edited little bit TABS store chrome plugin - I add button to run my flask app (just to open new site == my flask app) and whole process should looks like that I click to Save url and after that I click on button which open new tab with my Flask app (which already get urls from chrome plugin).
EDITED...
I just find out how to show via Flask the ouput (I simulated POST via POSTMAN app) ... there is chunk of my flask app, where I show posted URL.
@app.route('/jsonexample', methods=['POST'])
def jsonexample():
    req_data = request.get_json()
    #json is formatted as list, so we choose 1st element from list
    url_n1 = req_data[0]

    return '''
           The 1st url is: {}
           '''.format(url_n1)

But can somebody help me with POST request in JavaScript??? I am quite newbie in js.
Here is my manifest.json:
{
"update_url": "https://clients2.google.com/service/update2/crx",

  "manifest_version": 2,
  "name": "tabStore_MREVAK_version",
  "description": "This extension will store the urls of all the tabs opened and launch the FLASK  APP",
  "version": "1.0",
  "minimum_chrome_version": "23",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "tabs",
    "notifications",
    "fontSettings"
   ]
}

Here is my popup.html:
<!doctype html>

    <title>tabStore</title>

    <button id="saveActionId"> Save urls </button>
    <button id="btnOpenNewTab"> Click to open App </button>
    <button id="loadActionId"> Load </button>
    <input type="file" id="files" name="files[]" style="visibility: hidden;" multiple />

And there is my whole logic of plugin - popup.js:
document.addEventListener('DOMContentLoaded', function() {

    // Check for the various File API support.
    if (window.File && window.FileReader && window.FileList && window.Blob) {
    //
    } else {
        alert('The File APIs are not fully supported in this browser.');
    }

    // button to open stackoverflow-just placeholder, it will be link on my flask app
    window.addEventListener('DOMContentLoaded', function() {
        // your button here
        var link = document.getElementById('btnOpenNewTab');
        // onClick's logic below:
            link.addEventListener('click', function() {
                var newURL = "http://stackoverflow.com/";
                chrome.tabs.create({ url: newURL });
            });
    });

    var saveActionButton = document.getElementById('saveActionId');
    saveActionButton.addEventListener('click', function() {
        myArray = [];
        chrome.tabs.query({"currentWindow": true},  //{"windowId": targetWindow.id, "index": tabPosition});
        function (array_of_Tabs) {  //Tab tab
            arrayLength = array_of_Tabs.length;
            //alert(arrayLength);
            for (var i = 0; i < arrayLength; i++) {
                myArray.push(array_of_Tabs[i].url);
            }
            obj = JSON.parse(JSON.stringify(myArray));
            //alert(JSON.stringify(obj));
            var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
            var dlAnchorElem = document.getElementById('downloadAnchorElem');
            dlAnchorElem.setAttribute("href",     dataStr     );
            dlAnchorElem.setAttribute("download", "tabs.json");
            dlAnchorElem.click();
        });
    }, false);

    var loadActionButton = document.getElementById('loadActionId');
    loadActionButton.addEventListener('click', function() {
        document.getElementById('files').click();
    }, false);

    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        for (var i = 0, f; f = files[i]; i++) {
            var start = 0;
            var stop = f.size - 1;
            reader = new FileReader();
            //alert(f.name);
            // If we use onloadend, we need to check the readyState.
            reader.onloadend = function(evt) {
                if (evt.target.readyState == FileReader.DONE) { // DONE == 2
                    jsonObj = JSON.parse(evt.target.result);
                    for (var i=0; i<jsonObj.length; i++) {
                         chrome.tabs.create({"url": jsonObj[i]}); //chrome.tabs.create({"url": 'http://www.google.com'});
                    }
                }
            };
            var blob = f.slice(start, stop + 1);
            reader.readAsBinaryString(blob);
        }
    };
    document.getElementById('files').addEventListener('change', handleFileSelect, false);

}, false);


text:
Q: youtube api v3 - get videos from a public playlist. with out using api key Youtube V2 where this code use to list top 50 videos from the play list
        var ytURL = "http://gdata.youtube.com/feeds/api/playlists/PLgtnUFn0ROBBPO2nC-bduEDDlxikKwZ6R?v=2&alt=json&callback=?&max-results=50";

    var thumbBase = "http://img.youtube.com/vi/";

    $.getJSON(ytURL, function (data) {
            $.each(data.feed.entry, function (i, item) {
                var itemTitle = item.title.$t; // Title of the video
                var itemdescription = item.media$group.media$description.$t; //Description of the Video
                itemdescription = itemdescription.replace(/"/g, "");
                var itemdate = item.published.$t;
                var fulldate = new Date(itemdate).toLocaleDateString();

                 var yobject = { 'title': itemTitle, 'description': itemdescription, 'gdate': itemdate };
               localStorage.setItem(videoID, JSON.stringify(yobject));

            });

Same code is not working now, since google update the youtube apis
i have referred the youtube documentation,
after seeing that i came to know to use like this
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLgtnUFn0ROBBPO2nC-bduEDDlxikKwZ6R&key={YOUR_KEY_HERE}&maxResults=50

Problem is, There was public : playlist id "PLgtnUFn0ROBBPO2nC-bduEDDlxikKwZ6R" here.
i want to list all the videos from the playlist without using API key..
how can i access this...
suggest me to how can i overcome from this solution

A: You cannot access even the public youtube data without an API key in v3.
From the docs:

You can request information about information about a channel's public
  playlists without authentication. When you submit an unauthenticated
  request, you need to include the key argument that specifies the
  unique API key for the application making the request. For example,
  this request retrieves the playlists associated with the
  GoogleDevelopers channel.

So you can perform the request to get the playlist data without authenticating the user (no need to go via the OAuth flow), but you still have to supply an API Key for your app (you can generate that in the Google Developer console quite easily). This allows Google to keep track of your app's requests.


text:
Q: Event object in Javascript, trouble finding information I believe there is an object in javascript called event, I see it in some code that wasn't written by me in lines that look something like this:
event.x + document.body.scrollLeft;

I am having trouble finding more out information, furthermore, the object comes up undefined in Firefox. It works fine in all the other browsers. Can anyone provide me with more information? Specifically how do I access this object in Firefox?

A: Official W3c reccomendation
clientX and clientY are the official event property handlers you are looking for. Although you might want to consider screenX and screenY too.

Events (API)
Events
Creating, triggering events
Event handlers
Orientation and motion data

Window Event X and Y property
Explanation
event.x and event.y, what are those?
First of all, the x and y properties are not in all events. It is relative on the event triggered.
Here is an example:
document.body.onclick = function(){console.log(window.event.x)};

If you paste and execute that code in your browser's console, it will log you the x position of the cursor each time you click.

Although taking a look at this example:
document.body.onkeyup = function(){console.log(window.event.x)};

The console will log undefined each and everytime you release a key from your keyboard, since the onkeyup() event does not hold any values for the x and y properties.

A: event (or just e) is a common first parameter name for event handler functions.
In all modern browsers except IE a function registered as an event handler will be passed an Event object as its first parameter containing information about the event.
In IE similar information is available in the global event object (window.event).
Because of these browser differences you will often see event handler boilerplate code such as:
var clicked = function (e) {
  e = e || window.event;  // sets e to window.event if no parameter was passed
};


text:
Q: I designed a touch PCB keypad what can I do for silking and covering I want to design a custom keypad for my board. I put my board in a Plastic box 15cm x 19cm and the box has a simple box door.

I want to put a keypad and a 2x16 character LCD in this door to control the board.the box must be water resist. I want to change or modify this door so that it looks beautiful. currently I want to design a Capacitive touch keypad but what is next or how can I put it in the box. My question is what kind of keypad do you suggests and how much is the cost? I can even change the box if a better suggestion.

A: Let's assume that the box is fully waterproof, I would still recommend using a box as  the one Michel suggested. The main reason for this is the transparant cover. You really don't want to drill holes in the cover and try to make everything water proof so what is easier then mounting everything inside. With the transparant cover you can easily read the lcd and you can mount capacitive buttons on the inside of the lid. Example in figure below. *image taken from Source image

regarding the touch buttons themselves, the capacitive touch buttons are quite easy to do, they are being used extensively for this purpose. I would suggest reading the "TI slaa576a" Design Document Design Document the document describes the theory of operation and the ways you can design your buttons, which materials you can use and so on. As far as IC's go there are lots of options to choose from, fully assembled breakout board based on the "Atmel AT42QT1070" or the "microchip MTCH101" or a lot more options.
Pricing and cost will be determined by your final solution but should definitely not break the bank. The IC's I listed are both available for less then 1 euro.

A: Are you sure your box is waterproof. I would think more like this enclosure box. You have to find one that fits your size better (this one is too small, just as example). It has a rubber inlay, and more important, no holes through the box.
(example picture):

About the LCD, just make sure you glue it very good so it is waterproof. Typically, 1602 and 2004 displays are used, unless you want a graphic screen (OLED maybe).
About the keypad, you cannot use probably ones with feedback/'moving' keys, so a 4x4 keypad might do. Costs: < 1 euro/$.

A: If you can do a bit of micro-controller programming, there is a very neat way to do that with capacitive touch sensing.
You can sense the touch trough plastic, metals like aluminium, glass, keeping the electronic safe from water damage and making the design very simple.
If you don't want to program or do electronics, you can use an evaluation kit which is ready to use.


text:
Q: If $a_i$ is a basis does $\langle f, a_i \rangle =0$ for all $i$ mean that $f=0$? Let $A$ be a set spanned by $a_1, .., a_n$ with an inner product $\langle , \rangle$. If for all $i$ $\langle f, a_i \rangle = 0$, then does it follow that $f=0$?
It's easy to prove this when the basis is orthonormal. How to do it otherwise? please no Gram-Schmidt.

A: If $f=\sum_{j=1}^nf_ja_j$, then $||f||^2=\langle f,f \rangle=\langle f,\sum_{j=1}^nf_ja_j \rangle=\sum_{j=1}^nf_j \langle f,a_j \rangle=0$.
So $||f||=0$, which means that $f=0$.

A: Does $f$ in A? If not $f$ is just orthogonal to A so not necessarily $f=0$.
If it is in A, then $f=\sum_{i=1}^n c_i a_i$ for some $c_i$ from the field. Then we have $\langle f,a_i \rangle=\sum_{j=1}^n c_i\langle a_j,a_i$ which is greater than zero since it has at least one $c_k \neq 0$ hence it has $c_k\langle a_k,a_k \rangle=c_k||a_k||^2 > 0$. Contradiction, so $f=0$ if $f\in A$


text:
Q: Modulo of 24 digit long integer? I need to calculate the modulo of a 24 digit long integer (IBAN checksum) but JS calculates wrong.
e.g.:
700901001234567890131400 % 97 = 90
but in JS (V8) it's 38.
How can I calculate the modulo in JS

A: I think the document you're linking to already says what you should do:

If the application software in use does not provide the ability to handle integers of this size, the modulo operation can be performed in a piece-wise manner.
Piece-wise calculation D mod 97 can be done in many ways. One such way is as follows:

*

*Starting from the leftmost digit of D, construct a number using the first 9 digits and call it N.[Note 3]

*Calculate N mod 97.

*Construct a new 9-digit N by concatenating above result (step 2) with the next 7 digits of D. If there are fewer than 7 digits remaining in D but at least one, then construct a new N, which will have less than 9 digits, from the above result (step 2) followed by the remaining digits of D

*Repeat steps 2–3 until all the digits of D have been processed
  The result of the final calculation in step 2 will be D mod 97 = N mod 97.

A: It might be harder than one can think.
It's quite tricky to ensure javascript handle number as integer (it often store them as float, but not always).
Others already made libraries to handle IBAN check in JS.
Take a look at https://github.com/arhs/iban.js for instance.

A: The largest number that can be represented in javascript is 2^53 - 1. They are 64-bit floating point values. So the largest number is 9007199254740991.
A number greater than 9007199254740991 can not be caclcuted in normal way. So, to find the modulo of such large number you have to break it into pieces.
eg. 700901001234567890131400 can be broken into 700901001234567 and 890131400.
First find the modulo of 700901001234567.
700901001234567 % 97 = 13
Now join 13 infront of second number 13890131400 and find the modulo of this number
13890131400 % 97 = 90

A: I came across this problem recently and this looks like what is solvable with Horner's method [https://en.wikipedia.org/wiki/Horner%27s_method]
/**
*  str is numeric.
*  MOD=97 is our use case
*  @return: an integer 0<=x<=97
**/
int getMod(String str, int MOD) {
    int remainder = 0;
    for(Character c : str.toCharArray()) {
        int value = Character.getNumericValue(c);
        remainder = 10*remainder + value;
        remainder %= MOD;
    }

    return remainder;
}

Unless I don't fully understand the problem, the code above should work.


text:
Q: How to get the parameter sending by post method in php included file? Good day. I am having the following code snippet in init.php.
<?php
include_once("config.php");
include_once(__SITE_PATH . 'view/' . $_REQUEST['page'] . EXT);

$loginobj = new $_REQUEST['page']($_REQUEST['billingentitynuber']);
$text = $loginobj->$_REQUEST['content']();
echo $text;
?>

In Jquery I am having the function Jquery_event.js
$("#entertoapp").click(function()
{
  alert($("#btval").val());
  $.ajax({
    type: "POST",
    url: "init.php?page=processing&content=enterintoapplication&btval=" + $("#btval").val(),

    success: function(msg) {
      alert(msg);
      if(msg==1)
        window.location.href='index.php?page=processing&content=mycontent';
    }
  });
});

In processing.php I am having
<?php
class processing
{
  public function enterintoapplication()
  {
    global $billingentityname;
    $_SESSION['btval'] = $billingentityname;
    echo $billingentityname;
  }
}
?>

My problem is I am getting all the parameters in the init.php. But when I call a function I need to get in the processing.php in the enterintoapplication function (i.e. I am expecting btval in the enterintoapplication function). How can I achieve this? I tried to get $_REQUEST['btval'] within the function. But I didn't get.

A: Try assigning the values to variables, for example this works for PHP 4:
class processing
{
  function enterintoapplication()
  {
    echo "hello";
  }
}

$className="processing";
$functionName="enterintoapplication";

$loginobj=new $className();
$text=$loginobj->$functionName();
echo $text;

Paste it here to verify it works: http://writecodeonline.com/php/
Pls,pay attention to "$functionName", here it keeps the "$".
Nevertheless, for security reasons, you should be attentive to what people can do if they change the value "page".

A: I don't understand your problem correctly, but with some general information, you should get out of this.
$_REQUEST is a superglobal, that means that variable will always be accessible from everywhere within your script. If your problem is you can't find the btval variable that was in your URL, you are doing something else wrong. If your url=http://someUrl/test.php?btval=banana you should always get banana if you evaluate $_REQUEST['btval']. $_SESSION is another superglobal to access the PHP session, and has nothing to do with URL variables.
My guess:
Try changing
$_SESSION['btval'] = $billingentityname;

into
$billingentityname = $_REQUEST['btval'];

In that case, your real mistake was that you've put the two variables in this assignment in the incorrect order. $a = $b means: put the contents of $b into $a.


text:
Q: pytest parametrizing fixtures with multiple asserts I have an example code where I have a parametrized test function with two asserts:
@pytest.mark.parametrize("test_input,expected", [
    ("3", 8),
    ("2", 6),
])
def test_eval(test_input, expected):
    assert test_input == expected # first assert
    assert test_input + 2 ==expected # second assert

So the output I wanted was (pseudo code):
assertion error 3==8
assertion error 5==8
assertion error 2==6
assertion error 4==6

While executing the test for all combinations is there a way to reach the second assert even if the first one fails ?
As alternative I'd like to know is there a way to put this into class for example something similar to this:
@pytest.mark.parametrize("test_input,expected", [
    ("3", 8),
    ("2", 6),
])
class TestFunc(object):
   def test_f1(test_input, expected):
     assert test_input==expected
   def test_f2(test_input, expected):
     assert test_input+2==expected

And I want to get the same output as the previous case:
assertion error 3==8
assertion error 5==8
assertion error 2==6
assertion error 4==6

A: There is the pytest-expect plugin which does that kind of thing.
The way you outlined with using @pytest.mark.parametrize on a class works out-of-the-box, you just forgot self.
Another possibility would be to simply write two tests and share the parametrization:
eval_parametrize = pytest.mark.parametrize("test_input, expected", [
    ("3", 8),
    ("2", 6),
])

@eval_parametrize
def test_f1(test_input, expected):
    assert test_input == expected

@eval_parametrize
def test_f2(test_input, expected):
    assert test_input + 2 == expected


text:
Q: A way to increase tile working range All cities have a maximum tile working radius of 3. I sometimes want to try a game with just a few enormous cities.
Is there any way, such as config file settings or mods out there that do this?

A: Unfortunately, without mods, there is no way to get cities with more than a range of 3 workable tiles.
Note that you can still get certain benefits from tiles that are within your borders past the three workable tiles - such as strategic and luxury resources.


text:
Q: "Categorize" or "Mark" SELECT query I have a query that SELECTs from multiple databases where column 'auth' = mad:
$result = mysql_query("SELECT * FROM test.1 WHERE auth = 'mad' LIMIT 1
    UNION SELECT * FROM test.2 WHERE auth = 'mad' LIMIT 1
    UNION SELECT * FROM test.3 WHERE auth = 'mad' LIMIT 1");

How do I mark or categorize the result, obtained from test.1; test.2 or test.3 ?
Thanks a lot.

A: Add the table name to results:
$result = mysql_query("SELECT *, 'test.1' FROM test.1 WHERE auth = 'mad' LIMIT 1
                  UNION SELECT *, 'test.2' FROM test.2 WHERE auth = 'mad' LIMIT 1
                  UNION SELECT *, 'test.3' FROM test.3 WHERE auth = 'mad' LIMIT 1");

A: $result = mysql_query("SELECT *, 'test1' as Source FROM test.1 WHERE auth = 'mad' LIMIT 1
UNION SELECT *, 'test2' FROM test.2 WHERE auth = 'mad' LIMIT 1
UNION SELECT *, 'test3' FROM test.3 WHERE auth = 'mad' LIMIT 1");

A: If I understand correctly, you just add a column.  Also, it is better to use union all rather than union, because union also expends extra effort to eliminate duplicates:
SELECT 1 as test, t1.* FROM test.1 t1 WHERE auth = 'mad' LIMIT 1
    UNION ALL
SELECT 2 as test, t2.* FROM test.2 t2 WHERE auth = 'mad' LIMIT 1
    UNION ALL
SELECT 3 as test, t3.* FROM test.3 t3 WHERE auth = 'mad' LIMIT 1;


text:
Q: How to unlock HP BIOS advanced option My HP Pavilion laptop's BIOS is locked out by the manufacturer, preventing me from installing Linux. In the past,when I attempted to install Linux on my other laptop I had to turn off Intel RST and turn on AHCI mode
However, I am unable to perform the same action on my brand-new HP laptop since I do not have access to the Advanced BIOS function.
My question is:

*

*Does Linux support intel RST now?

*Is there anyway I can unlock laptop's BIOS settings? I tried with HP customer support but they said it is not possible.

A: In some versions of BIOS, one must first set a password to access advanced features. After setting it, boot and then shutdown. The next time BIOS is accessed, enter the password. (On some PC's, expect loud beeping until the password has been entered. Likely, this is a corporate "security" feature.)
If the password is already set, but has been forgotten, it may be possible to reset it.


text:
Q: Ctrl keys not working - 16.04 LTS, Cougar 200k keyboard I have a fresh install of Ubuntu 16.04 LTS and a Cougar 200k keyboard.
As far as I can tell all keys and functions are working, except the two Ctrl keys.
Not having Ctrl keys kinda sucks ;)
Any ideas?
UPDATES:

*

*Both Ctrl keys act like additional Shift keys

*Tried this code(https://bitbucket.org/Swoogan/aziokbd), but it didn't solve the problem

*--  Did the blacklist as described for aziokbd, but it did not solve the problem.

*Tested the keycodes using showkey and xev: Ctrl, Shift, and Alt all have the same keycode. showkey returns 42, and xev returns 50

A: Just install the aziokbd driver, it worked for me:
sudo apt-get install mercurial build-essential linux-headers-generic dkms
git clone https://github.com/teitss/aziokbd
cd aziokbd
./install.sh

Make sure to plug it out after installing the driver then plug it in again.


text:
Q: Was there only a single mithril-mail shirt made? Considering mithril is both incredibly light and strong (compared to other materials such as steel) are there any references to there being more than a single mithril mail shirt (Bilbo's) ever being made or used?
Did the dwarves craft more of them?

A: In The Fellowship of the Ring, book 2 chapter 6, Gimli sees Frodo's mithril coat for the first time, after the Fellowship (save Gandalf) have escaped from Moria. He says:

It is a mithril coat. Mithril! I have never seen or heard tell of one
  so fair. Is this the coat that Gandalf spoke of? Then he undervalued it.

Since Gandalf had already said it was a mithril coat, Gimli is saying that this is a particularly fine example of a mithril coat, which implies that he knows of and indeed has seen others.

A: In addition to Mike's answer - in The Hobbit, the coat Thorin chooses for Bilbo is described as

"...wrought for some young elf-prince long ago. It was of silver-steel which the elves call mithril"

For it to fit Bilbo, it had to be a very young Elf prince. The idea that there was only ever one mithril chain mail shirt forged and it was given to a young elf, who would soon outgrow it, seems very unlikely.


text:
Q: Ajax: Submit form with form name I have a following form
<form autocomplete="off" id="settleUp" name="settleUp" method="post" role="form">

Gautam Sawala

                    <input onChange="checkInput(this);" step="0.01" type="number" class="form-control" id="amount" name="amount" value="0.00" placeholder="0.00" min="0.00" required>
                    <input id="payeeId" name="payeeId" value="3" hidden required>

                  <input type="submit" class="btn btn-success" value="Pay Back">

I want to submit this form as ajax form submit,
$("#settleUp").submit(function(e){
        alert('here');
        $.ajax({
            type:"PUT",
            url: "/api/v1/settlements",
            data: $(this).serialize()+'&groupId='+'<?php echo $_GET['group_id'] ?>'+'&userId='+'<?php echo $_SESSION['userId'] ?>'+'&token='+'<?php echo $_SESSION['token'] ?>',
            dataType: "json",
            success: function(response){
                refreshExpenseListing();
                $('#settleUpModal').modal('hide');
                },
            error: function(data) {
                alert("failure");
              }
        });

        e.preventDefault();
    });

I am able to submit the form using the id of the form $("#settleUp").submit(function(e)
But I have multiple form as above and I want to submit the form using the name and not the id.
Is there a way in AJAX to do that?
Something like this,
$("form[formname]").submit(function(e)?
I have tried
$("form.settleUp").submit(function(e) but this doesn't work!

A: Yes you can do it using Attribute Equals Selector :
$("form[name='settleUp']").submit(function(e){
    //Your code here
}

Explanation
First attempt :

$("form[formname]").submit(function(e)

Your first attempt will not work since you give just the value formname without specifying the concerned attribute.

Second attempt :

$("form[formname]").submit(function(e)

It will not work it your form has a class name equal settleUp since . is a class selector.

To deal with forms added dynamically to the document by ajax you must use event delegation on() :
$('body').on('submit', "form[name='settleUp']", function(e)

Hope this helps.


text:
Q: Is it possible to take a crawled html file, and get information about how a browser would render it? Examples of stuff I'd like to do:
- process javascript and produce new DOM
- be able to provide information about DOM objects as rendered (e.g. position, size)
Edit: My main concern is if a page contains a large, central flash object (typically a movie or game).

A: I guess the only way to do this is to pipe the HTML through a rendering engine, either a real one (like WebKit or Gecko) or something feature-complete enough for your purposes, and then query the resulting DOM about how it looks. Maybe take a look at projects like webkit2png for inspiration.


text:
Q: How would this equation be converted to polar coordinates? How would this equation be converted to polar coordinates?
$(x^2 + y^2)^2 = 2xy$
First, I changed $(x^2 + y^2)^2$ to $(r^2)^2 = r^4$
Then, rewrote the equation to $r^4 = 2xy$
What needs to take place next?

A: Remember that also $x = r \cos \theta$ and $y = r \sin \theta$. So: $$(x^2+y^2)^2 = 2xy \implies r^4 = 2r^2\cos\theta \sin \theta \implies r^2 = \sin(2\theta) \quad \mbox{or}\quad  r = 0.$$

A: When converting from rectangular to polar coordinates, you'll want to remember your trigonometry. In particular, let $x=r\cos\theta$ and $y=r\sin\theta,$ then simplify using relevant trigonometric identities.
Nota Bene: Don't forget the possibility that $r$ might be $0$!


text:
Q: Multiple column data extraction Problem : I want to aggregate multiple conditions in discontinueted column.
Link : Google Sheet link
Context: I'm a mushroom grower and I wanna schedule my production program for 2020.
We call batch an amount of inoculated mushroom substrate put in production at the same time. Usually, it weights a ton, and for the total year 2020 we'll have about 40 batches put in production.
A batch has several characteristics :

*

*An ID. 20-B1 is the first batch for 2020, 20-B2 the second, and so on.

*A scheduled week of production start. Usually, the production for 1 batch last 14 week. The week of production is numbered from 1 to 14.

*A calendar week, where the array of 14 production week is placed.

*An Origin. We work with two companies (Eurosubstrat and CNC) and are producing our own substrate. This means 3 arguments: "EURO", "CNC" and "LCU"

*A species cultivated. We have two species: Shiitake and Pleurotus Ostreatus

*A weight; about 1 ton but few batches can be much lighter

*A production capability VS time: For example, in The third week of exploitation, a batch will produce 3,4% of his mass in mushroom.

I wanna extract and put the following results in a column :
Target 1 : In order to establish an order schedule, the amount of batch who match those criteria for 1 given calendar week; for example "Week production = 1" AND "Origin = Euro" AND "Species = shii."

Target 2 : In order to estimate total production capability for 1 given species, the sum of individual production capability for 1 given calendar week: for example "Species = shii" AND (related)  "production capability"

Hope I'm clear
If you imagine a better way to organize my data, feel free to suggest. I don't know if the current organization is the best.
Sorry, English is not my native tongue.


text:
Q: How can I connect HDMI out from an android setup box to a android tablet to see the setup box screen? I want to connect an android setup box HDMI out to an android tablet to see the screen of the setup box in the tablet. Here I want to interface an android setup box with the android tablet, so that I can test my android app from setup box to a handy tablet. Is there is any hardware connector or any android app to read the HDMI signal from outside???

A: You would need a tablet with HDMI IN for that, but I think this feature does not exists.
So you can't.
But you can use remote desktop or screen share applications to see what the box is displaying.


text:
Q: VBA querytables loop placing retrieved data in not correct cells I'm creating a little macro to retrieve data from a website that has the table in rows of 30.
The problem is that when I loop, every iteration of the loop places data to the column at the right instead of below. I mean, my query retrieves data from Columns A to Q until row 30. When I get the next iteration I would want that it gets Columns A to Q but from row 31 to 61.
Thing is it places from Columns R to... XX until row 30.
I guess the issue might be on the Destination:=Range...
Sub Extract_data_table()
'
' Extract_data_table Macro

' For i = 1 to 41
For x = 1 To 41
Z = (x * 30) - 29
Worksheets("NHL_results_RS").Select
Worksheets("NHL_results_RS").Activate
mystr = "URL;http://www.nhl.com/stats/game?fetchKey=20062ALLSATALL&viewName=summary&sort=gameDate&gp=1&pg=" & x

With ActiveSheet.QueryTables.Add(Connection:= _
    **mystr, Destination:=Range("$A$1"))**
    '.CommandType = 0
    .Name = _
    "game?fetchKey=20062ALLSATALL&viewName=summary&sort=gameDate&gp=1&pg=1_2"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .WebSelectionType = xlSpecifiedTables
    .WebFormatting = xlWebFormattingNone
    .WebTables = "3"
    .WebPreFormattedTextToColumns = True
    .WebConsecutiveDelimitersAsOne = True
    .WebSingleBlockTextImport = False
    .WebDisableDateRecognition = False
    .WebDisableRedirections = False
    .Refresh BackgroundQuery:=False
End With

Next x

End Sub

Could any of you help?

A: You are correct in assuming the problem lies in Destination. I have never used this command, but after some brief experimenting I've deducted that if the Destination is occupied, it will paste the data in the nearest suitable space to the right of your original destination.
To bypass this, you should add an Offset to your destination range, based on your iterator, which is x in your example.
What I did was this:
Destination:=Range("$A$1").Offset((x - 1) * 31, 0))

This would work, but you'll notice that you will be repeating the column headers, so I guess you'll need to experiment with .FieldNames a bit as well.


text:
Q: Add SSL Server Certificate for DB2 in JDBC code I am trying to access a DB2 instance via SSL port.
I have the certificate that I need to access it.
But I am not sure of the parameter that I need to add it to so that connection is successful.
Dataset<Row> data=session.read().jdbc("jdbc:db2://url:port/DBNAME"+":sslConnection=true"
    , "db2inst1.JOB_STATUS", connectionProperties);

    connectionProperties.put("driver", "com.ibm.db2.jcc.DB2Driver");
    connectionProperties.put("url", "jdbc:db2://url:port/DBNAME");
    connectionProperties.put("user", "db2inst1");
    connectionProperties.put("password", "xxxxx");

The python code to connect to the same DB2 instance is this :
"DATABASE=DB_NAME;HOSTNAME=url;SSL=TRUE;PORT=port;PROTOCOL=TCPIP;UID=xxxx;PWD=xxxx;SSLServerCertificate=DB2Certificate.arm;;SECURITY=SSL"

I would want to provide the DB2Certificate.arm as a parameter to the jdbc url , similar to the python parameter of SSLServerCertificate . How can I do this ?

A: Configuring your JRE/JVM to use SSL with Db2 for Linux/Unix/Windows is described here and also here.
The exact version of your jdbc driver can also influence what configuration options exist (db2jcc4.jar, db2jcc.jar ).
Notice that configuring JRE is a different activity from configuring CLI programs (such as Python).
Suggest you try to follow the docs first.

A: Does the following URL work for you?
jdbc:db2://url:port/DBNAME:sslConnection=true;sslCertLocation=/full_path/DB2Certificate.arm;


text:
Q: Hover effect on only one item out of multiple displayed - VUEJS I have put in a mouseenter and mouseleave on the li tag that i want  when a person hovers over it, it will display the price on product.price. However, when i hover over it, it will display the price for all 6 rendered data instead of just the 1 its hovered on. I only want it to display pricing on the specific item its hovered on and not all. The data is being loaded from firebase. Please see below template code and image here for reference.

                    {{ product.name }}

                  Cheapest At

                  {{ product.cheapestat }}

                  From
                 A${{ product.price }}

script code on firebase data

  setup() {
    onMounted(() => {
      onSnapshot(collection(db, "malesneakers") , (querySnapshot) => {
        const maleProducts = [];
        querySnapshot.forEach((doc) => {
          const mlproducts = {
          id: doc.id,
          imageSrc: doc.data().imageSrc,
          name: doc.data().name,
          price: doc.data().price,
          cheapestat: doc.data().cheapestat,
          svgSrc: doc.data().svgSrc,
          href: doc.data().href,
        }
        maleProducts.push(mlproducts)

        });
        products.value = maleProducts

      });

    });

A: Try with product.id instead of boolean for hover variable:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const products = ref([{id: 1, name: 'aaa', href: '#', cheapestat: 5, price: 7}, {id: 2, name: 'bbb', href: '#', cheapestat: 5, price: 5}])
    const hover = ref(null)
    return {
      products, hover
    };
  },
})
app.mount('#demo')

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

              {{ product.name }}

            Cheapest At

            {{ product.cheapestat }}

            From
           A${{ product.price }}


text:
Q: Create file with content, where the content has new line In linux, how to create a file with content whose single line with \n (or any line separator) is translated into multi-line.
fileA.txt:
trans_fileA::abcd\ndfghc\n091873\nhhjj
trans_fileB::a11d\n11hc\n73345

Code:
while read line; do
         file_name=`echo $line | awk -F'::' '{print $1}' `
         file_content=`echo $line | awk -F'::' '{print $2}' `
             echo $file_name
             echo $(eval echo ${file_content})
         echo $(eval echo ${file_content}) > fileA.txt

The trans_fileA should be:
abcd
dfghc
091873
hhjj

Please suggest

A: Using the bash shell:
while IFS= read -r line; do
    name=${line%%::*}
    contents=${line#*::}

    echo -e "$contents" >"$name"
done <fileA.txt

This reads the input file line by line and extracts the output filename and the contents form the read line using standard parameter substitutions.  ${variable%%pattern} removes the longest matching substring from the tail end of $variable that matches pattern, while ${variable#pattern} removes the shortest matching substring from the start of $variable that matches pattern.
The value of line is read with read -r so that the backslashes are preserved in the data.  Without -r, read would not preserve these.  We also set IFS to an empty string before calling read so that no flanking whitespace is trimmed from the data.
The output is done using echo -e, which interprets the escape sequences in the data.  This means that it will replace the \n in the data with actual newlines.
After running this, you will have
$ ls -l
total 12
-rw-r--r--  1 kk  wheel  71 Jun 17 16:28 fileA.txt
-rw-r--r--  1 kk  wheel  24 Jun 17 16:31 trans_fileA
-rw-r--r--  1 kk  wheel  16 Jun 17 16:31 trans_fileB

$ cat trans_fileA
abcd
dfghc
091873
hhjj

$ cat trans_fileB
a11d
11hc
73345

Related:

*

*Understanding "IFS= read -r line"

A: My first thought was sed
Given your file, fileA.txt above:
abcd\ndfghc\n091873\nhhjj

and running sed against newline.sed which contains:
s/\\n/\
/g

thusly
sed -f ./newline.sed <./fileA.txt >./trans_fileA
will return these results in trans_fileA:
abcd
dfghc
091873
hhjj

This was the simplest way I could figure to accomplish your task.
HTH


text:
Q: Ordering: Normalized Given a Hilbert space $1\in\mathcal{A}$.
Denote selfadjoints:
$$\mathcal{S}:=\{A\in\mathcal{A}:A=A^*\}$$
Introduce an order:
$$A\leq A':\ \ \sigma(A'-A)\geq0$$
Regard a projection:
$$P\neq0:\quad P^2=P=P^*$$
Then one has:
$$P\leq A\leq1\implies\|A\|=1$$
How can I check this?
(Operator-algebraic proof?)

A: Since you have to relate the norm with the spectrum, I don't think this has an elementary algebraic proof.
Facts needed (from the theory of Banach algebras):

*

*For any $A\in\mathcal S$, $\sigma(A)=\{\phi(A):\ \phi\in S(\mathcal A)\}$, where $S(\mathcal A)$ is the state space.

*For any $A\in\mathcal S$, $\|A\|=\text{spr}(A)=\max\{|\lambda|:\ \lambda\in\sigma(A)\}$.
From those two facts you easily deduce that $\|P\|=1$. Whenever $0\leq B\leq A$,  we have $\phi(B)\leq\phi(A)$ for any state $\phi$, so $\|B\|=\text{spr}(B)\leq\text{spr}(A)=\|A\|$.
As $\|1\|=1$, you are done.


text:
Q: An elegant way of overloading Python class properties Consider a base class:
class A(object):
   def __init__(self, x):
      self._x = x

   def get_x(self):
      #...
      return self._x

   def set_x(self, x):
      #...
      self._x = x

   x = property(get_x, set_x)

and a derived class:
class B(A):
   def set_x(self, x):
      #...
      self._x = x**2

   x = property(A.get_x, set_x)

Is there an elegant way of overloading set_x() in class B, without re-declaring it and the property x? Thank you.

A: Add an extra layer of indirection (i.e. use a hook):
class A(object):
    def __init__(self, x):
        self._x = x

    # Using a _get_hook is not strictly necessary for your problem...
    def _get_hook(self):
        return self._x
    def get_x(self):
        return self._get_hook()

    # By delegating `set_x` behavior to `_set_hook`, you make it possible
    # to override `_set_hook` behavior in subclass B.
    def _set_hook(self, x):
        self._x=x
    def set_x(self, x):
        self._set_hook(x)

    x = property(get_x, set_x)

class B(A):
    def _set_hook(self, x):
        print('got here!')
        self._x = x**2

b=B(5)
b.x=10
# got here!
print(b.x)
# 100

For modern versions of Python, you can also use the @property decorator:
class A(object):

   @property
   def x(self):
      return self._get_hook()

   @x.setter
   def x(self, x):
      self._set_hook(x)

A: Try this one:
 class A(object):
    def __init__(self):
        self._x = 0

    def get_x(self):
        #...
        return self._x

    def set_x(self, x):
        #...
        self._x = x

    x = property(get_x, lambda self,x : self.set_x(x))

class B(A):
    def set_x(self, x):
        #...
        self._x = x**2

The extra indirection given by the lambda will make the set_x function virtually.


text:
Q: How to fix Type 'ContentView' does not conform to protocol 'View' etc. XCODE - SwiftUI

import SwiftUI
import CodeScanner

struct ContentView: View {
    @State var isPresentingScanner = false
    @State var scannedCode: String = "Scan a QR code to get started."

    var scannerSheet : some View {
        CodeScannerView(
            codeTypes: [.qr],
            completion:{ result in
                if case let.success(code) = result {
                    self.scannedCode = code.string
                    self.isPresentingScanner = false

                }
    }

)
        var body: some View {
        VStack(spacing: 10) {
            Text(scannedCode)

            Button("Scan QR code") {
                self.isPresentingScanner = true
            }

            .sheet(isPresented: $isPresentingScanner) {
                self.scannerSheet
            }
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }

}

}

I'm a very new beginner in XCODE and am a bit stuck with these errors shown on my code and I've tried looking up solutions but I cannot get anywhere, unfortunately. I would appreciate any help or feedback.
The errors that are occuring are "Type 'ContentView' does not conform to protocol 'View'", "Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type", "Result of 'CodeScannerView' initializer is unused"
P.S I am attempting to create a code scanner and I already have a packaged added.
enter image description here

A: It's because you didn't put closing brackets for scannerSheet, and had extra closing brackets after the body variable.
This should work.
import SwiftUI
import CodeScanner

struct ContentView: View {
    @State var isPresentingScanner = false
    @State var scannedCode: String = "Scan a QR code to get started."

    var scannerSheet : some View {
        CodeScannerView(
            codeTypes: [.qr],
            completion:{ result in
                if case let.success(code) = result {
                    self.scannedCode = code.string
                    self.isPresentingScanner = false

                }
            }

        )
    } // ←

    var body: some View {
        VStack(spacing: 10) {
            Text(scannedCode)

            Button("Scan QR code") {
                self.isPresentingScanner = true
            }

            .sheet(isPresented: $isPresentingScanner) {
                self.scannerSheet
            }
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }

}

P.S. Something that would help you spot this type of error in the future would be to re-indent all the code.
You can do that by selecting all the code in the file (CMD+A), then selecting Editor -> Structure -> Re-Indent (CTRL+I)


text:
Q: Spark Streaming Kafka with Java11 scala code Issue I am using scala Spark Streaming Kafka with JDK 11. But I am getting the below error.

Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)Lscala/collection/mutable/ArrayOps;

Below is the code I am using.
val conf = new SparkConf().setMaster("local[*]").setAppName("KafkaExample")
      .set("spark.mongodb.input.uri", "mongodb://127.0.0.1/db.table_data")
      .set("spark.mongodb.output.uri", "mongodb://127.0.0.1/db.table_data")
      .set("spark.driver.allowMultipleContexts", "false")
      .set("spark.ui.enabled", "false")

val kafkaParams = Map("metadata.broker.list" -> "localhost:9092")
    val topics = List("topic").toSet
    val lines = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](
      ssc, kafkaParams, topics)

Below is my pom.xml
<dependency>
          <groupId>org.apache.spark</groupId>
          <artifactId>spark-core_2.12</artifactId>
          <version>2.4.8</version><!--<version>2.3.2</version>-->
      </dependency>
      <dependency>
          <groupId>org.apache.spark</groupId>
          <artifactId>spark-sql_2.12</artifactId>
          <version>2.4.8</version>
      </dependency>
      <dependency>
          <groupId>org.apache.spark</groupId>
          <artifactId>spark-streaming_2.12</artifactId>
          <version>2.4.8</version><!--<version>2.3.2</version>-->
          <!--<scope>provided</scope>-->
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-kafka-0-10 -->
      <dependency>
          <groupId>org.apache.spark</groupId>
          <artifactId>spark-streaming-kafka_2.11</artifactId>
          <version>1.6.1</version>
      </dependency>

      <dependency>
          <groupId>org.mongodb.spark</groupId>
          <artifactId>mongo-spark-connector_2.12</artifactId>
          <version>2.4.3</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.10.0</version>
      </dependency>

The issue is coming in KafkaUtils.createDirectStream() and i checked the maven and scala compatibility JDK 11 is compatible with scala 2.12 and higher and we don't have any maven dependency for spark-streaming-kafka jar. KIndly let me know if my analysis is wrong and which jar should i use for spark-streaming-kafka for JDK 11

A: *

*DirectStream API is deprecated, you should be using spark-sql-kafka-0-10 dependencies. The Mongo Spark driver works with Spark SQL also

*As commented, you're mixing your Scala versions (the broker Scala version doesn't matter), and you're also mixing your Spark versions


text:
Q: There is a word for mis-characterization of a political figure What is it called when someone (example: a political figure) is mis-characterized constantly and untruthfully?
For example a campaign constantly hammers the message: "Senator X promotes high spending", because they voted for 1 expensive bill, but evaluating them across all votes might demonstrate that they are actually quite fiscally conservative.
There is a nice concise term for such mis-characterizations that's used commonly in the political landscape.
In this case we might say: "The opposing campaign has ____ this candidate", or something along those lines.

Addition: Perhaps the word I'm hoping to find is one that describes the wholesale act of this kind of mis-characterization across political discourse...

A: Might I suggest "swiftboating," as defined by Wikipedia below?

The term swiftboating (also spelled swift-boating or swift boating) is an American neologism used pejoratively to describe an unfair or untrue political attack. The term is derived from the name of the organization "Swift Boat Veterans for Truth" (SBVT, later the Swift Vets and POWs for Truth) because of their widely publicized—and then discredited—campaign against 2004 U.S. Presidential candidate John Kerry.
Since the political smear campaign conducted by the Swift Boat Veterans for Truth against John Kerry, the term "swiftboating" has come into common use to refer to a harsh attack by a political opponent that is dishonest, personal, and unfair. The Swift Boat Veterans and media pundits objected to this use of the term to define a smear campaign.

You might also refer to a "smear campaign."

A: In the specific example you mentioned (i.e. politics), it's called mudslinging:

the use of insults and accusations, especially unjust ones, with the aim of damaging the reputation of an opponent; efforts to discredit one's opponent by malicious or scandalous attacks.

More generally, it is a form of character assassination or slander:

the act of deliberately attempting to destroy a person's reputation by defamatory remarks

A: I think denigrate may be used in this context:

To attack the character or reputation of; speak ill of; defame.

Political denigration.

A: lampooned or vilified may work in this case, though neither are specifically restricted to politics.

A:
Roorback  a false and more or less damaging report circulated for political effect, usually about a candidate seeking an office.

A: Misrepresent would seem to fit, and since such misrepresentation is intended to injure the affected party, if one feels strongly about the incident slander comes to mind.

A: This only covers the selective use of evidence, rather than doing so against a particular figure, but cherry picking may be a useful term.

Cherry picking, suppressing evidence, or the fallacy of incomplete
  evidence is the act of pointing to individual cases or data that seem
  to confirm a particular position, while ignoring a significant portion
  of related cases or data that may contradict that position. It is a
  kind of fallacy of selective attention, the most common example of
  which is the confirmation bias. Cherry picking may be committed
  intentionally or unintentionally. This fallacy is a major problem in
  public debate.


text:
Q: SQL How do I script a index to a sproc Does anyone know how to script an index. If I have 2 indexes and I want to script them to a sproc, how do I do this, like how do I seperate each of the indexes and copy them into a stored procedure?
USE [master]
GO

/****** Object:  Index [index1]    Script Date: 03/26/2014 20:31:47 ******/
CREATE CLUSTERED INDEX [index1] ON [dbo].[EmployeeTbl]
(
[ID] ASC
)
WITH (PAD_INDEX  = ON, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,           IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY]
GO

How do I script, this, and another index into a sproc and save it. Thanks!

A: You could always use dynamic SQL
Create a string that contains the script that will Create the Index:
CREATE PROCEDURE sp_CreateIndex
AS

  DECLARE @index_script NVARCHAR(2000)

  SET @index_script = 'CREATE CLUSTERED INDEX [index1] ON [dbo].[EmployeeTbl]
  (
  [ID] ASC
  )
  WITH (PAD_INDEX  = ON, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,           IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY]'

  EXEC(@index_script)

A: The 'GO' keywords separate the sql script into discrete operations that are executed sequentially. Whilst it's important for the index creation to happen against the right database (per the 'USE' command), this will tend to happen correctly for you once you've opened you SqlConnection.
So the important stuff to put on your SqlCommand is everything between the 'GO' statements (and don't include these).
You can add a second CREATE INDEX to your first without needing a 'GO' in between. A newline will generally suffice. (A semi-colon will force the two to be recognised as two separate CREATE commands if you're paranoid.)


text:
Q: Запуск сервера Nest js, чтобы выполнить Cron таски Обязательно ли запускать весь сервер Nest чтобы запустить cron таски? Или есть какой-то подход написания launch скрипта в packages.json, который позволяет запустить только связанные с typeorm таски для cron, при этом, не меняя оригинальный код проекта?

A: Cron таски NestJS можно выполнить только при работающем проекте NestJS. Если у вас есть БД в которой так же указаны timestamp'ы ваших Cron, то можете написать отдельный скрипт, который каждые секунд 10 будет получать все кроны, проходиться по ним и если он находит крону, которая устарела - выполнять её, а после удалять из БД
Либо что-то универсальное, по типу
"нынешнее время"-"последний запуск кроны" > "интервал"


text:
Q: How to open and read SQLite files I am trying to recover something from Mozilla Firefox history, and grep returns lots of binary files, I think they come from sqlite content. How can I view them in human-readable form, as text? At the top of the file I see something like
 SQLite format 3

A: I don't think there's any general way to turn an arbitrary binary file into human-readable form - you would need to know the byte-by-byte format in order to unpack and convert it. (There is the strings utility, but that will only extract ASCII sequences that happen to be embedded in the file).
In the specific case of Mozilla Firefox, it appears to use SQLite 3 - this is likely what you are seeing at the top of the file - this is one time where strings is useful:
$ strings ~/.mozilla/firefox/dhjktlo7.default/storage.sqlite
SQLite format 3

although you could also use the file command to identify the content type:
$ file -b ~/.mozilla/firefox/dhjktlo7.default/storage.sqlite
SQLite 3.x database, user version 65536, last written using SQLite version 3013000

Probably the best way to display / search these specific files is to use the sqlite3 command line client (from package sqlite3) to .dump them e.g.
$ sqlite3 ~/.mozilla/firefox/dhjktlo7.default/storage.sqlite .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
COMMIT;

A: SQLite is a type of relational database, so that file will contain tables, columns and indexes.
sqlitebrowser is a GUI based application that lets you browse inside SQLite files.
Of course you can simply install sqlite3 itself and use the sqlite3 command-line tool to open the database.


text:
Q: How to pass List  from class to class AudioPlayer The site is an example of microsoft for Windows Phone 7, namely: Background Audio Player Sample or Sample
In this example, the playlist is formed in the class AudioPlayer as a list of
    private static List<AudioTrack> _playList = new List<AudioTrack>
{
    new AudioTrack(new Uri("Kalimba.mp3", UriKind.Relative),
                    "Kalimba",
                    "Mr. Scruff",
                    "Ninja Tuna",
                    null),

    new AudioTrack(new Uri("Maid with the Flaxen Hair.mp3", UriKind.Relative),
                    "Maid with the Flaxen Hair",
                    "Richard Stoltzman",
                    "Fine Music, Vol. 1",
                    null),

    new AudioTrack(new Uri("Sleep Away.mp3", UriKind.Relative),
                    "Sleep Away",
                    "Bob Acri",
                    "Bob Acri",
                    null),

    // A remote URI
    new AudioTrack(new Uri("http://traffic.libsyn.com/wpradio/WPRadio_29.mp3", UriKind.Absolute),
                    "Episode 29",
                    "Windows Phone Radio",
                    "Windows Phone Radio Podcast",
                    null)
};

And I have a question, for example if I make it in MainPage.cs:
 private static List<AudioTrack> playList2 = new List<AudioTrack>
{
    new AudioTrack(new Uri("http://myserver.com/tracks/track1.mp3", UriKind.Absolute),
                    "MyTrack1",
                    "Windows Phone Radio",
                    "Windows Phone Radio Podcast",
                    null),

    new AudioTrack(new Uri("http://myserver.com/tracks/track2.mp3", UriKind.Absolute),
                    "MyTrack2",
                    "Windows Phone Radio",
                    "Windows Phone Radio Podcast",
                    null),

    new AudioTrack(new Uri("http://myserver.com/tracks/track3.mp3", UriKind.Absolute),
                    "MyTrack3",
                    "Windows Phone Radio",
                    "Windows Phone Radio Podcast",
                    null)
};

which will be links to several Internet radio in the class MainPage, is it possible to transmit in AudioPlayer. Advise what to do, where to dig. Help me

A: Write the information to IsolatedStorage or a database from the client application, then read it from the AudioPlayer agent.
To clarify:
Whether you're playing local files or stream files you will communicate with the Agent by writing that info to a DB table or a file in IsolatedStorage.  Say you have a database with a table named Playlist.
From your app or MainPage.xaml.cs (or viewmodel) write the data to the playlist table.  Then issue BackgroundAudioPlayer.Instance.Play();
Then, in the AudioPlayerAgent read from the Playlist table to get the data to create an AudioTrack.
update:
Originally I was using IsolatedStorage for this and it worked, now I'm using SterlingDB.  This works pretty well as I can write play list records out to SterlingDB in my client app and read them one at a time in the Agent as the currentTrackIndex is manipulated, all without having to create an SterlingDB index.

A: It works for windows phone 8
BackgroundAudioPlayer.Instance.Track = new AudioTrack(new
         Uri("http://traffic.libsyn.com/wpradio/WPRadio_29.mp3", UriKind.Absolute),
        "title", "artist", "album", new Uri("albumArtUrl", UriKind.RelativeOrAbsolute));


text:
Q: How to use erode and dilate function in opencv? I'm trying to eliminate the thing around the number with erode and dilate process. I tryed but nothing happened. I changed the values just for see if would change something, but again, nothing has changed. The image continues like in the link above. What about this parameters... I read the documentation but don't quite understand (as you can see, I was guessing in the function). What am I doing wrong?
the image: https://docs.google.com/file/d/0BzUNc6BOkYrNeVhYUk1oQjFSQTQ/edit?usp=sharing
the code:
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;

int main ( int argc, char **argv )
{
    Mat im_gray;
    Mat img_bw;
    Mat img_final;

    Mat im_rgb  = imread("cam.jpg");
    cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

    adaptiveThreshold(im_gray, img_bw, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV, 105, 1);

    dilate(img_bw, img_final, 0, Point(-1, -1), 2, 1, 1);

    imwrite("cam_final.jpg", img_final);

    return 0;
}

A: According to official docs, the third argument should be the kernel (or structuring element). You are currently passing 0:
dilate(img_bw, img_final, 0, Point(-1, -1), 2, 1, 1);

Try rewriting it this way:
dilate(img_bw, img_final, Mat(), Point(-1, -1), 2, 1, 1);

In this case, a default 3x3 kernel will be used.

A: Kernel is basically a matrix. This is multiplied or overlapped on the input matrix(image) to produce the desired output modified(in this case dilated) matrix(image).
Try changing the parameters of Mat() in
dilate(img_bw, img_final, Mat(), Point(-1, -1), 2, 1, 1);
you're basically changing the number of pixels (height and width) of the kernel, which will change the dilation effect on the original pic.
So in the parameters of dilate you use Mat() instead of a number as already stated by esenti.


text:
Q: Remove "OneDrive" from path in onedrive folder I'm trying to setup a simple backup solution for a small office of a few people. We have a windows server with two disks in Raid 1 (mirrored) for saving files that can be reached both in office and from outside through a VPN. This folder is located at V:\Vault.
As an extra precation in case of robbery or fire we are thinking of saving the contents of this folder to OneDrive (as we are using it for other things already anyways).
Here comes the problem. Onedrive apparently requires you to put all your files in a folder path which ends in OneDrive, ie "V:\Vault\OneDrive". Even if you select a different location it automatically adds the "OneDrive" part to the end.
My question: Is there a way to get around this so that the onedrive folder is simply V:\Vault through some setting or other trikkery. I'm fine with regedit changes if it can be accomplished that way.
I would prefer not to change the folder structure/path because OneDrive has stupid settings/requirements.

A: Onedrive is a consumer product and isn't meant as a commercial backup target. Rather than trying to shoehorn it into your backup architecture, why not look at something much simpler and more suited for the task, such as Azure Backup


text:
Q: how to download a specific version of selenium with pip I want to install selenium via a requirements.txt with pip.
So I put selenium==2.53.0 into my requirements.txt.
However, when I do pip install -r requirements.txt it says
Could not find any downloads that satisfy the requirement selenium==2.53.0 >(from -r requirements.txt (line 8))
No distributions at all found for selenium==2.53.0

even though on the website it says that this is the last version.
Any ideas?


text:
Q: Including legacy library in .NET Core 2 app I'm trying to build a .net core C# app that requires a reference to an older library. Everything compiles and builds fine, but when the app attempts to execute any code from this library, it throws an exception:

System.IO.FileLoadException: 'Could not load file or assembly 'mscorlib, Version=5.3.0.620, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'

The 5.3.0.620 is the version of the DLL that I'm including, but it shouldn't be the version of mscorlib required. When I include the reference in a .NET 4.6.1 app, I don't get this error.
Is there any way to force the library to be happy with the included version of mscorlib (or any other workaround)?
Edit: This is not a duplicate of this question.  That person is trying to reference 4.0.0.0.  I already have that reference in place.   My problem is that in a .NET Core 2 app, the library I'm loading tries to reference an incorrect (non-existent) version of MSCORLIB for reasons that I don't comprehend.  When I load the library in a .NET 4.6.1 app, the library behaves correctly and loads the 4.0.0.0 version.


text:
Q: Convert Radio Button into a Checkbox I was wondering how to convert my radio buttons into checkboxes because I want to insert multiple options for the same record... for example: I want a game to be in the "Strategy" and "Action" category, so only a checkbox can make me achieve that.
here is my code for inserting a game with radio buttons:
<?php
session_start();

if(!isset($_SESSION['user_name'])){

header("location:login.php");

}
else {
?>
<?php
include("../includes/connect.php");

$action_status = 'unchecked';
$sports_status = 'unchecked';

if(isset($_POST['submit'])){

$game_name = $_POST['game_name'];
$game_category = $_POST['game_category'];
$game_keywords = $_POST['game_keywords'];
$game_image = $_FILES['game_image']['name'];
$image_tmp = $_FILES['game_image']['tmp_name'];
$game_code = $_FILES['game_code']['name'];
$code_tmp = $_FILES['game_code']['tmp_name'];
$game_file = $_FILES['game_file']['name'];
$file_tmp = $_FILES['game_file']['tmp_name'];
$game_desc = $_POST['game_desc'];

if($game_name=='' or $game_category=='' or $game_keywords=='' or $game_image=='' or $game_code=='' or $game_file==''){

echo "";

exit();

}
else {

 $path = "../games/$game_name";

 mkdir("$path", 0777);

 move_uploaded_file($image_tmp,"../images/games_images/$game_image");

 move_uploaded_file($code_tmp,"$path/$game_code");

 move_uploaded_file($file_tmp,"$path/$game_file");

 $insert_query = "insert into games (game_name,game_category,game_keywords,game_image,game_code,game_file,game_desc) values ('$game_name','$game_category','$game_keywords','$game_image','$game_code','$game_file','$game_desc')";

 if($game_category == '3d'){

 $three_d_status = 'checked';

 }else if($game_category == 'action'){

 $action_status = 'checked';

 }else if($game_category == 'adventure'){

 $adventure_status = 'checked';

 }else if($game_category == 'arcade'){

 $arcade_status = 'checked';

 }else if($game_category == 'brain'){

 $brain_status = 'checked';

 }else if($game_category == 'cards'){

 $cards_status = 'checked';

 }else if($game_category == 'destruction'){

 $destruction_status = 'checked';

 }else if($game_category == 'education'){

 $education_status = 'checked';

 }else if($game_category == 'extreme'){

 $extreme_status = 'checked';

 }else if($game_category == 'fighting'){

 $fighting_status = 'checked';

 }else if($game_category == 'flying'){

 $flying_status = 'checked';

 }else if($game_category == 'girls'){

 $girls_status = 'checked';

 }else if($game_category == 'holidays'){

 $holidays_status = 'checked';

 }else if($game_category == 'hidden_objects'){

 $hidden_objects_status = 'checked';

 }else if($game_category == 'motocross'){

 $motocross_status = 'checked';

 }else if($game_category == 'multiplayer'){

 $multiplayer_status = 'checked';

 }else if($game_category == 'new'){

 $new_status = 'checked';

 }else if($game_category == 'puzzle'){

 $puzzle_status = 'checked';

 }else if($game_category == 'racing'){

 $racing_status = 'checked';

 }else if($game_category == 'fps'){

 $fps_status = 'checked';

 }else if($game_category == 'space'){

 $space_status = 'checked';

 }else if($game_category == 'sports'){

 $sports_status = 'checked';

 }else if($game_category == 'strategy'){

 $strategy_status = 'checked';

 }else if($game_category == 'stunt'){

 $stunt_status = 'checked';

 }else if($game_category == 'top_rated'){

 $top_rated_status = 'checked';

 }else if($game_category == 'words'){

 $words_status = 'checked';

 }else if($game_category == 'zombies'){

 $zombies_status = 'checked';

 }

 if(mysql_query($insert_query)){

 echo "";

 echo "";

 }

}

}

?>

<?php } ?>

<!DOCTYPE HTML>

<link href="css/insert_game.css" rel="stylesheet" type="text/css">

<form method="post" id="insert_form" action="insert_games.php" enctype="multipart/form-data">

 Insert New Game

 Game name:
 <input type="text" name="game_name" size="80">

 Game category:
 <input class="radio" type="radio" name="game_category" value="3d"<?php print $three_d_status; ?>/>3D

 <input class="radio" type="radio" name="game_category" value="action"<?php print $action_status; ?>/>Action

 <input class="radio" type="radio" name="game_category" value="adventure"<?php print $adventure_status; ?>/>Adventure

 <input class="radio" type="radio" name="game_category" value="arcade"<?php print $arcade_status; ?>/>Arcade

 <input class="radio" type="radio" name="game_category" value="brain"<?php print $brain_status; ?>/>Brain

 <input class="radio" type="radio" name="game_category" value="cards"<?php print $cards_status; ?>/>Cards

 <input class="radio" type="radio" name="game_category" value="destruction"<?php print $destruction_status; ?>/>Destruction

 <input class="radio" type="radio" name="game_category" value="education"<?php print $education_status; ?>/>Education

 <input class="radio" type="radio" name="game_category" value="extreme"<?php print $extreme_status; ?>/>Extreme

 <input class="radio" type="radio" name="game_category" value="fighting"<?php print $fighting_status; ?>/>Fighting

 <input class="radio" type="radio" name="game_category" value="flying"<?php print $flying_status; ?>/>Flying

 <input class="radio" type="radio" name="game_category" value="girls"<?php print $girls_status; ?>/>Girls

 <input class="radio" type="radio" name="game_category" value="holidays"<?php print $holidays_status; ?>/>Holidays

 <input class="radio" type="radio" name="game_category" value="hidden_objects"<?php print $hidden_objects_status; ?>/>Hidden Objects

 <input class="radio" type="radio" name="game_category" value="motocross"<?php print $motocross_status; ?>/>Motocross

 <input class="radio" type="radio" name="game_category" value="multiplayer"<?php print $multiplayer_status; ?>/>Multiplayer

 <input class="radio" type="radio" name="game_category" value="new"<?php print $new_status; ?>/>New Games

 <input class="radio" type="radio" name="game_category" value="puzzle"<?php print $puzzle_status; ?>/>Puzzle

 <input class="radio" type="radio" name="game_category" value="racing"<?php print $racing_status; ?>/>Racing

 <input class="radio" type="radio" name="game_category" value="fps"<?php print $fps_status; ?>/>FPS

 <input class="radio" type="radio" name="game_category" value="space"<?php print $space_status; ?>/>Space

 <input class="radio" type="radio" name="game_category" value="sports"<?php print $sports_status; ?>/>Sports

 <input class="radio" type="radio" name="game_category" value="strategy"<?php print $strategy_status; ?>/>Strategy

 <input class="radio" type="radio" name="game_category" value="stunt"<?php print $stunt_status; ?>/>Stunt

 <input class="radio" type="radio" name="game_category" value="top_rated"<?php print $top_rated_status; ?>/>Top Rated

 <input class="radio" type="radio" name="game_category" value="words"<?php print $words_status; ?>/>Words

 <input class="radio" type="radio" name="game_category" value="zombies"<?php print $zombies_status; ?>/>Zombies

 Game keywords:
 <textarea id="insert_text_area" name="game_keywords"></textarea>

 Game image:
 <input type="file" name="game_image">

 Game HTML:
 <input type="file" name="game_code">

 Game Flash File:
 <input type="file" name="game_file">

 Game description:
 <textarea id="insert_text_area" name="game_desc"></textarea>

 <input type="submit" name="submit" value="Publish Game Now" id="insert_submit">

</form>

Anyone?
EDIT: While solving this problem I found an error in my code, I have much more then "action" and "sports" categories in my website, I forgot to add more categories to this lines "$action_status = 'unchecked';", but for some reason I didn't got any errors, and everything worked perfectly... strange O.o

A: If all you are looking to do is replace your RADIO buttons with CHECKBOXES, just change the HTML to reflect that, like so:
 <input class="radio" type="checkbox" name="game_category[]" value="action"<?php print $action_status; ?>/>Action

You will then need to change all the "else if"'s in your PHP to just "if"'s, as you can iterate over multiple values, like so:
if($game_category == 'multiplayer'){
     $multiplayer_status = 'checked';
}
if($game_category == 'new'){
    $new_status = 'checked';
}

A: The solution:
I change this line for example from this:
<input class="radio" type="radio" name="game_category" value="3d"<?php print $three_d_status; ?>/>3D

into this:
<input class="checkbox" type="checkbox" name="game_category[]" value="3d"<?php print $three_d_status; ?>/>3D

Then, I edited the if statements from this:
if($game_category == '3d'){

 $three_d_status = 'checked';

 }else if($game_category == 'action'){

 $action_status = 'checked';

 }

Into this:
if($game_category == '3d'){

 $three_d_status = 'checked';

 }
 if($game_category == 'action'){

 $action_status = 'checked';

 }

and finally I changed this line from this:
$game_category = $_POST['game_category'];

Into this:
$game_category = implode(",",$_POST['game_category']);

Hope that helped someone out there :)
Credit goes to: "binaryatrocity" and "Fred-ii-" :D

A: If you got only one, maybe the NAME  element must be an array :
Checkbox:<input type="checkbox" checked="checked" name="myCheck[]">


text:
Q: Detailed differences between type annotation `variable: type` and type assertion `expression as type` in TypeScript

Even with basarat explanations on type assertions in his great book TypeScript Deep Dive:

Basically, the assertion from type S to T succeeds if either S is a subtype of T or T is a subtype of S.

I was wondering what is the exact difference between type annotation variable: type and type assertion expression as type, more precisely when type assertion is working or not, especially regarding that TypeScript errors are sometime surprising: see them for the foo3 and foo5 variables bellow:
interface Foo {
    n?: number;
    s: string;
}

const foo1 = {} as Foo;               // ok
const foo2 = { n: 1 } as Foo;         // ok
const foo3 = { n: '' } as Foo;        // KO: "Property 's' is missing..."
const foo4 = { n: '' as any } as Foo; // ok
const foo5 = { n: 1, x: 2 } as Foo;   // KO: "Property 's' is missing..."
const foo6 = { s: '', x: 2 } as Foo;  // ok
const foo7 = { s: 1, x: 2 } as Foo;   // KO: "Types of property 's' are incompatible."

Other difference I've noticed: renaming the n property in the Foo interface in VSCode does not propagate to expressions being asserted, while it's working with type annotated variables.

A:
I was wondering what is the exact difference between type annotation
  variable: type and type assertion expression as type

Type declaration variable: type tells the compiler that the variable must always conform to the declared type. It is used by typechecker when a value is assigned to the variable (the value must be compatible with the declared type), and also whenever the variable is used (the declared type of the variable must be compatible with whatever way the variable is used in each particular place).
Type assertion overrides built-in type compatibility rules. It allows you to tell the compiler that you know that the value actually conforms to the type you give in the assertion, thus suppressing error message about type incompatibility. There are limits, however - you can't just assert that variable has any type you want (BTW there is any type just for that). As you quoted in the question, for type assertion to work,

the assertion from type S to T succeeds if either S is a subtype of T or T is a subtype of S

It works exactly in that way in each example:
const foo3 = { n: '' } as Foo; // KO: "Property 's' is missing..."

Here two types: {n?: number, s: string} and {n: string} are checked for compatibility - if any of them can be converted to another. It can't be done either way: in one way, {n: string} is missing non-optional s and n has the wrong type (must be number | undefined); in another way, {n?: number, s: string} has wrong type for n (must be string).
The complete error message is
Type '{ n: string; }' cannot be converted to type 'Foo'.
  Property 's' is missing in type '{ n: string; }'.

When reporting structural type incompatibility, the compiler chooses just one incompatible property to show in the error message - it could be any of the three incompatibilities mentioned above.

const foo4 = { n: '' as any } as Foo; // ok

Works because {n?: number, s: string} is compatible with {n: any}: the first one can be assigned to the second - any is compatible with anything, and s is just ignored (basically, a value is compatible with the type if it has all non-optional properties compatible with declared type)

const foo5 = { n: 1, x: 2 } as Foo;   // KO: "Property 's' is missing..."

{n: number, x: number} is not assignable to {n?: number, s: string} -s is missing, as compiler says:
Type '{ n: number; x: number; }' cannot be converted to type 'Foo'.
   Property 's' is missing in type '{ n: number; x: number; }'.

const foo6 = { s: '', x: 2 } as Foo;  // ok

Works because {s: string, x: number} is assignable to {n?: number, s: string}: s is OK, missing n is OK because it's declared as optional, extra x is ignored

const foo7 = { s: 1, x: 2 } as Foo;   // KO: "Types of property 's' are incompatible."

Type of s is incompatible:
Type '{ s: number; x: number; }' cannot be converted to type 'Foo'.
  Types of property 's' are incompatible.
    Type 'number' is not comparable to type 'string'.


text:
Q: expand DIV with contents when this contents are absolute positioning I tried to put two divs over each other like layers of some ontent
and because I dont know what content size will be,I gave tow divs POSITION:ABSOLUTE to set thew twise at the top left of their container
the problem is: the container dosent expand with absolute divs
I tried some jquery to set height of the child to the parent, but because the absolute child div doesnt have width or height from the beginning, the code didnt affect
$("div.selectionTabs.inner").css("height",$("div.selectionTabs.inner>div.productsTab.under").height()+"px");

A: Try this :
function placeElementOver(e1,e2){
 e1.style.position = "absolute";
 e1.style.left = e2.getClientRects()[0].left;
 e1.style.top = e2.getClientRects()[0].top;
 e1.style.width = e2.clientWidth;
 e1.style.height = e2.clientHeight;
}

Then just call
placeElementOver(div2,div1);

in some init function.


text:
Q: Keyboard shortcut to switch between Songs, Albums, Artists, Genres, Videos, Playlists in iTunes? I wasn't able to find keyboard shortcuts for switching between Songs, Albums, Artists, Genres, Videos, Playlists in iTunes. This is the only thing that is missing in order to have a complete keyboard experience.
Are there any shortcuts for this? And if not, can they be created and how?

A: You could assign shortcuts to scripts like this:
tell application "System Events" to tell window 1 of process "iTunes"
    if exists radio button 4 of radio group 1 of splitter group 1 then
        click radio button 4 of radio group 1 of splitter group 1
    else -- if the sidebar is not shown
        click radio button 4 of radio group 1
    end if
end tell

tell application "iTunes"
    set view of browser window 1 to user playlist "Music"
end tell
tell application "System Events" to tell window 1 of process "iTunes"
    if exists radio button 4 of radio group 1 of splitter group 1 then
        click radio button 4 of radio group 1 of splitter group 1
    else
        click radio button 4 of radio group 1
    end if
end tell

tell application "iTunes"
    set view of browser window 1 to (get user playlist 1 where special kind is none)
end tell

A: The following keyboard shortcuts work in the Music app (vers. 1.2.5.7)

*

*Cmd+Ctrl+1 switches to Recently Added

*Cmd+Ctrl+2 switches to Artists

*Cmd+Ctrl+3 switches to Albums

*Cmd+Ctrl+4 switches to Songs


text:
Q: A basic question about this identity in Lie group setting.
$\textbf{Problem.}$ Let $G$ be Lie group. Let $F:G\times G\rightarrow G$ denote the multiplication map. Identify the space $T_{(e,e)}(G\times G)$ with $T_{e}G\oplus T_{e}G$ by
  $$v\in T_{(e,e)}(G\times G)\mapsto\bigg(d\pi_{1}(v),d\pi_{2}(v)\bigg)$$
  where $\pi_{1}$ and $\pi_{2}$ are projections of $G\times G$ to the first and the second components, respectively. Show that $dF_{e}:T_{e}G\oplus T_{e}G\rightarrow T_{e}G$ is given by $dF(X,Y)=X+Y$.

I was little bit confused about interpreting the last identity.
If I plug in a function $f$ defined on $G$ on the both sides, the LHS becomes $dF(X,Y)(f)=(X,Y)(f\circ F)$ and the RHS becomes $(X+Y)(f)$. But it looks like then the LHS became a function on $G\times G$ and the RHS became a function on $G$. It doesn't look right to me so please let me know how to understand this.

A: I believe that the shorthand $\Bbb d F (X, Y) = X + Y$ means the following (it is important to apply it at points, to make thnigs clear). I shall use lower indices for applications at points.
If $F(g,h) = gh$, then $\Bbb d F : T_g G \oplus T_h G \to T_{gh} G$ is defined as follows:
$$\Bbb d _{(g,h)} F \ (X_g, Y_h) = \Bbb d _g (R_h) (X_g) + \Bbb d _h (L_g) (Y_h) .$$
Applying to some $f : G \times G \to G$, the right-hand side becomes $(f \circ R_h) (X_g) + (f \circ L_h) (Y_h)$, which is now fine.


text:
Q: Writing to Core Data from a secondary thread I have an HTTP call to a URL, which returns my data in JSON format, I parse it, then I have to load it in my Core Data context.
Now I am doing it (parsing - entities creation - commit) on the main thread, by using GCD (grand central dispatch) to dispatch a block on the main queue.
The http call is asynchronous, so it's ok, but the db loading is not, so it freezes my user interface: a UITableView backed by a NSFetchedResultsController.
What I'd like to do, is making these last tasks on a secondary thread, but don't know how!
I heard something about creating a second context, using that on the secondary thread, then trash it and "refresh" the "main" context, don't know how to explain.
Maybe is there a wwdc ed. video on this argument, too? I can't find valid documentation.
Can you help me, loading data in asynchronous way, so my table never stop scrolling?

A: There is a rule: One context for one thread. Create new context in your not main queue and work with it.
Add observer for this context:
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(<#Selector name#>)
                                      name:NSManagedObjectContextDidSaveNotification
                                      object:<#A managed object context#>];
After your parser is done and objects in context, save that context which will kick out notification. In main queue, catch this notification and on main queue context call - (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification.


text:
Q: How to compare combobox value with items in listbox - vb.net I have a combo box and a listbox.
All i want is, when i select a value(text) from the combobox to check if there is a same value(same text) at the listbox and if there is, then msgbox should display as "DATA FOUND"
i tried this code, but its not working
Dim i As Integer
    For i = 0 To ListBox1.Items.Count - 1
        If ComboBox1.SelectedItem = ListBox1.ValueMember Then
            MsgBox("DATA FOUND")
        End If

    Next i

Thanks in advance....

A: You are using two properties with a different meaning for your comparison.
SelectedItem is an object (could be anything depending on how you have filled the combo, ValueMember is just the name of a property to use as the actual value for the items in the ListBox.
However the two classes (ListBox and ComboBox) share the same pattern for storing their list items, so supposing that both are populated using a list of strings then your code could be
Dim curComboItem = ComboBox1.SelectedItem.ToString()
For i = 0 To ListBox1.Items.Count - 1
    If  curComboItem = ListBox1.Items(i).ToString() Then
        MsgBox("DATA FOUND")
        Exit For
    End If
Next i

A: If ComboBox1.SelectedItem = ListBox1.ValueMember Then

should be
If ComboBox1.SelectedItem = ListBox1.Items(i) Then

Notice that
    ComboBox1.SelectedItem
only works for items inside of the Collection. You can extend this to any text by the
    .text
parameter.
P.D.
Next i '???

A: Using real objects in your ComboBox and ListBox can often lead to better flexibility of your application.
For example, you have a car lot application, in which you have long list of available cars and you don't want to browse the entire list - you use ComboBox to select make and model, and do something with the items in your list box.
(in pseudo-code)
Your car object.
class Car
    ModelId
    ModelMake
    ModelName
    FullName = ModelMake & " " & ModelName
End Class

class AvailableCar Inherits Car
    IsOnTheLot
    VIN
    Price
    'etc
End Class

In your Form class
comboCarMakes.DataSource = GetListOfMakesOfCars() ' List of Car classes
comboCarMakes.ValueMember = "ModelId"
comboCarMakes.DisplayMember = "FullName"

listAvbailableCars.DataSource = GetListOfAvailableCars() ' List of AvailableCar classes
listAvbailableCars.ValueMember = "VIN"
listAvbailableCars.DisplayMember = "FullName"

Sub comboCarMakes_SelectedIndexChanged

    Dim car as Car = DirectCast(comboCarMakes.SelectedItem, Car)
    For i = 0 To listAvbailableCars.Items.Count - 1
        If  car.ModelId = DirectCast(listAvbailableCars.Items(i), AvailableCar).ModelId Then
            ' Do something
        End If
    Next
End Sub

Advantage - you have lots of information available immediately.


text:
Q: web app design issue regarding to JSF2 managed bean scope mechanism (request scope) I have a question about design problem caused by JSF2 managed bean scope mechanism (request scope).
I am building a web app using tabview component and datatable component of primefaces4. Each tab has one datatable with data retrieved from managed bean with request scope, which uses JDBC to get data from database. Therefore, every time user clicks on a tab, the managed bean will retrieve data from database. This is how the whole architecture is designed. Simple enough.
The purpose to use @RequestScoped for each ManagedBean is that users want to see real time data from database when they choose each tab (each request). All other scopes do not apply. Problem is that all tabs database accesses logic are executed when user chooses one tab. I think that is becaused of Ajax call request, so that every @RequestScoped beans are called.
This causes 2 drawbacks:
 1. bad performance. Users need to wait for 4-5 seconds to see the datatable appeared after all beans are executed.
 2. too much useless access to database.
My solution is to use Spring scheduler to manage all database accesses in seperate threads from managed bean, and then add a data cache layer to interact with managed bean. Spring scheduler may be designed to access database every 10 minutes, poll data and put them into data cache. So that managed bean will access all data in memory. Then I would like to use Primefaces Push API to push data to client side, so user don't need to refresh browser.
Obviously it is not in real time, but solves 2 problems stated.
Is there any other better or simplified solution ?
Thanks!
-------solution-----------

*

*change ManagedBean to sessionScoped

*add tabviewListener

*add tabview class to handle tab switch

*in tabview class, use method in this post to get managed bean at runtime.
JSF 2 : Accessing managed bean's instance in the phase listener object?

*in tabview page, use cache="true" to increase performance, and let tabViewListner to update the whole tabview component which will update datatables inside.

A: You should change the beans be viewscoped and change the page logic to update the table upon a tab click, instead of throwing the whole bean away after each request.  Look into PrimeFaces ajax requests and upon a tab click, call a method on the bean that retrieves fresh data that can then be referenced by the p:dataTable, etc.


text:
Q: Links to open apps in iOS I want to open apps using a link. So when you tap a link in safari, you open an app.
I had already found these links:
Message  --- sms:
Maps --- maps://
App Store --- itms-apps://
iTunes --- itms://
Safari --- http://blanksafari.com/
iBooks --- ibooks://
Videos --- videos://
Music --- music://
Mail --- mailto:
Reminders --- x-apple-reminder://
Calendar --- calshow://

I also want to open following apps with a link, so my question is… What is the link to open those apps?
Phone
Photos
Camera
Clock
Game Center
Notes
Passbook
Settings
Facetime (app is in iOS 5 and iOS 7)
Weather
Contacts
Calculator
Stocks

A: The apps would need to have a custom URL scheme registered in their info.plist. A registry site was launched a while back in an attempt to make it easier for developers to discover existing custom URL schemes: http://handleopenurl.com/
Unfortunately, the site has been blacklisted by Norton Safe Web, so click at your own risk.
UPDATE: The site is no longer available. Click on the original link only if you want to fall into the vast emptiness of the web or visit the Wayback Machine at Internet Archive to see the site in its glory days.
https://web.archive.org/web/20161128234603/http://handleopenurl.com/

A: Have to many possibility, here there a calling from Safari from developer.apple.com:
iPhoneURLScheme Reference
Here there a youtube dev for chrome mobile
Youtube scheme for chrome
This Is for Linkedin: linkedin://profile/{id}
The best way to get all information is to learn the PhoneGap Scheme, and if you want with phoneGap you can try to convert your web app in to a Partial Native app in Xcode.
Hope this help you.


text:
Q: Building a chrome extension that scrapes data from a webpage I want to try building a chrome extension, but I just wanted to ask around to make sure it was actually possible first, as I have never built a chrome extension before.
My idea for the extension is that it finds and returns prices of commodities from the frontpage of a site and then displays this information depending on what commodities the user wishes to see.
This is rather vague, but this is pretty much all that needs to be done. I thought this could definitely be done, but I am starting to doubt myself after seeing some other posts saying things like it would not be possible if the tab wasn't open to that page.
Feedback on the feasibility of this would be appreciated.
Also would any languages besides HTML/CSS and JS be needed to implement this?
Thanks!


text:
Q: Make UITextField not to draw image attachment but keep its frame UITextField have very bad performance on drawing image attachments while scrolling on iPhone 6+/6s+. I am working on some subviews solution to overlap attachments with UIImageViews. It works well, but I need UITextView to stop drawing this attachments but keep attachment frames on their places.
I know about NSTextContainer exclusionPaths property, but not sure it will works well for async image loading. Image sizes will be known after downloading.

A: Found working solution by nilling [NSTextAttachment image] and restoring bounds:
CGRect bounds = attachment.bounds;
attachment.image = nil;
attachment.bounds = bounds;