text:
Q: Mac app crashes on launch, linked framework not bundled (Edit: I was able to bundle the framework but it still would not take the changed installation directory. So, below, the question has changed to "linked and bundled framework image not found")
The Mac app was submitted to MAS but rejected by Apple, for a very reasonable reason: a framework that was linked was not bundled.
I simply ask how I can make sure it is included correctly in the bundle, and confirm that on my Mac before submitting again.
Please let me know what/any extra information you need from me.
Edit: More information after following subzero's instructions.
When going Product > Build, .app files end up in Documents/build/Release on my machine.
Here's how my build phases look - https://dl.dropbox.com/u/19155207/copyframeworks.jpg
and a UIKit.Framework folder is inside WinKonto.app/Contents/Frameworks containing this: https://dl.dropbox.com/u/19155207/frameworksfolder.jpg
It still gives the same error if I run it from the Releases folder. Only when I run it from XCode it works. Can you see something wrong?
Edit 2: I've gotten the framework file (UIKit) into the bundle.
Here is the crash report error message:

Dyld Error Message:   Library not loaded:
  Frameworks/UIKit.framework/Versions/A/UIKit   Referenced from:
  /Users/henrikerlandsson/Documents/build/Release/WinKonto.app/Contents/MacOS/WinKonto
  Reason: image not found

But the framework is in the bundle, and it was modified by install_name_tool before being added to the project.
I don't know why that modification didn't work, but I made it a private framework instead and changed the installation directory there instead, and it worked (see my answer).

A: In XCode,

*

*Add a Copy Files build phase to your application's target

*Move this above the Link phase set its destination to myApp.app/Contents/Frameworks and add the framework to it.

A: I made it a private framework. I followed the instructions under Embedding a Private Framework in Your Application Bundle, and that let me set the framework's Installation Directory properly to where it appeared in the bundle.


text:
Q: Web Api Server Side Processing and DataTables parameters I'm trying to create an object that represents the values that datatables supplies to my web api call, which I'll then route to another api that actually returns the values (to separate the datatables nonsense from the api interface).
After researching a bit on the datatables wiki I ended up with the following objects defined:
public class DataTableParameters
{
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public order[] order { get; set; }
    public column[] columns { get; set; }
}

public class order
{
    public int column { get; set; }
    public string dir { get; set; }
}

public class column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public search search { get; set; }
}

public class search
{
    public string value { get; set; }
    public bool regex { get; set; }
}

However, when I try to use them as arguments to the DataTables api controller, it comes out null:
    public DataTableResult Get(DataTableParameters parameters) //parameters is null!
    {
         return new DataTableResult();
    }

As far as I understood it, model binding should be reading the result and applying it to my object. This is an example call to the api from the front end:
Key Value
Request GET /MVC/api/DataTables?action=Get&draw=1&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1440437669357 HTTP/1.1

Why is my parameters object null, and how can I fix it?
Edit: I also attempted this:
 public DataTableResult Get(int draw, int start, int length, column[] columns, order[] order)
    {
        return new DataTableResult();
    }

But I get "Can't bind multiple parameters ('columns' and 'order') to the request's content."

A: UGH less than 10 minutes later, I need a [FromUri] attribute on the parameters.
 public DataTableResult Get([FromUri]DataTableParameters parameters)
 {
      return new DataTableResult();
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keep home folder from OpenSuse 12 to Leap I currently run OpenSuse 12.3 (Dartmouth) and since it is no longer supported I would like to perform a clean install for latest OpenSuse Leap and keep my existing files inside home folder. I have a separate "home" partition. If during the installation I keep the home partition and do not format it, will I get compatibility problems?

A: you could run into compability problems if config files change their format or if you have plugins included in your dotfiles (e.g. firefox).
Just give it a try. I've used the same home directory on a dual boot system for Arch and openSuSe and went well with it.
You should watch out for files like .xinitrc where typically a window manager is specified. So be sure you have all applications installed that are referenced by scripts in your home directory.
If you plan to do some clean up though, I would backup my home directory first, start out with a fresh one to have sane defaults and then copy over only the stuff I need.

A: Be sure to check device related to home.
df /home
Filesystem     1K-blocks   Used Available Use% Mounted on
/dev/sda3       95164008 368388  94795620   1% /home

in this case /dev/sda3.
During the install you will be given a choice to select partitionning.
(see official documentation §6)
Note

*

*that / must be at least 20 Gb.

*If you have time, disk and memory, you may try install/upgrade on a virtual host.

*You may also retrieve leap repository and do an upgrade.


text:
Q: having an array that can be accessed from all viewControllers i have a root view controller that has a container view embedded that links to my TabBarController and 4 different tab views. The root view controller is embed in a Navigation Controller as i have a couple of buttons that allow for measurement changes and a geographical location selection.
Rather than each tab loading the same data each time(as current), i wish to load the data into arrays via the root view controller and then access these 4 NSMutableArrays from each of the 4 tabs. what would be the more efficient and correct practice way to do this?  I also have a timer setup in the root controller so these NSMutableArrays update with extra data anywhere from 5 seconds to 5 minutes, user set as loading live weather information.

A: Global variables are not exactly something I'd recommend as a design pattern, but if you feel it's necessary for each controller to have this data, the best approach would be a singleton.
Imagine that the data in question is an array of co-ordinates. If I had to give multiple objects access to this data, I would probably implement it in this way:

*

*I would create a class which manages the data. In this case, I would call it LocationDataManager.

*On this class, I would create a class method which return a shared instance of the class.
-
/**
 *  Returns a shared instance of this class.
 *
 *  @return A singleton instance of this class.
 */
+ (instancetype)sharedInstance
{
    static LocationDataManager *sharedInstance;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,
    ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

Obviously you would need to declare the method in the public interface in the .h file:
/**
 *  Returns a shared instance of this class.
 *
 *  @return A singleton instance of this class.
 */
+ (instancetype)sharedInstance;

*

*I would then add a property to this class with all of the data. I would declare it in the public interface as read only:

-
/** An array of the location data.  */
@property (nonatomic, strong, readonly) NSArray *locations;

In the implementation I would use the getter method to return the necessary data:
- (NSArray *)locations
{
    return @[coordinateA, coordinateB, coordinateC];
}


text:
Q: Color in python's colorama not unset even with Fore.RESET I use colorama to stylize the output of tqdm in a way similar to this:
tqdm.pandas(f'{Fore.CYAN}some prefix text {Fore.RESET} some text {Fore.MAGENTA} Some message')
some prefix text is cyan, and Some message is magenta, but some text is somehow red! I actually need it to be white, i.e. the general color of the console, but as you probably know Fore.WHITE is not exactly white but somewhat gray, so it won't work.
Could anybody explain how this works, why I get it red, and what can I do here? Thank you very much.

A: My suggestion would be to use Style.RESET_ALL from the Style object instead of Fore.RESET
The solution would look like this:
from colorama import Fore, Style

tqdm.pandas(f'{Fore.CYAN}some prefix text {Style.RESET_ALL} some text {Fore.MAGENTA} Some message {Style.RESET_ALL}')


text:
Q: Changing DataGridViewButton Color C# I am trying to figure out how to change the colour of my button but it seems to be overwritten by my code for alternating row colours, i cant figure out how to make it so i can have alternating row colours and have a red delete button.
Button Code:
DataGridViewButtonColumn btnDelete = new DataGridViewButtonColumn();
        dgvCarsPurchased.Columns.Add(btnDelete);
        btnDelete.HeaderText = "Delete";
        btnDelete.Text = "Delete Record";
        btnDelete.Name = "btnDelete";
        btnDelete.DefaultCellStyle.ForeColor = Color.White;
        btnDelete.FlatStyle = FlatStyle.Flat;
        btnDelete.DefaultCellStyle.BackColor = Color.Red;

        btnDelete.UseColumnTextForButtonValue = true;

Alternating Row Colours
this.dgvCarsPurchased.RowsDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#3E606F");
        this.dgvCarsPurchased.AlternatingRowsDefaultCellStyle.BackColor =
            ColorTranslator.FromHtml("#91AA9D");

A: Basically you need to change DefaultCellStyle to CellTemplate.
Example:
btnDelete.FlatStyle = FlatStyle.Flat;
btnDelete.CellTemplate.Style.BackColor = Color.Red;
btnDelete.CellTemplate.Style.ForeColor = Color.White;

A: I recommend you use the CellFormatting event:
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex != btnDelete.Index || e.RowIndex < 0)
        return;

    if (e.RowIndex % 2 == 0)
        e.CellStyle.BackColor = ColorTranslator.FromHtml("#3E606F");
    else
        e.CellStyle.BackColor = ColorTranslator.FromHtml("#91AA9D");
}

Reference: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellpainting(v=vs.110).aspx


text:
Q: How to import a function from one typecript from another? I have a typescript file name SettingHelper.ts under '~\Modules\Common\Helpers' which contains a export function GetsettingValue
I tried to import this function by writing this:
import { GetsettingValue } from "./SettingHelper"
import { GetsettingValue } from "./Modules/Common/Helpers/SettingHelper"

But, both are giving compile error like:
cannot compile modules using option 'outfile' unless the '--module' flag is 'amd' or 'system'
Cannot find module
Source File(.ts):
namespace TourExpAdmin.SettingsDB {

    export function GetsettingValue(SettingName: string) {

        //codes

        return myresult;

    }

}

Calling File(.ts):
import { GetsettingValue } from "./SettingHelper"
namespace TourExpAdmin.SettingsDB {

    @Serenity.Decorators.registerClass()
    export class SettingsDialog extends Serenity.EntityDialog<SettingsRow, any> {
        protected getFormKey() { return SettingsForm.formKey; }
        protected getIdProperty() { return SettingsRow.idProperty; }
        protected getLocalTextPrefix() { return SettingsRow.localTextPrefix; }
        protected getNameProperty() { return SettingsRow.nameProperty; }
        protected getService() { return SettingsService.baseUrl; }
        protected getDeletePermission() { return SettingsRow.deletePermission; }
        protected getInsertPermission() { return SettingsRow.insertPermission; }
        protected getUpdatePermission() { return SettingsRow.updatePermission; }

        protected form = new SettingsForm(this.idPrefix);

        protected getToolbarButtons() {
            var buttons = super.getToolbarButtons();

            buttons.push(
                {
                    title: "Setting Fetcher",
                    cssClass: 'settingFetcher-button',
                    onClick: () => {

                        let MySetting = "TestSetting1";
                        let MySettingValue = SettingHelper.GetsettingValue(MySetting);

                        Q.notifySuccess(MySetting + " has value of: " + MySettingValue);
                    },
                });
            return buttons;
        }

    }
}


text:
Q: C++ User login program only reads the first line of file void abc::loginUser()
{
    abc x;
    fstream file;
    char usr[25];
    string pwd = "",line;
    int ch;
    file.open("user.txt"),ios::in;
    cout << "User Login" << endl;
    cout << "Username: ";
    gets(usr);
    cout << "Password: ";
    file.seekg(0);
    while(ch = getch())
    {
        if(ch == 13)
        {
            while(file)
            {
                file >> user.username >> user.password;
                if(strcmp(usr,user.username)==0)
                {
                    if(pwd != user.password)
                    {
                        file.close();
                        cout << "\nLogin Failed";
                        getch();
                        system("cls");
                        x.login();
                    }
                    else if(pwd == user.password)
                    {
                        file.close();
                        cout << "\nLogin Successful";
                        getch();
                        system("cls");
                        x.menuUser();
                    }
                }
                else if(strcmp(usr,user.username)!=0)
                {
                    file.close();
                    cout << "\nUser Not Registered";
                    getch();
                    system("cls");
                    x.login();
                }
                else
                {
                    file.close();
                    cout << "\nLogin Failed";
                    getch();
                    system("cls");
                    x.login();
                }
            }
        }
        else if(ch == 8)
        {
            if(pwd.length() > 0)
            {
                cout<<"\b \b";
                pwd.erase(pwd.length()-1);
            }
        }
        else
        {
            cout << "*";
            pwd += ch;
        }
    }
}

Does anyone know why the program only reads the first line of user.txt file? I can't seem find a way to fix this issue, tried the file.read method but it also doesn't work.
Is there anything that i should change to improve my code?
Can you guys please help me, a beginner here.
(sorry for my bad english, not my main language)


text:
Q: create a list with pairs from a column in pandas I have a column with pairs like these

id
pairs

1
a,b,c

2
b,d

3
a

4
d,e

5
g,h

6
a,h

7
f,d

8
o,p

I want to have these output
[('ca', 'b'), ('a', 'c'),('b','c'),('b','d'),('d','e'),('g','h'),('a','h'),('f','d'),('o','p')]

I did these, but not the desired solution
for pair in combinations([df['pairs']], 2):
print(pairs)

any suggestions?

A: try this
pairs = []

for row in df['pairs']:
    row_list = row.split(',')
    for pair in combinations(row_list, 2):
        pairs.append(pair)

print(pairs)


text:
Q: How can I send the JSON coming from a POST request to the client? I have a node server running with express which listens to incoming requests. I am rendering an HTML file which I would like to update when I receive a GET request in my server. However, the data that is sent to my server is sent by an API when an external event happen (asynchronously). I don't know how to update the HTML file I'm serving with the JSON content of the incoming request. Particularly, I am trying to replace the inner.HTML content of the incoming class as you can see in my code.
I have tried to use the fetch API on the client side to make a request to the server to retrieve this data, but it doesn't seem to work.
Server.js
const bodyParser = require('body-parser');
const port = 3000;

const app = express();
const server = app.listen(port, () => console.log('App listening on port ${port}'));

app.set('view engine', 'html');
app.engine('html', ejs.renderFile);

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true}));

app.get ('/incoming', (req,res)=>{

  const { status} = req.url;

  res.json(status);
  console.log(status);

}) ```

Client.js

fetch('http://localhost:3000/incoming').then(function(response) {
  return response.json();
}).then(response => {
  document.getElementById("dlr").innerHTML = response
}).catch(error => console.error(error))

index.html

 <!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/css-layout/1.1.1/css-layout.js" />
  <title>Node SMS Texting</title>

Text API

    <input type="sender" name="from" id="from" placeholder="Enter sender ID ...">
    <input type="button" id="button" value="Send Text" class="button button-primary">

I get the result logged in the console as per my console.log in the server side, but the client doesn't receive anything. This is the console.log

/incoming?user=A&to=Me&code=21404&Id=150000001A01F77B&&timestamp=2019-04-08+15%3A57%3A15&timestamp=1554739095&nonce=59167e2f-654c-4dd5-b236-bff9ac97f917

The only thing I see happening on the client side is /incoming set as text  set under the incoming.innerhtml class, but not the content of the GET request sent to my server.

Any help here would be highly appreciated.

Thanks in advance.

Regards,
Javier

A: You are sending a GET request to a POST endpoint. This you can fix by passing a body and a method in your fetch on client side. Also, you should handle the response as it comes back. Rewrite your fetch to something like this.
fetch('http://localhost:3000/incoming', {
  method: 'post',
  body: JSON.stringify(body)
}).then(response => {
  document.getElementById("incoming").innerHTML = response
}).catch(error => console.error(error))


text:
Q: iron router, trying to create a contacts app with a separate page for each contact I am trying to make it so that each contact has a particular set of values in the collection like a first name, a last name and an email. I want each time a contact is selected from the list for it to link to a second page where all the details for that contact are displayed.
This is the code I have placed at the top of my Contact.js file...
Router.route('/post/:_id', function () {
    this.render('Post', {
  data: function () {
    return Contax.findOne({_id: this.params._id});
  }
  });
});

And this is the event handler for when a particular contact is selected...
Template.aCont.events({
    "click #view": function() {
      Router.go('/post/:' + this._id);
    }
  });

And here is my relevant html
<template name="contDeets">

{{this.firstName}}, {{this.lastName}}

</template>

<template name="Post">
  {{#contentFor "headerButtonLeft"}}
    {{>ionNavBackButton}}
  {{/contentFor}}
  {{#contentFor "headerTitle"}}

Contacts

  {{/contentFor}}
  {{#contentFor "headerButtonRight"}}
  Add
  {{/contentFor}}
  {{#ionView}}
    {{#ionContent}}

        {{> contDeets}}

     {{/ionContent}}
  {{/ionView}}
</template>

What is wrong with my code? It is opening a new page with the correct url however the information it should be displaying...{{this.firstName}}, {{this.lastName}}... isn't there at all except for the comma.

A: The colon in the route declaration is to mark parameters. When calling the route you must not include it but just provide the value you want for the parameter:
Template.aCont.events({
    "click #view": function() {
      Router.go('/post/' + this._id);
    }
});

Everything else looks good.


text:
Q: Navigation bar title color looks different from app to app in ios I have created two app. In both the apps I have used the navigation Controller and have used the same code. But in first app the navigation bar title appears as white but in second its black.. Can anyone help me to solve this.
I didnt use any code for separately for navigation bar.
Thanks in advance.


text:
Q: How to calculate the speed of a collapse? Let's suppose i'm using dominoes or card pyramids or any other structure.
How could I calculate the maximum speed of a pancake collapse? How close to free fall could it get? What variables should be taken into consideration?


text:
Q: Overwrite a global JavaScript function in TypeScript In JavaScript, I can overwrite a function:
function testf() {
    console.log('old function')
}
testf = function() {
    console.log("new function");
}

How can I do this in TypeScript? I'm writing a WebP polyfill and would like to overwrite the global createImageBitmap function, but tsc complains:
Cannot assign to 'createImageBitmap' because it is not a variable.

A: Doing someName = whatever requires that someName is defined within the current scope as a variable.
You can, however, assign to window (same as assigning the variable of any other object), which should produce the same effect:
window.createImageBitmap = customImageBitmap

Just make sure customImageBitmap has the same signature (argument types and return types) as window.createImageBitmap in order for this to pass the type checker.


text:
Q: Install Linux on a second disk from an already running Linux (RHEL 7.8) instance I am trying to mount a second disk on a running Linux (RHEL 7.8) AWS instance, install a customized bootable Linux environment to it, and then change that disk to an AMI so we can boot new Linux instances from it. Since this is in the cloud, I don't have the ability to boot an ISO or kickstart to run the standard installation procedures. I realize this is a roundabout way to do this, but let's just say it's a requirement.
I create a partition on the disk, create the XFS filesystem, mount it, and install the Base and Core group of packages to it, as well as the kernel and grub2 packages. No issues there. I run a grub2-install on the new disk, and then chroot to its path and run grub2-mkconfig -o /boot/grub2/grub.cfg. I did make sure to use the UUID for the new disk in the fstab, and verified that the disk UUID was being used in the grub configurations.
I then shutdown the instance, snapshot the volume, and then turn that snapshot into an AMI. No issues there. Booting up an instance from it, I was able to get a login prompt. That's as far as I've been able to get, though. It seems sshd never starts up, so I can't access it, I'm just seeing the system log showing me a login prompt. No matter what I do, I can't seem to get the openssh server to startup and respond. I did verify the symlink systemd uses to enable processes is in place for sshd. I'm assuming I'm missing some configuration, or additional packages I need to get a functioning Linux instance. There doesn't seem to be much information out there on how to do something like this, but it seems like it should be possible with the right mix of packages and configurations.


text:
Q: how does this error means in react-router-dom? when I import switch from react-router-dom error screen shot
when I import switch from react-router enter image description here
I copied code from https://v5.reactrouter.com/web/guides/quick-start

A: Switch is exported from "react-router", not from "react-router-dom"
Convert this:
import { Switch } from "react-router-dom";

to:
import { Switch } from "react-router";

A: Hello because Switch is exported from react-router
import { Switch } from "react-router";

A: I have faced similiar problem with importing Switch from react-router-dom. In my case, I was using the latest (v6, i think) version of react-router-dom where the "Switch" is replaced by "Routes".
So either you check your react-router-dom's version and replace Switch to Routes and change the Route declaraton from <Route path="/" component={Dashboard} /> to <Route path="/" element={Dashboard} /> if it's v6, or you want to downgrade your react-router-dom version and keep using Switch.
Your call.

A: Try to install npm i react-router-dom@5.2.0 this version Switch working in this version


text:
Q: Google Website Optimizer Multivariate test not saving __utmx cookie? I'm trying to run a multivariate test across 3 pages, google says this should be ok, as long as you use the same section names, it doesn't care about the url so much.
so I have checked in google optimizer, it says all my scripts are set up correctly.
Also the strange thing is it DOES work, it replaces the content, but it never ever saves a cookie, so when you get to the next page, or even just refresh the same page, you might get a different variant.. Which obviously shouldn't happen.
I'm pulling my hair our here, any help would be appreciated.

A: I had the exact same problem.  I've run several tests with GWO and never had this issue.  However, with my latest MVT, at first I wasn't seeing GWO even set the cookie.  Then, it started setting the cookie but was not able to read the cookie.
Although I am running a sitewide, MVT, I am not running it across multiple domains.  However, in order to get GWO to set and read the cookie correctly, I found that I needed to use some of the code required for sitewide tests that span multiple domains.  Here is the google article on cross domain tracking:
http://www.google.com/support/websiteoptimizer/bin/answer.py?hl=en&answer=151978
According to the Google WSO API, by default, GWO is setting this property:
gwoTracker._setDomainName("auto");
For whatever reason, it was my experience that this was not happening and by making this call explicitly in my code, it fixed the problem!  This call needs to be added to both your Tracking Script and your Conversion Script.
Again, I've never experienced this with any of my other GWO tests, so it was kind of weird to have it happen out of the blue but explicitly making this call fixed this problem for me.  Good luck.


text:
Q: Is Kakutani's Theorem true for the Euclidean plane? The following  analogue of Kakutani's theorem has been proved by F. J. Dyson (MR44620)

Theorem (F. J. Dyson 1951):  Let $\Bbb S^2$ be the surface of a sphere with center $Z$ in Euclidean $3$-space $\Bbb R^3$, and let $f(x)$ be a continuous real-valued function defined on $\Bbb S^2$. Then there exist four points $x_1 , x_2 , x_3 , x_4$ on $\Bbb S^2$ forming the vertices of a square with center $Z$, such that
  $$f(x_1)=f(x_2)=f(x_3)=f(x_4).$$

Is the above theorem true for $\Bbb R^2=\Bbb S^2\backslash\{\infty\}$? i.e. are there four points $x_1 , x_2 , x_3 , x_4$ on $\Bbb R^2$ forming the vertices of a square with center $Z$ (probably the origin), such that
$$f(x_1)=f(x_2)=f(x_3)=f(x_4)?$$

A: No, let $f(x,y)=x$. Then the level sets of $f$ are straight lines $x=c$, and a straight line cannot contain a square.


text:
Q: Operation is not valid due to the current state of the object i am beginning in develop winphone and nokia imaging sdk. i have two function.
firstly, i call the function below to change image to gray color
 private async void PickImageCallback(object sender, PhotoResult e)
    {
        if (e.TaskResult != TaskResult.OK || e.ChosenPhoto == null)
        {
            return;
        }
            using (var source = new StreamImageSource(e.ChosenPhoto))
            {
                using (var filters = new FilterEffect(source))
                {
                    var sampleFilter = new GrayscaleFilter();
                    filters.Filters = new IFilter[] { sampleFilter };
                    var target = new WriteableBitmap((int)CartoonImage.ActualWidth, (int)CartoonImage.ActualHeight);
                    var renderer = new WriteableBitmapRenderer(filters, target);
                    {
                        await renderer.RenderAsync();
                        _thumbnailImageBitmap = target;
                        CartoonImage.Source = target;
                    }
                }
            }
        SaveButton.IsEnabled = true;
    }

then i call function to change image to binary color
private async void Binary(WriteableBitmap bm_image)
    {
        var target = new WriteableBitmap((int)CartoonImage.ActualWidth, (int)CartoonImage.ActualHeight);
        MemoryStream stream= new MemoryStream();
        bm_image.SaveJpeg(stream, bm_image.PixelWidth, bm_image.PixelHeight, 0, 100);

        using (var source = new StreamImageSource(stream))
        {
            using (var filters = new FilterEffect(source))
            {
                var sampleFilter = new StampFilter(5, 0.7);
                filters.Filters = new IFilter[] { sampleFilter };

                var renderer1 =new WriteableBitmapRenderer(filters, target);
                {
                    await renderer1.RenderAsync();
                    CartoonImage.Source = target;
                }
            }
        }
    }

but when it run to " await renderer1.RenderAsync();" in the second function, it doesn't work. How can i solve it. And you can explain for me about how "await" and "async" work ?
thank you very much!

A: I'm mostly guessing here since I do not know what error you get, but I'm pretty sure your problem lies in setting up the source. Have you made sure the memory stream position is set to the beginning (0) before creating an StreamImageSource?
Try adding:
stream.Position = 0;

before creating the StreamImageSource.
Instead of trying to create a memory stream from the writeable bitmap I suggest doing:
using Nokia.InteropServices.WindowsRuntime;

...

using (var source = new BitmapImageSource(bm_image.AsBitmap())
{
   ...
}


text:
Q: ¿Por qué no puedo hacer uso de android.support.annotation? Buenas, estoy intentando hacer uso de BluetoothAdapter.java pero no funciona debido a que no puede resolver símbolos como IntDef, RequiresPermission, etc...
Este es el código donde lo uso.
btnNewPairing.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                if(arrayDevices != null)
                    arrayDevices.clear();

            // Comprobamos si existe un descubrimiento en curso. En caso afirmativo, se cancela.
               if(bAdapter.isDiscovering())
                 bAdapter.cancelDiscovery();

                // Iniciamos la busqueda de dispositivos y mostramos el mensaje de que el proceso ha comenzado
                if(bAdapter.startDiscovery())
                    Toast.makeText(getBaseContext(), "Iniciando búsqueda de dispositivos bluetooth", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(getBaseContext(), "Error al iniciar búsqueda de dispositivos bluetooth", Toast.LENGTH_SHORT).show();

Y las dependencias son las siguientes:
dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:support-annotations:24.2.1'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.test.espresso:espresso-core:2.2.2'
    /* androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
                      exclude group: 'com.android.support', module: 'support-annotations'
                    })*/
    compile 'com.android.support:design:24.+'
    compile 'org.slf4j:slf4j-api:1.7.7'
    testCompile 'junit:junit:4.12'
    apply plugin: 'realm-android'
}

¿ALGUIEN PUEDE AYUDARME?
Gracias

A: Puedes verificar en al pagina oficial de Android tiene un apartado que hablan del https://developer.android.com/guide/topics/connectivity/bluetooth.html#Permissions y https://developer.android.com/studio/write/annotations.html. Ya que la información y fragmentos de código que das, no se logra ver cual es el problema.
Saludos


text:
Q: C# handling UI - Output Hello my fellow programmers,
this question is most likely pretty dumb, because I think I misunderstood something in my C# class at school.
The task is to create a simple UI-Form to check if a Website is available. The UI is already done and consists of 4 Textboxes which shall be filled with True or False if its reachable or not.
namespace Test_WebsiteChecker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void checkLinks_btn_Click(object sender, EventArgs e)
        {

            getTextBox0 = WebSiteIsAvailable("some website").ToString();
            getTextBox1 = WebSiteIsAvailable("some website").ToString();
            getTextBox2 = WebSiteIsAvailable("some website").ToString();
            getTextBox3 = WebSiteIsAvailable("some website").ToString();

        }

        public string getTextBox0
        {
            get { return LinkToCheck.Text; }
            set => LinkToCheck.Text = value;
        }

        public string getTextBox1
        {
            get { return linkToCheck1.Text; }
            set => linkToCheck1.Text = value;
        }

        public string getTextBox2
        {
            get { return linkToCheck2.Text; }
            set => linkToCheck2.Text = value;
        }

        public string getTextBox3
        {
            get { return linkToCheck3.Text; }
            set => linkToCheck3.Text = value;
        }

        public bool WebSiteIsAvailable(string Url)
        {
            string Message = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "GET";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                }
            }
            catch (WebException ex)
            {
                //TODO message für fehler?
                Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
            }

            return false;
        }

    }
}

I previously tried instead of the getTextBox0 the attempt to use inside the button function
linkToCheck.Text = WebSiteIsAvailable("site").ToString();

But this got me the error, that linkToCheck is not defined. Can anybody explain me what I am doing wrong?


text:
Q: DParser: Unresolved Ambiguity I have a large grammar written for DParser format and using the Python binding.  When I parse a code using this grammar, I get the following exception but with different symbols depending on what code I pass to it.  But the ambiguous symbols are always the same non_terminal.  How do I find out what the ambiguity is?
Traceback (most recent call last):
  File "parser.py", line 2030, in ambiguity
    raise dparser.AmbiguityException("\n\nUnresolved ambiguity!  Symbols:\n  " + '\n'.join([node.symbol for node in nodes]))
dparser.AmbiguityException:

Unresolved ambiguity!  Symbols:
  non_terminal
  non_terminal

Any hints or ideas would be appreciated.


text:
Q: Transactional Emails not sending to Hotmail I am testing my transactional emails currently and have noticed that none of the emails are being sent to Hotmail addresses. I have tested with other addresses with personal domains and they receive fine, so too does Gmail account. But any Hotmail emails don't seem to get received.
Is there a reason for this? Is there a setting I'm missing?

A: This is common with webmail providers. Look into the other answers on this forum about setting up DKIM/DomainKeys/SenderId/SPF or consider moving to a hosted SMTP service.

Deliverability issues can be a number of things including:
Email/domain blacklisting SPF/DKIM and DomainKeys, SenderId
  configuration Firewall/port configuration Mail transport
  misconfiguration Check /var/maillog on your server (for Linux, not
  sure for Windows-side) and ensure proper configuration of sendmail or
  postfix (again, Linux).
Some trustworthy SMTP relays:
http://sendgrid.com/
http://www.socketlabs.com/

Source: Me. https://magento.stackexchange.com/a/7632/336


text:
Q: Unsaved Changes Error in Lightning Experience We have a custom object "Quote". Whenever I go to any Quote record and try to navigate to some other record or home page, it gives me below error in lightning experience:

I have tried with other custom objects and also with standard object but no issue is occurring for that. I also tried by removing the feed tracking for this object but still no success. The behavior I have noticed is that, if there will be any editable field on Layout, this error popup comes on UI. When I removed all of the fields from layout, this error popup didn't come.
I tried with the classic view and it's working fine there.
Can anyone please suggest what could be the issue in it ?

A: Do you have the Name field on the page layout?  I have found that removing that field caused the Unsaved Changes error to start occurring, and adding it back again resolved the problem.
I believe this is (or should be) a bug, but at least there seems to be a simple workaround to avoid it.


text:
Q: Getting memory error during preprocessing HMDB51 dataset I am working on action recognition on HMDB51. Here is my code below.
This part is for declaring some constants and directories:
# Specify the height and width to which each video frame will be resized in our dataset.
IMAGE_HEIGHT , IMAGE_WIDTH = 64, 64

# Specify the number of frames of a video that will be fed to the model as one sequence.
SEQUENCE_LENGTH = 20

# Specify the directory containing the UCF50 dataset.
DATASET_DIR = r"\HMDB51"

# Specify the list containing the names of the classes used for training. Feel free to choose          any set of classes.
CLASSES_LIST = ["brush_hair", "cartwheel", "catch", "chew", "clap", "climb", "climb_stairs", "dive",
            "draw_sword", "dribble", "drink", "eat", "fall_floor", "fencing", "flic_flac", "golf",
            "handstand", "hit", "hug", "jump", "kick", "kick_ball", "kiss", "laugh",
            "pick", "pour", "pullup", "punch", "push", "pushup", "ride_bike", "ride_horse",
            "run", "shake_hands", "shoot_ball", "shoot_bow", "shoot_gun", "sit", "situp", "smile",
            "smoke", "somersault", "stand","swing_baseball", "sword", "sword_exercise", "talk", "throw", "turn",
            "walk", "wave"]

This part is for extracting frames from each video:
def frames_extraction(video_path):
# Declare a list to store video frames.
frames_list = []

# Read the Video File using the VideoCapture object.
video_reader = cv2.VideoCapture(video_path)

# Get the total number of frames in the video.
video_frames_count = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))

# Calculate the the interval after which frames will be added to the list.
skip_frames_window = max(int(video_frames_count/SEQUENCE_LENGTH), 1)

# Iterate through the Video Frames.
for frame_counter in range(SEQUENCE_LENGTH):

    # Set the current frame position of the video.
    video_reader.set(cv2.CAP_PROP_POS_FRAMES, frame_counter * skip_frames_window)

    # Reading the frame from the video.
    success, frame = video_reader.read()

    # Check if Video frame is not successfully read then break the loop
    if not success:
        break

    # Resize the Frame to fixed height and width.
    resized_frame = cv2.resize(frame, (IMAGE_HEIGHT, IMAGE_WIDTH))

    # Normalize the resized frame by dividing it with 255 so that each pixel value then lies between 0 and 1
    normalized_frame = resized_frame / 255

    # Append the normalized frame into the frames list
    frames_list.append(normalized_frame)

# Release the VideoCapture object.
video_reader.release()

# Return the frames list.
return frames_list

This part is for creating train, label lists:
def create_dataset():
    '''
    This function will extract the data of the selected classes and create the required dataset.
    Returns:
        features:          A list containing the extracted frames of the videos.
        labels:            A list containing the indexes of the classes associated with the videos.
        video_files_paths: A list containing the paths of the videos in the disk.
    '''

    # Declared Empty Lists to store the features, labels and video file path values.
    features = []
    labels = []
    video_files_paths = []

    # Iterating through all the classes mentioned in the classes list
    for class_index, class_name in enumerate(CLASSES_LIST):

        # Display the name of the class whose data is being extracted.
        print(f'Extracting Data of Class: {class_name}')

        # Get the list of video files present in the specific class name directory.
        files_list = os.listdir(os.path.join(DATASET_DIR, class_name))

        # Iterate through all the files present in the files list.
        for file_name in files_list:

            # Get the complete video path.
            video_file_path = os.path.join(DATASET_DIR, class_name, file_name)

            # Extract the frames of the video file.
            frames = frames_extraction(video_file_path)

            # Check if the extracted frames are equal to the SEQUENCE_LENGTH specified above.
            # So ignore the vides having frames less than the SEQUENCE_LENGTH.
            if len(frames) == SEQUENCE_LENGTH:

                # Append the data to their repective lists.
                features.append(frames)
                labels.append(class_index)
                video_files_paths.append(video_file_path)

    # Converting the list to numpy arrays
    features = np.asarray(features)
    labels = np.array(labels)

    # Return the frames, class index, and video file path.
    return features, labels, video_files_paths

So, when I tried to create the dataset as below:
   # Create the dataset.
   features, labels, video_files_paths = create_dataset()

I am getting the errow below:
Here it is!
How can I fix this? I think I need to preprocess dataset as batches during training the model. But how can I do that? When I worked on images, I have used keras.utils.image_dataset_from_directory but now should I build my own data loader?

A: You can also do the task without building your custom data loader.
Install necessary dependencies: tensorflow, keras, glob

*

*then install: !pip install keras-video-generators==1.0.11

Here is a full example below:
import tensorflow as tf
import glob
import keras
from keras_video import VideoFrameGenerator
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import TimeDistributed, GRU, Dense, Flatten
from tensorflow.keras.optimizers import  Adam

glob_pattern='/content/HMDB51/{classname}/*.mp4'

classes = [i.split('/')[3] for i in glob.glob('/content/HMDB51/*')]
classes.sort()

SIZE = (128, 128)
CHANNELS = 3
NBFRAME = 20
BS = 5

data_aug = keras.preprocessing.image.ImageDataGenerator(
        dtype = 'float16',
        rescale = 1./255,
        zoom_range = .1,
        horizontal_flip = True,
        rotation_range = 15
    )

train = VideoFrameGenerator(
    classes=classes,
    glob_pattern=glob_pattern,
    nb_frames=NBFRAME,
    split_val=.20,
    shuffle=True,
    batch_size=BS,
    target_shape=SIZE,
    nb_channel=CHANNELS,
    transformation=data_aug,
    use_frame_cache=True)

valid = train.get_validation_generator()

def build_vgg(shape=(128, 128, 3), nbout=51):
    vgg_model = VGG16(include_top=False, input_shape=shape, weights='imagenet')

    for layer in vgg_model.layers:
        layer.trainable = False

    return vgg_model

def action_model(shape=(20, 128, 128, 3), nbout=51):
    convnet = build_vgg(shape[1:])
    model = Sequential()
    model.add(TimeDistributed(convnet, input_shape=shape))
    model.add(Dense(256, activation='relu'))
    model.add(TimeDistributed(Flatten()))
    model.add(GRU(256, dropout=0.20))
    model.add(Dense(128, activation='relu'))
    model.add(Dense(nbout, activation='softmax'))
    model.summary()
    return model

INSHAPE=(NBFRAME,) + SIZE + (CHANNELS,)
model = action_model(INSHAPE, len(classes))
optimizer = Adam(lr=1e-4)
model.compile(
    optimizer=optimizer,
    loss='categorical_crossentropy',
    metrics=['accuracy']
)
EPOCHS=100

history = model.fit_generator(
    train,
    validation_data=valid,
    verbose=1,
    epochs=EPOCHS,
    callbacks=callbacks
)


text:
Q: How i insert intent method to this code for when click button it will show second activity Here is the java activity that provide to add data for record in SQLite. My question is how i insert some code for when clicking button and it will show second activity. i don't know where i should insert. And don't know what the code should be. please help me.
import java.sql.PreparedStatement;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class AddStudent extends Activity {
DatabaseStudent mHelper;
SQLiteDatabase mDb;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add);

    mHelper = new DatabaseStudent(this);
    mDb = mHelper.getWritableDatabase();

    final EditText editName = (EditText)findViewById(R.id.editName);
    final EditText editLastName = (EditText)findViewById(R.id.editLastName);

    ImageView buttonAdd = (ImageView)findViewById(R.id.imageAdd);

    buttonAdd.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            String name = editName.getText().toString();
            String lastname = editLastName.getText().toString();
            String condition = getIntent().getStringExtra("Condition");
            double school = getIntent().getDoubleExtra("Intent", 0);

            //Date&Time
            java.util.Date dt = new java.util.Date();
            java.text.SimpleDateFormat sdf =
                 new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(dt);

            if(name.length() != 0 && lastname.length() != 0
                     ) {//&& school.length() != 0

                Cursor mCursor = mDb.rawQuery("SELECT * FROM "
                        + DatabaseStudent.TABLE_NAME + " WHERE "
                        + DatabaseStudent.COL_NAME + "='" + name + "'"
                        + " AND " + DatabaseStudent.COL_LASTNAME + "='"
                        + lastname + "'" + " AND "
                        + DatabaseStudent.COL_SCHOOL + "='" + school //add COL_SCHOOL = currentTime
                        + "'"+ " AND " + DatabaseStudent.COL_TIME + "='" + currentTime
                        + "'"+ " AND " + DatabaseStudent.COL_CON + "='" + condition
                        + "'", null);

                if(mCursor.getCount() == 0) {
                    mDb.execSQL("INSERT INTO " + DatabaseStudent.TABLE_NAME
                            + " (" + DatabaseStudent.COL_NAME
                            + ", " + DatabaseStudent.COL_LASTNAME
                            + ", " + DatabaseStudent.COL_SCHOOL
                            + ", " + DatabaseStudent.COL_TIME
                            + ", " + DatabaseStudent.COL_CON
                            + ") VALUES ('" + name + "', '" + lastname
                            + "', '" + school + "', '" + currentTime + "', '" + condition + "');");

                    editName.setText("");
                    editLastName.setText("");

                    Toast.makeText(getApplicationContext()
                            , "Already added"
                            , Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext()
                            , "This data is exist"
                            , Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(getApplicationContext()
                        , "Please fill in the blank"
                        , Toast.LENGTH_SHORT).show();
            }
        }
    });

}

public void onStop() {
    super.onStop();
    mHelper.close();
    mDb.close();
}

}

A: You'd want to insert any code you want executed when you hit a button in the onClick method, which you have as seen here:
buttonAdd.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

    // do stuff when buttonAdd is clicked

    }
});

Now you can use intents inside the onClick method to begin a second activity, like so:
buttonAdd.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

        Intent intent = new Intent(current_activity.this, second_activity.class);
        startActivity(intent);
    }
});

You can consult the following for more details: http://developer.android.com/training/basics/firstapp/starting-activity.html


text:
Q: Incorrect integer value: 'caa506cd-a6c6-4907-9a70-81be26324cf3' for column 'notifiable_id' I'm following the notifications tutorial at Laravel docs but I'm getting the error
SQLSTATE[HY000]: General error: 1366 Incorrect integer value:
'caa506cd-a6c6-4907-9a70-81be26324cf3'
for column 'notifiable_id' at row 1

(SQL: insert into `notifications` (
    `id`,
    `type`,
    `data`,
    `read_at`,
    `notifiable_id`,
    `notifiable_type`,
    `updated_at`,
    `created_at`
) values (
    18983710-8eaf-4784-8015-63c078e93866,
    App\Notifications\UserSelectedToInterview,
    {"company_name":"McDonalds","job_title":null},
    ,
    caa506cd-a6c6-4907-9a70-81be26324cf3,
    App\User,
    2018-09-23 16:20:24, 2018-09-23 16:20:24)
)

when I'm calling
// Create the notification for the users
Notification::send(User::whereIn('id', $candidates->pluck('user_id'))
    ->select('id')
    ->get(),

new UserSelectedToInterview($loggedCompany->name, $job->title));

With my notifications migration being:
Schema::create('notifications', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('type');
    $table->morphs('notifiable');
    $table->text('data');
    $table->timestamp('read_at')->nullable();
    $table->timestamps();
});

I'm assuming that $table->morphs('notifiable'); is expecting an int but my User model is using as a primary key a uuid.
At my User model I have that specified with protected $keyType = 'string';
Any idea on where is the problem?

A: updated answer for laravel 6.x
instead of using @charlie's answer you can simply use uuidMorphs
in your notifications_table_migration
Change this:
$table->morphs('notifiable');

To:
$table->uuidMorphs('notifiable');

uuidMorphs function:
/**
     * Add the proper columns for a polymorphic table using UUIDs.
     *
     * @param  string  $name
     * @param  string|null  $indexName
     * @return void
     */
    public function uuidMorphs($name, $indexName = null)
    {
        $this->string("{$name}_type");

        $this->uuid("{$name}_id");

        $this->index(["{$name}_type", "{$name}_id"], $indexName);
    }

Thanks.

A: 2 hours later banging my head against the wall
Basically the problem if anyone is wondering is the morph() method.
The method behind it is:
/**
 * Add the proper columns for a polymorphic table.
 *
 * @param  string  $name
 * @param  string|null  $indexName
 * @return void
 */
public function morphs($name, $indexName = null)
{
    $this->unsignedInteger("{$name}_id");

    $this->string("{$name}_type");

    $this->index(["{$name}_id", "{$name}_type"], $indexName);
}

Instead of using morph() you can add the fields by yourself:
$table->string('notifiable_type');
$table->uuid('notifiable_id');
// Don't forget to add the indexes
$table->index(['notifiable_type', 'notifiable_id']);

Props to this answer How to make laravel Blueprints morphs method to add column after a specified column


text:
Q: Ubuntu 22.04 - how to set lower SSL security level? While using Ubuntu 20.04, the solution for lowering security and allow acces to some outdated servers I used the following solution Ubuntu 20.04 - how to set lower SSL security level?.
Today I upgraded to 22.04, and the solution won't work any more. I tried some other config file tweaks, but with no success. After some reading I guess it has something to do with the latest openssl 3 installed in Ubuntu 22.04.
Is there a way to be able to use legacy methods in openssl 3, as we did in 20.04?

A: It works if you change the security level to 0 instead of 1. In the /etc/ssl/openssl.cnf change SECLEVEL from 2 to 0:
CipherString = DEFAULT@SECLEVEL=0


text:
Q: Android Studio Log Filter AudioManager I never used AudioManager in my code
but This type of Logs are filling my console
How can I stop it ?
2021-09-23 07:03:42.392 5686-6405/com.abhi D/AudioManager: getStreamVolume packageName=com.abhi, index=4, streamType=3
2021-09-23 07:03:42.423 5686-6405/com.abhi D/AudioManager: get_do_mute_music = false
2021-09-23 07:03:42.426 5686-6405/com.abhi D/AudioManager: getStreamVolume packageName=com.abhi, index=4, streamType=3
2021-09-23 07:03:42.465 5686-6405/com.abhi D/AudioManager: get_do_mute_music = false

I tried to add Edit Filter Configuration
for package com.abhi
but no changes

A:
but this message is from my package com.abhi

Regards this, I checked the logcat filter in my Android Studio(AS), seems it's a normal case. See the screenshot.

Obviously, I didn't use any input, OpenGL, or sth. like that, but in the logcat there are many logs related to them. I can understand it because our App runs on the Android system.
To simply fix your problem, I think you need to use another LOG level to filter the log which is only your log. Or config the filter via Edit Filter Configuration
like this:

Again, I still suggest you read the answer link I attached before. Because there are many approaches to filter the log, not only As, but also the command of adb logcat


text:
Q: Realizar duas inserções seguidas e dependentes no MySQL com Node JS Bom Dia Pessoal.
Estou com um problema e preciso da ajuda de vocês.
Meu caso é o seguinte: Possuo uma tabela TAREFA e uma tabela de DIAS_TAREFA que tem uma chave estrangeira para id_tarefa. Portanto, após armazenar os dados de uma tarefa, tendo sucesso, devo inserir os dados na tabela DIAS_TAREFA de acordo com o id gerado anteriormente.
O problema que estou encontrando diz respeito as "threads" que estão rodando pois a função cadastrar da tarefa termina antes do retorno da função diasTarefaController.cadastrar() e com isso o sistema trava.
Estou usando async await mas não está adiantando.
Código da função cadastrar da tarefa
async function cadastrar(req, res){
var {descricao, id_categoria, hora_inicio, hora_fim, data_termino, id_usuario} = req.body.tarefa;

hora_inicio = hora_inicio==""?null:hora_inicio;
hora_fim = hora_fim==""?null:hora_fim;
data_termino = data_termino==""?null:data_termino;

const sql = "INSERT INTO TAREFA (DESCRICAO, ID_CATEGORIA, HORA_INICIO, HORA_FIM, DATA_TERMINO, ID_USUARIO) VALUES ?";

let values = [[descricao, id_categoria, hora_inicio, hora_fim, data_termino, id_usuario]];

conexao.query(sql, [values], async function (error, results, fields){
    if(error){
        return res.json({'erro':'Tarefa nao gravada'});
    }else{
        const retornoDias = await diasTarefaController.cadastrar(req,results.insertId);
        if(retornoDias){
            return res.json({'ok':'Tarefa gravada!'});
        }
    }
}).end;};

Codigo da função diasTarefaController.cadastrar():
async cadastrar(req, id_tarefa){
    const { segunda, terca, quarta, quinta, sexta, sabado, domingo} = req.body.dias;

    const sql = "INSERT INTO DIAS_TAREFA (ID_TAREFA, SEGUNDA, TERCA, QUARTA, QUINTA, SEXTA, SABADO, DOMINGO)  VALUES ?";

    const values = [[
        id_tarefa,
        segunda,
        terca,
        quarta,
        quinta,
        sexta,
        sabado,
        domingo
    ]];

    conexao.query(sql, [values], function(error, result, field){
        if(error){
            return false;
        }else{
            return true;
        }
    });
}


text:
Q: Solving linear programming problem with given information I want to find the optimal solution to a following linear programming problem:
$$8x_1+120x_2+114x_3\to \min$$
$$x_1+7x_2+3x_3\geq 4,$$
$$x_1+5x_2+5x_3\geq 5,$$
$$x_1+3x_2+10x_3\geq 9,$$
$$x_1+2x_2+15x_3\geq11,$$
$$x_1\geq0, \ \ \ x_2\geq 0, \ \ \ x_3\geq0$$
and solution for its dual problem. I already found the dual problem:
$$4y_1+5y_2+9y_3+11y_4\to \max$$
$$y_1+y_2+y_3+y_4\leq 8,$$
$$7y_1+5y_2+3y_3+2y_4\leq 120,$$
$$3y_1+5y_2+10y_3+15y_4\leq 114,$$
$$y_1\geq 0, \ \ \ y_2\geq 0 , \ \ \ y_3\geq 0 , \ \ \ y_4\geq 0.$$
I also know that in the primal problem solution $x^*_1>0, \ x^*_3>0$ for $x^*=(x_1^*,x_2^*,x_3^*)$ and $y_1^*=y_2^*=0$ for $y^*=(y_1^*,y_2^*,y_3^*,y_4^*)$. How should I use that information to find other coordinates in the optimal solution?

A: To use the complementary slackness to solve this LP problem, we first introduce slack variables $x_{s_i}$ and $y_{s_j}$ in each inequality above.
$$8x_1+120x_2+114x_3\to \min$$
\begin{align}
x_1+7x_2+3x_3-x_{s_1} &= 4 \\
x_1+5x_2+5x_3-x_{s_2} &= 5 \\
x_1+3x_2+10x_3-x_{s_3} &= 9 \\
x_1+2x_2+15x_3-x_{s_4} &= 11
\end{align}
$$x_1\geq0, \ \ \ x_2\geq 0, \ \ \ x_3\geq0, \ \ \ x_{s_1}\geq0, \ \ \ x_{s_2}\geq0, \ \ \ x_{s_3}\geq0, \ \ \ x_{s_4}\geq0$$
$$4y_1+5y_2+9y_3+11y_4\to \max$$
\begin{align}
y_1+y_2+y_3+y_4+y_{s_1} &= 8 \\
7y_1+5y_2+3y_3+2y_4+y_{s_2} &= 120 \\
3y_1+5y_2+10y_3+15y_4+y_{s_3} &= 114
\end{align}
$$y_1\geq 0, \ \ \ y_2\geq 0 , \ \ \ y_3\geq 0 , \ \ \ y_4\geq 0, \ \ \ y_{s_1}\geq0, \ \ \ y_{s_2}\geq0, \ \ \ y_{s_3}\geq0$$
By complementary slackness of the optimal solution,
\begin{align}
x^*_iy^*_{s_i} &= 0 \,\forall i \in \{1,2,3\} \\
x^*_{s_j}y^*_j &= 0 \,\forall j \in \{1,2,3,4\}
\end{align}
It's given that $x^*_1>0, \ x^*_3>0$, so $y^*_{s_1}=0, \ y^*_{s_3}=0$.  This means that the first and the third inequalities in the dual problem are in fact equalities.  Substituting $y_1^*=y_2^*=0$ into these equalities, we have
\begin{cases}
y^*_3+y^*_4 &= 8 \\
10y^*_3+15y^*_4 &= 114,
\end{cases}
which gives $y^*_3=\frac65,y^*_4=\frac{34}{5}$.  From this, we further deduce that $x^*_{s_3}=0, \ x^*_{s_4}=0$.  Similar to the dual problem, we have a system of simultaneous linear equations.
\begin{cases}
x^*_1+3x^*_2+10x^*_3 &= 9 \\
x^*_1+2x^*_2+15x^*_3 &= 11
\tag{*}\label{sys}
\end{cases}
This is not enough, so we think about the second inequality in the dual problem.  We aim at proving that it's a strict inequality (i.e. $y^*_{s_2} > 0$), so that we can conclude that $x^*_2 = 0$.
\begin{align}
y^*_{s_2}&=120-3y^*_3-2y^*_4\\
&=120-3\cdot\frac65-2\cdot\frac{34}{5}\\
&=\frac{514}{5}\\
&>0
\end{align}
Thus the system \eqref{sys} can be rewritten as
\begin{cases}
x^*_1+10x^*_3 &= 9 \\
x^*_1+15x^*_3 &= 11,
\tag{#}\label{sys1}
\end{cases}
which gives $x^*_1=5, x^*_3=\frac25$ as the solution.
Hence, we have $x^*=(x_1^*,x_2^*,x_3^*)=(5,0,\frac25)$ and $y^*=(y_1^*,y_2^*,y_3^*,y_4^*)=(0,0,\frac65,\frac{34}{5})$ as an optimal solution.

A: Let $e_1,e_2,e_3,e_4$ be the slack variables of the primal, and $f_1,f_2,f_3$ the slack variables of the dual.
By the complementary slackness conditions:

*

*$x_1^*>0 \quad \Rightarrow \quad f_1=0$

*$x_3^*>0 \quad \Rightarrow \quad f_3=0$

And since $y_1^*=y_2^*=0$, it follows that $y_3^*$ and $y_4^*$ satisfy
\begin{cases}
y_3^*+y_4^*=8 \\
10y_3^*+15y_4^*=114
\end{cases}
Solving for $y_3^*$ and $y_4^*$ yields
\begin{cases}
y_3^*= \frac{6}{5} \\
y_4^*= \frac{34}{5}
\end{cases}
Plugging these values in the second constraint, we get
$$
0+0+3\frac{6}{5}+2\frac{34}{5}+f_2=120\quad \Rightarrow \quad f_2 =\frac{514}{5}
$$
Again, by complementary slackness:

*

*$y_3^*>0 \quad \Rightarrow \quad e_3=0$

*$y_4^*>0 \quad \Rightarrow \quad e_4=0$

*$f_2>0 \quad \Rightarrow \quad x_2^*=0$

Therefore $x_1^*$ and $x_3^*$ satisfy
\begin{cases}
x_1^*+0+10x_3^*=9 \\
x_1^*+0+15x_3^*=11
\end{cases}
which gives us
\begin{cases}
x_1^*= 5 \\
x_3^*= \frac{2}{5}
\end{cases}
Plugging these values in the two first constraints, we get $e_1=\frac{11}{5}$, $e_2=2$ and finally $y_1^*=y_2^*=0$ by complementary slackness again.
In summary:
$$
\boxed{
(x_1^*,x_2^*,x_3^*)=(5,0,\frac{2}{5})\quad \mbox{and}\quad (y_1^*,y_2^*,y_3^*,y_4^*)=(0,0,\frac{6}{5},\frac{34}{5})
}$$


text:
Q: Create JSON using python with sequence key for LLD Zabbix discovery top mem process I try create JSON using python with sequence key for LLD Zabbix discovery top mem process
#!/usr/bin/python

import subprocess
import json

s = subprocess.Popen(["ps axho comm --sort -rss | head -5"], shell=True, stdout=subprocess.PIPE).stdout
service_states = s.read().splitlines()

count = 0
data = {"data":{}}
for i in service_states:
  count += 1
  key = "{#TOPMEMNAME" + str(count) + "}"
  data["data"][key] = i

json_data = json.dumps(data)
print(json_data)

Get JSON not accepted Zabbix (Below code):
{
  "data": {
    "{#TOPMEMNAME2}": "node",
    "{#TOPMEMNAME1}": "mongod",
    "{#TOPMEMNAME4}": "ffmpeg",
    "{#TOPMEMNAME3}": "kubelet",
    "{#TOPMEMNAME5}": "dockerd"
  }
}

Below code where Zabbix accepted JSON.
{
    "data": [{
            "{#TOPMEMNAME1}": "mongod"
        },
        {
            "{#TOPMEMNAME2}": "node"
        },
        {
            "{#TOPMEMNAME3}": "kubelet"
        },
        {
            "{#TOPMEMNAME4}": "ffmpeg"
        },
        {
            "{#TOPMEMNAME5}": "dockerd"
        }
    ]
}

How change python code for get JSON zabbix accepted ?

A: data = {"data":{}}
# should be changed to the line below
data = {"data":[]}

data["data"][key] = i
# should be changed to the line below
data["data"].append({key:i})


text:
Q: Какие аргументы получает шейдер от SpriteRenderer? Доброй ночи! Хочу написать шейдер, который бы брал из текстуры альфа-канал и превращал его в переданный цвет. Шейдер используется внутри материала, который в свою очередь используется внутри компонента SpriteRenderer. Цвет пробую менять через переменную color SpriteRenderer-a:
  private SpriteRenderer spriteRenderer;

  void OnColorChanged (Color color) {
    spriteRenderer.color = color;
  }

Но беда в том, что шейдер не получает цвет из SpriteRenderer-a. И вроде бы создал свойство _Color, а цвет всегда тот, что по-умолчанию или тот, что задан в материале. Подскажите возможные проблемы, пожалуйста.

A: Нашёл. Точнее я нашел не все, но нужный точно! Рассказываю алгоритм действий.
Сперва настраиваем свой Renderer, даём ему материал, который сейчас в разработке. Среди стандартных шейдеров ищем те, которые содержат нужный эффект. Например я искал шейдер, который меняет оттенок текстуры в зависимости от выбранного цвета в SpriteRenderer.
Найдя нужный шейдер кликаем правой кнопкой по нему прямо в материале, выбираем пункт "Edit Shader":

В некоторых случаях сразу откроется код, а в некоторых нужно кликнуть "Compile and show code":

Дальше методом смекалки и научного тыка выбираем нужный property. В моём случае это был _FaceColor, тогда как я долго думал, что должно быть просто _Color.
Конечно хотелось бы как-то сразу узнавать какие свойства задаёт тот или иной Renderer. Но то ли я документацию плохо читал, или ещё что, а найти ответ на свой вопрос не мог. К счастью случайно заметил возможность редачить стандартные шейдеры, что ускорило поиск необходимого в разы.


text:
Q: elasticsearch returns RequestError 400 GET 31searchskurecord/_search
{
    "query": {
        "match_all": {}

    }
    , "sort": [
      {
        "sort_order": {
          "order": "desc"
        }
      }
    ]
}

returns RequestError(400, 'search_phase_execution_exception', 'No mapping found for [sort_order] in order to sort on')

A: This is because you might not be having any field sort_order in your index.
You must be getting this error  -
"root_cause": [
      {
        "type": "query_shard_exception",
        "reason": "No mapping found for [sort_order] in order to sort on",
        "index_uuid": "n0rYitJtQZ2ku3ahDqsohQ",
        "index": "67297292"
      }
    ],

To know more about sort order you can refer to this official documentation
If you want to sort on the basis of a particular field, you need to modify your query as
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "<field-name>": {      // add your field name here
        "order": "desc"
      }
    }
  ]
}


text:
Q: Bus Error when trying to create new object in C++ I'm running into a weird bus error when trying to create an object in C++. This is my gdb backtrace when the program crashes:
#0  0xff146ff4 in _malloc_unlocked () from /usr/lib/libc.so.1
#1  0xff146e40 in malloc () from /usr/lib/libc.so.1
#2  0x24430 in __builtin_new (sz=128) at /usr/local/src/gcc-2.95.1/gcc/cp/new1.cc:84
#3  0x1e71c in FileHeader::Allocate (this=0x3f5d8, freeMap=0x3eea0, fileSize=5719)
    at ../filesys/filehdr.cc:63
#4  0x1f61c in FileSystem::Create (this=0x3d8b8, name=0xffbff8f3 "test", initialSize=5719)
    at ../filesys/filesys.cc:200
#5  0x1ffac in Copy (from=0xffbff8e4 "assignment 2.c", to=0xffbff8f3 "test")
    at ../filesys/fstest.cc:52
#6  0x15150 in main (argc=3, argv=0xffbff768) at ../threads/main.cc:116

The relevant line of code from filehdr.cc is:
IndirectHeader * s;
s = new IndirectHeader;

It crashes on the second line. I thought it might be that I wasn't explicitly using my own constructor, but adding one didn't seem to help. It seems to me like there's some other simple problem i'm not noticing but i haven't been able to find it.. Any advice would be appreciated.

A: What you're seeing in the backtrace is a crash allocating the memory to back your IndirectHeader.  It hasn't even started constructing the object yet because it's still trying to allocate memory for it.  Most likely there is a bug earlier in your program, that has corrupted the heap.


text:
Q: Question about interpretation of importance in contrastive explanation section of the explanation task response I'm wondering how to interpret the "importance" values in the contrastive explanation part when getting an explanation task response. See https://cloud.ibm.com/apidocs/ai-openscale#get-explanation-task > entity > contrastive_explanation > pertinent_positive_features (and also pertinent_negative_features).
Importance seems to be high for some features that are not changed compared to input features, and low for some where the value has changed compared to the input. I'm trying to understand which of all the features returned are key - i first went with those that were changed compared to the input features, but since this does not line up with the importance values I'd like to understand better what this importance stands for?
For example:
"input_features": [
            {
                "feature_type": "categorical",
                "name": "CheckingStatus",
                "value": "less_0"
            },
            ...

and
 "contrastive_explanation": {
            "pertinent_positive_features": [
                ...
                {
                    "feature_value": "no_checking",
                    "importance": "0.0",
                    "feature_name": "CheckingStatus"
                },

The feature was changed and yet its importance for pertinent positive features is 0?

A: The importance of features for pertinent positive is computed as the change needed to get to the Pertinent positive feature value from its median value. E.g., if the feature F1 has value 20 in its pertinent positive and the median value of f1 is 2, then the importance depends on the distance between 20 and 2 (i.e., 18).  We also factor in the standard deviation to normalise the distance across different features. Hence it could happen that a feature whose value has not changed in the PP has high weight (if that value is away from its median). So the weight is a measure of how far the PP feature value is from its median.
Having said that, another way of looking at feature importance is to look at those features which have changed.
Thanks,
Manish


text:
Q: Extract Perfmon data from SQL I typically log all of my perfmon data to a sql database.  Someone in the office requested that I pull out the data and put it back into a perfmon binary file (a .blg file).  Reasons for this is so that it's more portable for others to view without having to add in a datasource to their machine.  I did some searching and haven't found any methods to do this.  Is it possible?

A: It's possible. SQL database could be used as source for relog.exe.
Use following syntax for relog.exe to get data from SQL database:
relog.exe SQL:(your_DSN_name_here)!(your_perfmon_preset_name_here) -b "start_date" -e "end_date" -f bin -o (your_blg_file_name_here)
In my case:
relog.exe SQL:PMDWH!JUMP01_System_Overview -b "02.03.2015 08:00:00AM" -e "02.03.2015 09:00:00AM" -f bin -o C:\Temp\SQLlogfile.blg


text:
Q: Rails action after pressing button I have buy method in my item controller and I tried to print user email who have pressed buy button, but I don't know how to do it. Is there a way to do it without creating Buy model, where I can connect user with my models?
my buy method:
def buy
    item = current_user.items.find(params[:id])
    item.ammount -= 1
    item.save
    flash[:success] = "You bought item"
    redirect_to :back
end

Thanks!

A: Some better code, using decrement!:
def buy
    item = current_user.items.find params[:id]
    item.decrement! :amount
    redirect_to :back, success: "Item purchased"
end

If you want your own user to buy one of their items, you would not need a separate model:
#app/models/user.rb
class User < ActiveRecord::Base
   has_many :items
end

#app/models/item.rb
class Item < ActiveRecord::Base
   #columns id | user_id | amount | purchased | created_at | updated_at
   belongs_to :user
end

This would allow you to do the following:
def buy
   @item = current_user.items.find params[:id]
   @item.decrement! :amount
   @item.increment! :purchased
end

Quite why you'd want to do this, I don't know.

However, if you wanted to make it so that a user can buy another user's items, you'll be able to use a has_many :through model as follows:
#app/models/user.rb
class User < ActiveRecord::Base
   has_many :items
   has_many :purchases
   has_many :purchased_items, through: :purchases, class_name: "Item", foreign_key: :item_id
end

#app/models/purchase.rb
class Purchase < ActiveRecord::Base
   belongs_to :item
   bleongs_to :user

   after_create :decrease

   private

   def decrease
       item.decrement!
   end
end

#app/models/item.rb
class Item < ActiveRecord::Base
   belongs_to :user
   has_many :purchases
   has_many :purchasers, through: :purchases, class_name: "User", foreign_key: :user_id
end

This would allow you to do the following:
#config/routes.rb
resources :items do
   resource :purchase, only: [:create]
end

#app/controllers/purchase_controller.rb
class PurchaseController < ApplicationController
   def new
      @item = Item.find params[:item_id]
      @purchase = current_user.purchases.create @item
   end
end

This will give you the ability to "buy" items from other users


text:
Q: Problems with IndexPath in the tableView reload I am facing such a trouble, let's go:
I have a tableView which has been loaded with a array of arrays, this process have worked perfectly, however, when I update that tableView (reload), even using the same array and the scroll is posicioned in half of list, or in the end, it seems the indexes are loaded wrongly, that is, when a cell is loaded, the information of another cell is loaded. On the other hand, if the scroll is on the top of tableview, that is, in the first cell, even in reload process, this problem does not happen, bellow my code:
Thanks so much!
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {

static NSString *CellIdentifier = @"cell_aux";

clsTableViewCell *cell = (clsTableViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"cell_aux" owner:self options:nil];
    cell = (clsTableViewCell *)[nib objectAtIndex:0];
}

[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

arInfos = [[NSArray alloc] initWithArray:[[arMain objectAtIndex:indexPath.row]                  componentsSeparatedByString:@"|"]];

[arInfosAll addObject:arInfos];

NSURL *imgURL = [NSURL URLWithString:[arInfos objectAtIndex:4]];

UIImage *Noimg=[UIImage imageNamed:@"NoImage.png"];
cell.img.image = Noimg;

cell.lblNome.text = [arInfos objectAtIndex:1];
cell.lblEndereco.text =[arInfos objectAtIndex:2];

NSURLRequest* request = [NSURLRequest requestWithURL:imgURL];
[NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response,
                                               NSData *imgData,
                                               NSError * error)
    {
                               if (!error)
                               {
                                   UIImage *img = [UIImage imageWithData:imgData];
                                   cell.img.image = img;
                               }

                           }];
    }

      return cell;
  }


text:
Q: Regex to extract a part out of a URL and use it as a reference in url rewrite OK, I'm wondering if someone can lend a hand with a regex I'm trying to write.
Basically, what I want to do is use IIS urlrewrite module to do a redirect to a specific URL if the user accesses a URL on another site.  The only catch is I have to also capture a bit of the query string, and move it into the redirect.  I think I actually DO have the regex correct for this, but it's implementing it in my web.config that is causing the problem.
so here is the input, the URL that a user may access would look like:
https://of.example.com/sfsv3.aspx?waform=pro&language=en
I want to match that URL (either http or https, case insensitive), and capture from it also one piece of information, the two letter language code.  then the url i want to forward the user to looks like:
http://example.com/ca/en/ppf
(where en is replaced by whatever i captured above)
So, I'm working with IIS Rewrite module, and I've gotten my input data and regex in, so far the regex pattern I have is this:
https?://of.example.com/sfsv3.aspx\?waform=pro&(language=(..))

so basically i'm matching the whole string, plus a group and a subgroup for language and it's code.  in the IIS test pattern dialog, this is working.
I get the following
{R:1} language=en
{R:2} en
great!  so then my IIS rewrite rule should look like this to redirect the user:
<system.webServer>
    <rewrite>
      <rules>
        <rule name="test" stopProcessing="true" enabled="true">
          <match url="https?://of.example.com/sfsv3.aspx\?waform=pro&(language=(..))" ignoreCase="true" />
          <action type="Redirect" url="http://www.example.com/ca/{R:2}/ppf" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

this all seems right to me.  however, IIS is balking and saying that my web.config is invalid.  specifically, it says "Entity '(' is not defined" and it's pointing to the ( right before language as the problem.  So, I can't build or deploy this application till I fix that.  If i build it without and then just try to drop that into the web.config, i get an error loading the site:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Can someone help me figure out how to put a capture group into a rewrite rule properly?

A: You forgot to code the ampersand.  Should be:
<system.webServer>
<rewrite>
  <rules>
    <rule name="test" stopProcessing="true" enabled="true">
      <match url="https?://of.example.com/sfsv3.aspx\?waform=pro&(language=(..))" ignoreCase="true" />
      <action type="Redirect" url="http://www.example.com/ca/{R:2}/ppf" />
    </rule>
  </rules>
</rewrite>


text:
Q: why are the right answers coming out wrong from random import randint

correct = 0

for i in range(10):
    n1 = randint(1, 10)
    n2 = randint(1, 10)
    prod = n1 * n2

    ans = input("What's %d times %d? " % (n1, n2))
    if ans == prod:
        print ("That's right -- well done.\n")
        correct = correct + 1
    else:
        print ("No, I'm afraid the answer is %d.\n" % prod)

print ("\nI asked you 10 questions.  You got %d of them right." % correct)
print ("Well done!")

What's 1 times 5? 5
No, I'm afraid the answer is 5.
What's 9 times 3? 27
No, I'm afraid the answer is 27.
What's 4 times 1? 4
No, I'm afraid the answer is 4.

A: You have to convert the input string into a number:
for i in range(10):
    n1 = randint(1, 10)
    n2 = randint(1, 10)
    prod = n1 * n2

    ans = int(input("What's %d times %d? " % (n1, n2)))
    if ans == prod:
        print("That's right -- well done.\n")
        correct += 1
    else:
        print("No, I'm afraid the answer is %d.\n" % prod)
print("\nI asked you 10 questions. You got %d of them right." % correct)
print("Well done!")

A: in your case, ans are string. so, you should casting like :
ans = int(input("What's %d times %d? " % (n1, n2)))


text:
Q: How to display the secondary records in the data table child row with respective id? I am using CodeIgniter and data table with child row.
What I am doing is I have a master table with a primary member and a secondary member. Primary member can identify using member_type=1 and secondary member member_type=2. Both members are connected with the relation table. I am able to display the records in the data table with the primary member as well as a secondary member.
Now I am using the data table child row plugin(https://datatables.net/examples/api/row_details.html). I have to display the primary member in the list if the user wants to check the secondary member of the specific primary member then should click on plus sign image and they will get the secondary member list.
So the output will be

Explanation of the code
Now I am calling two model from the Listdetails_ajax(). First for the primary records(getTotalList_of_primary();) and second for the secondary records(getTotalList_of_secondary()). In the first model, I get the primary details with id and that id I am passing to the second model to get the secondary member record related to the id.
Issue is,
1) I am getting the all the records in the data table(I need only primary records)
2) How do I assign the child value in the data table?
Would you help me out with this issue?
Controller
public function Listdetails_ajax(){
   $draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$books = $this->Search_model->getTotalList_of_primary();

$data['draw'] = 1;
$data['recordsTotal'] = count($books);
$data['recordsFiltered'] = count($books);
foreach ($books as $key => $row)
{
    //print_r($row->customer_id);
    $arr_result = array(
                "member_id" => base64_encode($this->encryption->encrypt($row->member_id)),
                "profile_pic" => $row->profile_pic,
                "name" => $row->first_name.' ' .$row->last_name,
                "phone" => $row->phone,
                "chss_no" => $row->chss_no,
                "emp_id" => $row->emp_id,
                "address" => $row->address
                // "member_type" => $row->member_type
    );
     $data['data'][] = $arr_result;
     $books_of_secondary = $this->Search_model->getTotalList_of_secondary($row->customer_id);
     print_r($arr_result);
     foreach ($books_of_secondary as $key => $row)
        {
            //print_r($row->customer_id);
            $arr_result2 = array(
                        "s_member_id" => base64_encode($this->encryption->encrypt($row->member_id)),
                        "s_profile_pic" => $row->profile_pic,
                        "s_name" => $row->first_name.' ' .$row->last_name,
                        "s_phone" => $row->phone,
                        "s_chss_no" => $row->chss_no,
                        "s_emp_id" => $row->emp_id,
                        "s_address" => $row->address
            );

            $data['data'][] = $arr_result2;
              print_r($arr_result2);
        }
  }
echo json_encode($data);
exit;
}

Model
public function getTotalList_of_primary(){
      $this->db->select('*');
      $this->db->from('members');
      $this->db->where('member_type',1);
      $query = $this->db->get();
      $res   = $query->result();
     return $res;
}
public function getTotalList_of_secondary($id){
      $this->db->select('*');
      $this->db->from('members');
      $this->db->join('relation_member', 'relation_member.secondary_member_id = members.member_id');
      $this->db->where('relation_member.primary_customer_id',$id);
      $query = $this->db->get();
      $res   = $query->result();
      return $res;
}

Datatable
function format ( d ) {
    // `d` is the original data object for the row
    return '
'+
        '
'+
            'Full name:	'+
            ''+d.s_name+'	'+
        '
'+
        '
'+
            'Mobile number:	'+
            ''+d.s_phone+'	'+
        '
'+
    '
';
}

$(document).ready(function() {
            var oTable =$('#all_list').DataTable( {
                "processing": true,
                // "serverSide": true,
                "pageLength": 10,
                "ajax": {
                    "url": baseUrl+ "/index.php/Search/Listdetails_ajax",
                    "type": "POST"
                },
                "columns": [
                   {
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
                    },
                { "data": "member_id","className": "display_none"},
                { "data": "profile_pic","className":"img_list_pic",
                "render": function (data, type, full, meta) {
                return '';
                }
                 },
                { "data": "name" },
                { "data": "phone" },
                { "data": "chss_no" },
                { "data": "emp_id" },
                { "data": "address" },
            ],

            } );
            // Add event listener for opening and closing details
    // Add event listener for opening and closing details
     // Add event listener for opening and closing details
    $('#all_list tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = oTable.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');

            $('[data-toggle="tooltip"]', tr.next('tr')).tooltip();
        }
    } );

} );

Json
Array
(
    [member_id] => M2EwYzhmNzBjYTYzMTdiMzFiZDFjNGIwY2Y1NmYwNmQ3ZWY0MGEzNTg5OTY2YjBkNWUwZjc3MWY4NWJiZTdmMGM3Y2Y4YTdhZGI4MTM1MTMyMDVmMDQ1NjRkZTVmMmViZjYzMjcxZGVlODhmNzg1OGMzM2M1ZWI0MjUwYjQ5YzVOUDZSRlZKcFhaNWZ0eTg3NVlBT09HcFhwcW5XSGlIaWpYelJpOTduNzI0PQ==
    [profile_pic] => 5b1b88a7cd85a1528531111090618.png
    [name] => alpha bita
    [mobileno] => 9898981234
    [emp_id] => EMP_2018_03
    [address] => Navi Mumbai
)
Array
(
    [s_member_id] => ZWFlMjQwNGEwMGQ2YWVjMzlkZGRkN2Y1ZTQ1ODQ1NDc0N2M5ZDRiZDY3NDkyZDQ2YjNkN2UxZjI4ZTFhY2Y1Y2U1NWI2N2RlMDEyY2M5NDE3NDc2NWNiZmU4MzFjNWYwYzc2OWQxNjIzZDJiM2QwMzg0ODU2OWNjNDY5OWI4MWM0Yjl0YUgzOUVKaGNka2ZuTEp4Tk1EZitraTEyd2NtLzliNk8wSlpQU0FJPQ==
    [s_profile_pic] =>
    [s_name] => Anil
    [s_phone] => 2121212121
    [s_emp_id] =>
    [s_address] => Navi Mumbai
)
Array
(
    [member_id] => ZDVkYTFiMGM0MGRhNzBjMTg1N2VhMDMyYjU0NDQyMDFlNjMyNDNjNGFhZjg0ODM4YTRhNWJiZjBlODkyZGZkYzk5MGFmN2JjZmFmODM0ZTQ3NzA3NTkwZWFlNGIwYzU2MzBmZGQ0NTZlOTkyMWJiNDc2OTdmN2EyZjJkOGM0NDZDNTlRRVFmK1hoMUNZRlM3R0dFMCtvaGZMclplNWxIYk1DOG0vVklwMjBBPQ==
    [profile_pic] => 5b1b8c15eefe31528531989090618.jpg
    [name] => Ajay Waghmare
    [phone] => 8989855451
    [chss_no] => chss/ajay/2018
    [emp_id] => emp_2018_45
    [address] => Andheri Mumbai
)
Array
(
    [s_member_id] => ZTk1NWYwNWVlMmE3ZTUwMjExMDk3NzlmNTE0YmQ5ZGYzNzkyOTU3M2ZjOGE3YWUyZjg0N2I3ODZhMzhmNWNmNTQ2ZTg1MTM4OGMxNzk4MjFmZWYzMzA3YzViODE5YWNjZmIzNDBlYzJlZTUwYzBhYmRjN2RhZmJmMzk5NjAxOTR1SmJyYngwbE04N0wwTVEyK280V0RhVWlKang4VzBlSExyK0VtQTB4eHlNPQ==
    [s_profile_pic] => 5b1b8fae049341528532910090618.jpg
    [s_name] => Rohit Suman
    [s_phone] => 7885458454
    [s_chss_no] => roh/sum/2018/09
    [s_emp_id] =>
    [s_address] => Andheri Mumbai
)
Array
(
    [s_member_id] => MzVlOGFhM2MwN2RkMzNmYzdiMjhiMzdiNDVhOGMzMTVjZjhlOTFlNzg4ODAxNjFiM2JhZTExZDUxNzg2NDU3MDBmODllZmJlZTcxMThlOWFiODQ4YjAwMThmZGRmNDIxOTU0NWZmYzEwZTg5YzQzOWM3MDBhNGVlM2ZjMDQ5OTFjV3FuZGdsbXJtK3A1YUhFaEI1dTBSWDN5RkhKVVBEbFpJTE95eDdNb3Q0PQ==
    [s_profile_pic] => 5b1b9052d56bd1528533074090618.jpg
    [s_name] => Pankaj
    [s_phone] => 8989989898
    [s_chss_no] => p/2018/09/05
    [s_emp_id] =>
    [s_address] => Andheri Mumbai
)

A: Following the first idea, using a details popup, the controller would look like this:
public function Listdetails_ajax(){
   $draw = intval($this->input->get("draw"));
    $start = intval($this->input->get("start"));
    $length = intval($this->input->get("length"));
    $books = $this->Search_model->getTotalList_of_primary();

    $data['draw'] = 1;
    $data['recordsTotal'] = count($books);
    $data['recordsFiltered'] = count($books);
    foreach ($books as $key => $row)
    {
        //print_r($row->customer_id);
        $arr_result = array(
                    "member_id" => base64_encode($this->encryption->encrypt($row->member_id)),
                    "profile_pic" => $row->profile_pic,
                    "name" => $row->first_name.' ' .$row->last_name,
                    "phone" => $row->phone,
                    "chss_no" => $row->chss_no,
                    "emp_id" => $row->emp_id,
                    "address" => $row->address
                    // "member_type" => $row->member_type
        );

         $array_secondary = array();
         $books_of_secondary = $this->Search_model->getTotalList_of_secondary($row->customer_id);
         foreach ($books_of_secondary as $key => $row)
            {
                //print_r($row->customer_id);
                $arr_result2 = array(
                            "s_member_id" => base64_encode($this->encryption->encrypt($row->member_id)),
                            "s_profile_pic" => $row->profile_pic,
                            "s_name" => $row->first_name.' ' .$row->last_name,
                            "s_phone" => $row->phone,
                            "s_chss_no" => $row->chss_no,
                            "s_emp_id" => $row->emp_id,
                            "s_address" => $row->address
                );

                $array_secondary[] = $arr_result2;
            }
         $arr_result['secondary'] =  $array_secondary;
         $data['data'][] = $arr_result;
      }
    echo json_encode($data);
    exit;
}

And then in the format function you would access the secondary field to get an array of secondaries. Maybe like this:
function format(d) {
    // d is the original data object for the row var val;
    if(d.secondary.length == 0) {
        return "There are no secondary members";
    }

    var display = '
';
    for (val of d.secondary) {
        display += '
' + 'Full name:	' + '' + val.s_name + '	' + '
' + '
' + 'Mobile number:	' + '' + val.s_phone + '	' + '
';
    }
    display += '
';
    return display;
}


text:
Q: Get error SSL operation failed with code 1 when using swiftmailer to send an email in yii2 I'm trying to send a email by using the included mailer in yii2. But getting this error when I submit the email.
stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

I not sure is that the setup issue with my localhost.
Following is my mailer config code set in common/config/main-local.php
 'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp-mail.outlook.com',
        'username' => 'myMail@outlook.com',
        'password' => 'myPassword',
        'port' => '587',
        'encryption' => 'tls',
    ],
]

Following is the code I trying to submit an email
$model = new email;
if($model->load(Yii::$app->request->post(),'email') && $model->validate()){

    if(count($model->htmlBody)>=1){
    Yii::$app->mailer->compose()
         ->setFrom("myPass@outlook.com")
         ->setTo($model->receiver)
         ->setSubject($model->subject)
         ->send();
         Yii::$app->session->setFlash("msg","A mail has been sent");
    }
    else{
          Yii::$app->mailer->compose()
         ->setFrom("imotthegod@outlook.com")
         ->setTo($model->receiver)
         ->setSubject($model->subject)
         ->send();
         Yii::$app->session->setFlash("msg","A mail has been sent");

    }
}
return $this->render("email",['model'=>$model]);

A: Try this config
'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp-mail.outlook.com',
        'username' => 'myMail@outlook.com',
        'password' => 'myPassword',
        'port' => '587',
        'encryption' => 'tls',
        'streamOptions' => [
            'ssl' => [
                'verify_peer' => false,
                'allow_self_signed' => true
            ],
        ],
    ],
]

A: <?php

    require_once 'vendor/autoload.php';

    // Create the Transport
    $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
      ->setUsername('cyr.freaxxx@gmail.com')
      ->setPassword('kwbbmewlbylwnuoh')
    ;

    // Create the Mailer using your created Transport
    $mailer = new Swift_Mailer($transport);

    $emailBody = 'Here is the message itself';

    if (isset($_POST['submit'])) {
        //echo '
'; print_r($_POST); exit;
        $name        =   $_POST['name'];
        $email       =   $_POST['email'];
        $phone       =   $_POST['phone'];
        $message     =   $_POST['message'];

        $emailBody = "New Enquiry !
 Name:  $name
 Email: $email
 Phone: $phone
 Message: $message";
    }

    // Create a message
    $message = (new Swift_Message('New Enquiry'))
      ->setFrom(['cyr.freaxxx@gmail.com' => 'AKP learning'])
      ->setTo(['vaibhavrajput201997@gmail.com'])
      ->setBody($emailBody)
      ;

    // Send the message
    $result = $mailer->send($message);

    if($result){
        echo "Email has been sent successfully!";
    }else{
        echo "Email not sent! please debug";
    }

?>

A: Change your mailer setting as per below code in file common/config/main-local.php
'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    'viewPath' => '@common/mail',
    'useFileTransport' => false,
    'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'smtp.gmail.com',
        'username' => 'your username',
        'password' => 'your password',
        'port' => 587,
        'encryption' => 'tls',
        'streamOptions' => [
            'ssl' => [
                'allow_self_signed' => true,
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        ],
    ],
],

See this array in the above code:
    'streamOptions' => [
        'ssl' => [
            'allow_self_signed' => true,
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ],

verify_peer is used to for the verification of SSL certificate used.
verify_peer_name is used for verification of peer name.
The default values for both of these variables is TRUE which was causing problem with your code.
Read more here.


text:
Q: Varargs in typescript I want to pass arbitrary number of arguments of different types into a function and use these types. It looks like following:
function f<A>(a: A): A;
function f<A, B>(a: A, b: B): A & B;
function f<A, B, C>(a: A, b: B, c: C): A & B & C;
function f<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;

function f(...args: any[]) {
    return Object.assign({}, ...args);
}

var smth = f({ x: 1 }, { y: 2 }, { z: 3 });
var res = smth.x + smth.y + smth.z;

As I want arbitrary number of parameters, I'd like to get rid of these declarations
function f<A>(a: A): A;
function f<A, B>(a: A, b: B): A & B;
function f<A, B, C>(a: A, b: B, c: C): A & B & C;
function f<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;

and use a single declaration like:
function f<...T>(args: [...T]): &<...T>;

but this thing is syntactically wrong.
Is there a way to rewrite it in a correct way?
PS: Same question in Russian.

A: Edit for 3.0
While the original answer is correct, since I first gave it typescript has changed. In typescript 3.0 it is possible to use tuples in rest parameters to capture the type of the arguments in a tuple
type UnionToIntersection<U> =
    (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

function f<A extends any[]>(...args: A): UnionToIntersection<A[number]> { return null! }
var smth = f({ x: 1 }, new A(), new B());  // will have type  A & B & { x: number; }

Original answer
While as others have mentioned Proposal: Variadic Kinds would help with this task, we can find some workarounds for your specific example.
If we write the function signature with a single type argument, we can get a union type of the arguments:
function f<A>(...args: A[]): A {}
var smth = f({ x: 1 }, { y: 2 }, { z: 3 });
typeof smth = {
    x: number;
    y?: undefined;
    z?: undefined;
} | {
    y: number;
    x?: undefined;
    z?: undefined;
} | {
    z: number;
    x?: undefined;
    y?: undefined;
}

The problem with this approach is that if we use a class instead of an object literal the compiler will refuse to infer the union and give us an error instead. If we let the rest parameter go (...) and just use an array the compiler will infer a union of the parameter type:
function f<A>(args: A[]): A { /*…*/}
var smth = f([{ x: 1 }, new A(), new B()]);
typeof smth == A | B | {
    x: number;
}

So now we have a union of types, but you want an intersection. We can convert the union to an intersection using conditional types (see this answer)
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never

function f<A>(args: A[]): UnionToIntersection<A> {
    return Object.assign({}, ...args);
}

class A { z: number }
class B { y: number }

var smth = f([{ x: 1 }, new A(), new B()]); // will have type  A & B & { x: number; }
var res = smth.x + smth.y + smth.z;

Hope this helps, and gives you a usable workaround at least until we get variadic kinds.


text:
Q: How to pass Enum to ParameterGrid? I would like to pass several parameters to a function that should be optimized  via hyperparameters and multiprocessing.
This fails if an Enum  is passed as a parameter. See code below.
How can I pass an Enum in this case?
from sklearn.model_selection import ParameterGrid
from multiprocessing import Pool
from enum import Enum

class MyStrategy(Enum):
    var1 = 1
    var2 = 2

var1 = MyStrategy(1)
var2 = MyStrategy(2)
abc = [1, 2]
xyz = [3, 4]
if True:
    pg = [{'variant': var1,
           'abc': abc,
           'xyz': xyz, },
          {'variant': var2,
           'abc': abc, }]
else:
    pg = [{'variant': '1',
           'abc': abc,
           'xyz': xyz, },
          {'variant': '2',
           'abc': abc, }]
parameterGrid = ParameterGrid(pg)

def myFunc(myParam):
    print(myParam)

pool = Pool(1)
myList = pool.map(myFunc, parameterGrid)

does work if False:
{'abc': 1, 'variant': '1', 'xyz': 3}
{'abc': 1, 'variant': '1', 'xyz': 4}
{'abc': 2, 'variant': '1', 'xyz': 3}
{'abc': 2, 'variant': '1', 'xyz': 4}
{'abc': 1, 'variant': '2'}
{'abc': 2, 'variant': '2'}

and fails with True:
TypeError: object of type 'MyStrategy' has no len()

A: First, you need to change the values in the enum to strings,since that is the same data type you are using for variant key in the False block. Like this
from sklearn.model_selection import ParameterGrid
from multiprocessing import Pool
from enum import Enum

class MyStrategy(Enum):
    var1 = '1'  #<--------Notice the value is string not int
    var2 = '2'

Next, use the values like this:
var1 = MyStrategy.var1.value
var2 = MyStrategy.var2.value

A: In the True example, in the pg list of dictionaries, both of the values of the 'variant' keys are type <enum 'MyStrategy'>. While in the False example are type str.
To replicate the False variant using enumerators, you have to change the following:
class MyStrategy(Enum):
    var1 = '1'
    var2 = '2'

pg = [{'variant': MyStrategy('1').value,  # Or MyStrategy.var1.value
           'abc': abc,
           'xyz': xyz, },
      {'variant': MyStrategy('2').value,  # Or MyStrategy.var2.value
           'abc': abc, }]