text:
Q: Flask-login usermixin class with a MongoDB I am working to try and build a login method for a while now. I am running a Flask app and have it working well. It all runs locally on my machine. Currently, I am using pymongo and MongoClient to make my connection to the DB. This is all working well and I would like to not change this if possible.
I am trying to use Flask-Login to create a users class using usermixin. This is where I have been grossly unsuccessful. I have tried a few different things and my issue is how to I pull the data from my DB. I have done this previously with an SQL DB but for this project I expressly want to use MongoDB. This is the tutorial I was attempting to follow but I am having difficulty understanding everything because it is not explained well what every line is doing.
https://medium.com/@dmitryrastorguev/basic-user-authentication-login-for-flask-using-mongoengine-and-wtforms-922e64ef87fe
This is my connection to my DB:
client = MongoClient('mongodb://localhost:27017')
and this is my current users class that I don't have working and where I need the help.
class User(UserMixin):

  def __init__(self, username, password_hash):
    self.username = username
    self.password_hash = password_hash

  def check_password(self, password):
    return check_password_hash(self.password_hash, password)

  def get_id(self):
    return self.username

@login_manager.user_loader
def load_user(user_id):
    return User.objects(pk=user_id).first()

Then my last part is my login form:
@app.route('/login', methods=["GET" , "POST"])
def login():
  if request.method == "GET":
    return render_template("login.html", error=False)
  if request.method == "POST":
    check_user = request.form["username"]
    if check_user:
      if check_password_hash(check_user['password'], request.form["password"]):
        login_user(check_user)
        return redirect(url_for('index'))

I am aware that this tutorial uses MongoEngine which I am not using, or not yet but some help here either how to get this code above to work or how to adapt it would be great. When I run this code I am not getting any errors it just doens't work. My test is I try to login and then I try to go to the logout page which is loaded with the following code:
@app.route("/logout")
@login_required
def logout():
  logout_user()
  return redirect(url_for('index'))

When I do it doesn't load the page and I get and Unauthorized Page notice. Thus I know that my code is not working. Lastly, I have all of templates in a static file location.
Thanks in advance for the help and please if anything is not clear ask and I will try to add more details. The more specific the better I will be able to help.
UPDATE:
I realized that it is also probably important to describe how my DB is structured to make sure that I am accessing it properly because that is a major point where I am having issues. I have a DB with my collection called Users and it is structured with each document being a different user record, like this:
{
    "_id" : 1,
    "Reset" : false,
    "FirstName" : "John",
    "LastName" : "Doe",
    "Email" : "JohnDoe@gmail.com",
    "Username" : "",
    "admin" : false,
    "Pass" : "[hashed_password]"
}
{
    "_id" : 2,
    "Reset" : true,
    "FirstName" : "Jane",
    "LastName" : "Smith",
    "Email" : "JaneSmith@hotmail.com",
    "Username" : "Jane",
    "admin" : false,
    "Pass" : "[hashed_password]"
}
{
    "_id" : 3,
    "Reset" : true,
    "FirstName" : "Gary",
    "LastName" : "Bettman",
    "Email" : "GBettman@yahoo.com",
    "Username" : "HockeyGuy",
    "admin" : false,
    "Pass" : "[hashed_password]"
}

A: What you need to know about Flask-login: this extension works with the application's user model, and expects certain properties and methods to be implemented in it. (source : https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins).
The four required items are listed below:

*

*is_authenticated: a property that is True if the user has valid credentials or False otherwise.

*is_active: a property that is True if the user's account is active or False otherwise.

*is_anonymous: a property that is False for regular users, and True for a special, anonymous user.

*get_id(): a method that returns a unique identifier for the user as a string
Unfortunately all the examples in the official documentation and on Miguel Grinberg's excellent blog use SQLAlchemy. Good news, it is possible to implement it with Pymongo...
THE SOLUTION

*

*routes.py
from flask import Flask
from flask_pymongo import PyMongo
from flask_login import LoginManager
from flask import render_template, url_for, request, flash
from app.forms import Login
from flask import request
from werkzeug.urls import url_parse
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import current_user, login_user, logout_user, login_required

mongo = PyMongo(app)
login = LoginManager(app)
login.login_view = 'login'

class User:
    def __init__(self, username):
        self.username = username

    @staticmethod
    def is_authenticated():
        return True

    @staticmethod
    def is_active():
        return True

    @staticmethod
    def is_anonymous():
        return False

    def get_id(self):
        return self.username

    @staticmethod
    def check_password(password_hash, password):
        return check_password_hash(password_hash, password)

    @login.user_loader
    def load_user(username):
        u = mongo.db.Users.find_one({"Name": username})
        if not u:
            return None
        return User(username=u['Name'])

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if current_user.is_authenticated:
            return redirect(url_for('index'))
        form = Login()
        if form.validate_on_submit():
            user = mongo.db.Users.find_one({"Name": form.name.data})
            if user and User.check_password(user['Password'], form.password.data):
                user_obj = User(username=user['Name'])
                login_user(user_obj)
                next_page = request.args.get('next')
                if not next_page or url_parse(next_page).netloc != '':
                    next_page = url_for('index')
                return redirect(next_page)
            else:
                flash("Invalid username or password")
        return render_template('login.html', title='Sign In', form=form)

    @app.route('/logout')
    def logout():
        logout_user()
        return redirect(url_for('login'))

*form.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired

class Login(FlaskForm):
    name = StringField('name' validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    login = SubmitField('Login')

Assuming we have, on the side of Mongodb, a collection (Users) that contains some login information. For example:
{
  Name: [username],
  Password: [hashed_password]
}

For further explanation on what each line of code does, I recommend you to consult the following links:

*

*https://boh717.github.io/post/flask-login-and-mongodb/

*https://flask-login.readthedocs.io/en/latest/

A: I found the following works with flask-login, UserMixin, pymongo
Here is User model
import datetime
import uuid
from depo import bcrypt, login_manager
from flask import session, flash
from depo.common.database import Database
from depo.models.blog import Blog
from flask_login import UserMixin

class User(UserMixin):

    def __init__(self, username, email, password, _id=None):

        self.username = username
        self.email = email
        self.password = password
        self._id = uuid.uuid4().hex if _id is None else _id

    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return self._id

    @classmethod
    def get_by_username(cls, username):
        data = Database.find_one("users", {"username": username})
        if data is not None:
            return cls(**data)

    @classmethod
    def get_by_email(cls, email):
        data = Database.find_one("users", {"email": email})
        if data is not None:
            return cls(**data)

    @classmethod
    def get_by_id(cls, _id):
        data = Database.find_one("users", {"_id": _id})
        if data is not None:
            return cls(**data)

    @staticmethod
    def login_valid(email, password):
        verify_user = User.get_by_email(email)
        if verify_user is not None:
            return bcrypt.check_password_hash(verify_user.password, password)
        return False

    @classmethod
    def register(cls, username, email, password):
        user = cls.get_by_email(email)
        if user is None:
            new_user = cls( username, email, password)
            new_user.save_to_mongo()
            session['email'] = email
            return True
        else:
            return False

    def json(self):
        return {
            "username": self.username,
            "email": self.email,
            "_id": self._id,
            "password": self.password
        }

    def save_to_mongo(self):
        Database.insert("users", self.json())

Here is routes
from flask import flash, render_template, request, session, make_response,  redirect, url_for
from depo import app, bcrypt, login_manager
from depo.models.blog import Blog
from depo.models.post import Post
from depo.models.user import User
from depo.common.database import Database
from depo.usercon.forms import RegistrationForm, LoginForm
from flask_login import login_user

@app.before_first_request
def initialize_database():
    Database.initialize()

@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():

        if request.method == 'POST':
            username = request.form["username"]
            email = request.form["email"]
            password = bcrypt.generate_password_hash(request.form["password"])
                       .decode('utf-8')
            find_user =  User.get_by_email(email)
            if find_user is None:
                User.register(username, email, password)
                flash(f'Account created for {form.username.data}!', 'success')
                return redirect(url_for('home'))
            else:
                flash(f'Account already exists for {form.username.data}!', 'success')
    return render_template('register.html', title='Register', form=form)
@app.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        email = request.form["email"]
        password = request.form["password"]
        find_user = Database.find_one("users", {"email": email})
        if User.login_valid(email, password):
            loguser = User(find_user["_id"], find_user["email"], find_user["password"])
            login_user(loguser, remember=form.remember.data)
            flash('You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)

@login_manager.user_loader
def load_user(user_id):
    user =User.get_by_id(user_id)
    if user is not None:
        return User(user["_id"])
    else:
        return None

May be needed some codes for app also if already not initialized
from flask_login import LoginManager
login_manager = LoginManager(app)

A: I ran into the same issue following this, https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins.
I made a few changes to get it running in Mongo, but I did switch to MongoEngine from MongoClient.
__init__.py

from flask import Flask
from config import Config
from flask_mongoengine import MongoEngine, Document
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_object(Config)

login = LoginManager(app)
login.login_view = 'login'

db = MongoEngine(app)

from app import routes
from app.model import user

.
app/model/user.py

from datetime import datetime
from app import db, login
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

@login.user_loader
def load_user(id):
    return User.objects.get(id=id)

class User(UserMixin, db.Document):
    meta = {'collection': 'users'}
    username = db.StringField(default=True)
    email = db.EmailField(unique=True)
    password_hash = db.StringField(default=True)
    active = db.BooleanField(default=True)
    isAdmin = db.BooleanField(default=False)
    timestamp = db.DateTimeField(default=datetime.now())

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

.
app/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.model.user import User

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.objects(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.objects(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.')

.
app/routes.py

from flask import render_template, flash, redirect, request, url_for
from app import app, db
from app.forms import LoginForm, RegistrationForm
from flask_login import current_user, login_user, login_required, logout_user
from app.model.user import User

@app.route('/')
@app.route('/index')
@login_required
def index():
    posts = [
        {
            'author': {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        }
    ]
    return render_template("index.html", title='Home Page', posts=posts)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.objects(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        user.save()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)


text:
Q: at89c51 power supply I am making a project using at89c51. I used my mobile charger (output: 5V, 1A)
 as the power supply. Will my IC get damaged due to the high current?
I asked cause, without loading the program I connected the pin40(Vcc) and pin20(gnd) just to check whether all the port pins except port0 give output 1 or not, which is as I believe by default. And I got haphazard values which changed everytime I turned the supply off and on.
I also couldn't find the supply current range in the datasheet so got more confused.
Please advise.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to define +/- sign in as.difftime in R? I have strings representing time offsets, which have + and - signs, such as:
string1 <- c("+00:30", "-07:00")
How can I convert these to as.difftime format? I know if there were no signs, I could have just written as.difftime(string1, format = "%H:%M") and it will work. However, I do not know how to handle the signs. I want to use the resulted difftime for converting UTC time to LST.
I appreciate your time and help in advance.

A: It is possible to do this using as.difftime and the format = "%z" but there are a couple of issues. First, the colon isn't a valid part of a time zone specifier. Second, the output seems to be relative to your current timezone. Here's a function which gets round those:
tz_to_difftime <- function(x, zero = "+0000") {
  out <- as.difftime(c(zero, gsub("[: ]", "", x)),
                     format = "%z")
  out[1] - out[-1]
}
tz_to_difftime("+05:30")

Note that this will only work for differences of up to 14 hours in current R (less on older versions).
Here's an alternative using strsplit:
tz_to_difftime2 <- function(x) {
  as.difftime(sapply(strsplit(x, ":"),
    function(x) as.numeric(x) %*% c(1, 1/60)),
    units = "hours")
}

And if you like things more pipey (using magtittr)
tz_to_difftime3 <- . %>%
  strsplit(":") %>%
  sapply(
    . %>%
    as.numeric %>%
    multiply_by_matrix(c(1, 1/60))
  ) %>%
  as.difftime(unit = "hours")

These last two have the advantage that they'll take any number of hours.


text:
Q: Can I use wildcard to build paths when getting references of firebase database If I have the following database structure in firebase:
{
    level1 : {
        0: {
            prop1: {},
            prop2: {}
        },
        1: {
            prop1: {},
            prop2: {}
        },
        2: {
            prop1: {},
            prop2: {}
        }
    }
}

If I wanted to catch only the list of prop1 inside level1, could I build a reference path with wildcards like so: level1/*/prop1?
I don't think this is possible, but I am asking just to confirm, since I didn't find mentions to it in the documentation.
The call to the list of prop1, theoretically, would look like this: firebase.database().ref('level1/*/prop1').
Yes, I am trying to avoid to split those props into different nodes and then having to reference one to the other. Lazy programmer here.

A: I moved on to test it. It is not possible to use wildcards when building paths to be used to catch firebase database references. Instead, do fetch just prop1, the database structure has to be modified. The new structure will look like the following:
{
    level1 : {
        prop1level: {
            0: {prop1: {}},
            1: {prop1: {}},
            2: {prop1: {}}
        },
        prop2level: {
            0: {prop2: {}},
            1: {prop2: {}},
            2: {prop2: {}}
        }
    }
}

With this new database structure I am able to set different rules for the different properties.


text:
Q: BadImageFormatException Could not load file or assembly or one of its dependencies. An attempt was made to load a program with an incorrect format I am getting following runtime error, with my console application(VS2012) which refers to "dcasdk.dll".
.Net Framework of the console app is 4.5, platform target is "Any CPU".
Could not load file or assembly 'dcasdk, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I used CorFlags application to check the target platform of the dll. Below are the details..
Version : v4.0.30319
CLR Header : 2.5
PE : PE32
CorFlags : 16
ILONLY : 0
32BIT : 0
Signed : 0

As per the information above, i think the dll is also built using "Any CPU" target. So it should work with the console app having the same target platform. I am not sure why i get this error when i run.
I also tried changing the target platform to x86 which gives the following "FileNotFoundException". I checked for the dll's references in reflector. It only shows System.Xml and System.Data. Which are already added as a reference in the console app.
Could not load file or assembly 'dcasdk.dll' or one of its dependencies. The specified module could not be found.

Any help regarding this will be greatly appreciated.
Thanks in advance.
Below is the Assembly Binding Log from Fusion.. as per the last three lines of error information, this seems to be an issue with assembly platform. But as this is a third party dll, i cannot recompile this to any specific platform. Please share your thoughts on what can be done here..
Please note that i am running this console app on Windows7, 64bit OS.
*** Assembly Binder Log Entry  (4/26/2017 @ 8:31:08 AM) ***

The operation failed.
Bind result: hr = 0x8007000b. An attempt was made to load a program with an incorrect format.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\ConsoleApplication3.vshost.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = dcasdk, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/ConsoleApplication3/ConsoleApplication3/bin/Debug/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = ConsoleApplication3.vshost.exe
Calling assembly : ConsoleApplication3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\ConsoleApplication3.vshost.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/ConsoleApplication3/ConsoleApplication3/bin/Debug/dcasdk.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\dcasdk.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: dcasdk, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null
ERR: Invalid assembly platform or ContentType in file (hr = 0x8007000b).
ERR: Run-from-source setup phase failed with hr = 0x8007000b.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

If i set "Prefer 32-bit" ON, then the error above disappears. However i still get "FileNotFoundException", "Could not load file or assembly 'dcasdk.dll' or one of its dependencies. The specified module could not be found.". But this time no error in Fusion logs!
*** Assembly Binder Log Entry  (4/26/2017 @ 9:57:53 AM) ***

The operation was successful.
Bind result: hr = 0x0. The operation completed successfully.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\ConsoleApplication3.vshost.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = dcasdk, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/ConsoleApplication3/ConsoleApplication3/bin/Debug/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = ConsoleApplication3.vshost.exe
Calling assembly : ConsoleApplication3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\ConsoleApplication3.vshost.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/ConsoleApplication3/ConsoleApplication3/bin/Debug/dcasdk.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\dcasdk.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: dcasdk, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null
LOG: Binding succeeds. Returns assembly from C:\ConsoleApplication3\ConsoleApplication3\bin\Debug\dcasdk.dll.
LOG: Assembly is loaded in default load context.

"FileNotFoundException" stacktrace..
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args)
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state)
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart()

The ISSUE and fix:
It turned out to be an issue of dcasdk dll's dependencies not being found. I did contact the third party provider and they confirmed that the dcasdk dll had dependency with two more dlls(provided by them later) which after adding resolved the issue!
Thanks everyone for helping me understand the issue.

I am getting FileNotFoundException again when i try to deploy this as a windows service in a machine runs on Windows server R2.
I tried compiling with "Prefer 32" On which resulted in the "BadImageFormatException".
If i compile using x86 platform target i am getting FileNotFoundException, though all the dlls required are present in the service folder.
Can someone help me understand whats going wrong with the deployment. It works in the development system as expected with "Any CPU, Prefer 32bit ON".

A: Right click on project settings, then click on build and set the platform target from Any to x64 or x86 , according to your dll settings.
For me, I was trying to load x64 dll with AnyCpu setting. I changed the AnyCpu Setting to x64 and it start working for me.

A: As mentioned already it is due to wrong architecture either
a) Using x64 assembly with Windows x86
b) Using x86 assembly with x64 process or viceversa
For best results, ensure all .NET assemblies are built with "Any CPU", and same .NET profile (ie all using .NET Core, or Client Profile or Full .NET).
...or one dependency not being found at all, Enable Fusion Log to tell where is looking to gather the assemblies:
See How to enable assembly bind failure logging (Fusion) in .NET
and
http://www.hanselman.com/blog/BackToBasicsUsingFusionLogViewerToDebugObscureLoaderErrors.aspx
UPDATE: Given the error code 0x8007000b I am pretty sure is an architecture mismatch:
a) The dll may be Full .NET code, but not compiled with AnyCPU
b) The dll may be native code, and then you need a matching architecture (plus some calling its code using PInvoke)
c) The dll may be C++ CLI (mix of native/.NET code, again with wrong architecture).
d) The dll may be corrupt.
You may need to contact the 3rd party provider for support.
Also, this link mentions it could be a mismatch of .NET version.
Anyway, looks like the problem is narrowed.
Also if the DLL is partly native, it may need the MSVC runtime (as this question's answers mentions, Using 32-bit dll on 64-bit system shows 0x8007000B Error)
In that case the problem would be a dependency of dcasdk not being found.
You can check which Dependency Walker, see http://www.dependencywalker.com/
(it also has a profile mode where you profile an exe, and see the call to open a dll which failed at runtime).

A: In VS, go to tools, then click on options.
Search "iis" in search bar and check this option, and run the project, this is working for me as I was getting error in web project.


text:
Q: Connecting to a Cassandra Database I am new to Cassandra. I am now working on Ubuntu and the latest Cassandra. I am using Java 1.7 on a PC. I created the installation on a PC without any cloud or server network (replication was one). I can use CQL ok but when I am trying in Java the code fails.
Here is the code:
    Cluster cluster;
    Session session;
    cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    session = cluster.connect("casslinks");

    if (!tableExists(linktable, session))
    {
        createCassTable(linktable, session);
    }

    for (String url: urls) {
        insertCassUrl(url, crawledUrl, session, linktable);
    }

Here is the error:
 Exception in thread "main"
 java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.datastax.driver.core.Cluster.<clinit>(Cluster.java:65)
at com.example.GetSoogrData.insertUrls(GetSoogrData.java:596)
at com.example.GetSoogrData.main(GetSoogrData.java:1112)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)

I used the debugger and saw the session line failed. I assume the IP address is wrong. I am unsure how to test for the correct IP address or how to define the session variable to it will correctly connect.
I have been using mongo db and 127.0.0.1 works for that.
Has anyone any ideas?

A: You are probably running your code with missing dependencies.
Datastax java driver requires few addidional jars, SLF4J libraries being one of them for which exception is thrown.
Look here to see what jars you need:
http://www.datastax.com/documentation/developer/java-driver/2.0/java-driver/reference/settingUpJavaProgEnv_r.html
http://www.datastax.com/documentation/developer/java-driver/2.0/common/drivers/introduction/driverDependencies_r.html


text:
Q: 16.04: How to specify a certificate authority with ldapsearch I've been trying to debug LDAP connectivity, so I installed ldapsearch via sudo apt install ldap-utils. Here's the output of the command:
# ldapsearch -x -LLL -H ldaps://myip -d1 -ZZ
ldap_url_parse_ext(ldaps://myip)
ldap_create
ldap_url_parse_ext(ldaps://myip/??base)
ldap_extended_operation_s
ldap_extended_operation
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP myip:636
ldap_new_socket: 4
ldap_prepare_socket: 4
ldap_connect_to_host: Trying myip:636
ldap_pvt_connect: fd: 4 tm: -1 async: 0
attempting to connect:
connect success
TLS: peer cert untrusted or revoked (0x42)
TLS: can't connect: (unknown error code).
ldap_err2string
ldap_start_tls: Can't contact LDAP server (-1)
    additional info: (unknown error code)

Specifically, I'm focusing on this line:
TLS: peer cert untrusted or revoked (0x42)
I did some googling, and found people explaining to set this setting in a file that exists in a directory named /etc/openldap. However, this directory does not exist on the machine--it doesn't seem to have been created during installation of ldap-utils.
I can't figure out if there's a way to either tell ldapsearch to ignore the trust level of the server's cert, or to pass in some sort of CA. What is the appropriate solution here, to continue with connectivity testing?

A: Add the following line to /etc/ldap/ldap.conf:
TLS_REQCERT never
It will prevent ldapsearch from validating the certificate. So not the most secure option.
You can specify a CA certificate with TLS_CACERT /path/to/trusted/ca

A: This is an old question, but it just happened I've found a proper answer: How to install certificates for command line.
Short story:

*

*Copy (link) your private CA certificate to /usr/local/share/ca-certificates/;

*Run update-ca-certificates;

*Verify that /etc/ssl/certs/ca-certificates.crt contains your certificate (See https://serverfault.com/questions/590870/how-to-view-all-ssl-certificates-in-a-bundle);

openssl crl2pkcs7 -nocrl -certfile /etc/ssl/certs/ca-certificates.crt | openssl pkcs7 -print_certs -noout | grep "your CA"

*

*Repeat your ldapsearch, it should succeed now.

Long story:
On Debian/Ubuntu, LDAP tools are built with GnuTLS. GnuTLS does not work with /etc/ssl/certs hash cache. (See note on TLS_CACERTDIR in man ldap.conf.)
c_rehash utility only updates the hash cache, but not /etc/ssl/certs/ca-certificates.crt.
To properly update both hash cache and CA bundle, instead of linking your CA cert into /etc/ssl/certs, place the link into /usr/local/share/ca-certificates/ and run update-ca-certificates.


text:
Q: Como fazer um insert nessa tabela Eu tenho um cadastro de veículos, que tem um combo box com os anos para o usuário escolher, esses anos vem da tabela "ano". Quando eu completo um cadastro de um carro novo, eu tenho que da um insert na tabela "carro", o meu problema esta ai, como vou salvar o ano que o usuário escolheu, se a tabela "carro" não tem esse campo?

A: Acho melhor nao colocar ano dentro de tabelas deixe apenas direto na combobox
o ano-fabricacao/modelo você coloca na tabela veiculo.
tenta fazer assim:  http://www.luis.blog.br/userfiles/image/exemplo_SQL_2.jpg


text:
Q: how to add the input values in an array i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:

http://jsfiddle.net/yajeig/4Nr9m/69/

I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data  = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]

and if i would add another data again, it will add in that variable and it be something like this:
my_data  = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
     {plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]

the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1

A: You should be able to iterate over all of the textboxes using the following:
function add(e) {
    var obj = {};

    $('#addItem input[type="text"]')
        .each(function(){obj[this.name] = this.value;});
    myItems.push(obj);
}

Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.

A: Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">

Plank number

<input type="text" name="plank_number" id="plank_number"/>

Width

<input type="text" name="plank_width" id="plank_width"/>

Length

<input type="text" name="plank_length" id="plank_length"/>

Thickness

<input type="text" name="plank_thickness" id="plank_thickness"/>

Quantity

<input type="text" name="plank_quantity" id="plank_quantity"/>

<input type="submit" value="Add"/>
</form>

Javascript:
$(document).ready(function() {

    var plank_data = Array();

    $('#add_plank_form').submit(function() {

        // Checking data
        $('#add_plank_form input[type="text"]').each(function() {
            if(isNaN(parseInt($(this).val()))) {
                return false;
            }
        });

        var added_data = Array();
        added_data.push(parseInt($('#plank_number').val()));
        added_data.push(parseInt($('#plank_width').val()));
        added_data.push(parseInt($('#plank_length').val()));
        added_data.push(parseInt($('#plank_thickness').val()));
        added_data.push(parseInt($('#plank_quantity').val()));

        $('#add_plank_form input[type="text"]').val('');

        plank_data.push(added_data);

        // alert(JSON.stringify(plank_data));

        // compute L x W x F for each plank data
        var computed_values = Array();
        $('#add_plank_result').html('');
        for(var i=0; i<plank_data.length; i++) {
            computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
            $('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
        }

        return false;
    });
});

A: Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
  var json = my_data[i];
  for (var key in json) {
    if (json.hasOwnProperty(key)) {
      if (key in added) {
        added[key] += json[key];
      } else {
        added[key] = json[key];
      }
    }
  }
}

A: You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];

var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];

data = data.concat(to_add);

A: Sorry I only glanced at the other solutions.
$(document).ready(function() {
 var myData=[];
    var myObject = {}
        $("input").each(function() {
            myObject[this.id]=this.value
        });
     alert(myObject["plank"])
   myData.push(myObject)
});


text:
Q: Translation from Python to CIL(C Intermediate Language) I have worked on the static analysis on Python source code recently.
There is already a static analyzer written in Ocaml for CIL(C Intermediate Language) in our group. We want to reuse this analyzer, so our ideal approach is to translate Python to CIL.
Currently, I use Python built-in ast module to parse Python to Python AST. And then I translate the Python AST that ast.dump printed to C AST. In consider of C AST to CIL API and the static analyzer all written in Ocaml. I choose Ocamllex&Ocamlyacc to parse Python AST to C AST. However, there are some big problems.
The AST representation which ast.dump printed is hard to identify. That make my parser not easy to implement. On the other hand, I can't use Ocaml to acess the Python ast internal structure. Even I could, the data structure is different from Ocaml.
I wonder whether I choose a wrong approach on the translation from Python code to C AST at first?
Is there any other existing tools or approaches that may meet my requirements?
If there is anything I miss, please just point out that will be a lot of help for me.
Thanks.

A: I don't think this is going to work very well. CIL is essentially just the C langauge.  For your trick to work, you have translate Python completely to C... but the langauges have very dissimilar concepts.  How will you model Python objects?  Continuations? Dynamic load? Runtime typing? Infinite precision arithmetic? I think your problems are not the AST; rather they are conceptual.
If you could translate to CIL, you'd now have a new problem.  Analyzers are easier to build when the constructs they need to find are easily detected.  Once you translate you continuation to C, reasoning about interactions with continuations will be hard, because they won't be easy to recognize.
I think I'd spend my energy trying to build a Python static analyzer where the Python concepts were easy to detect.


text:
Q: update-manager crashes on Ubuntu Mate 16.04 I noticed that my computer doesn't automatically get updated, also that whenever the software updater prompts me for new updates, it disappears when I click on it.
Running
sudo apt-get upgrade

works and updates correctly but when I run
update-manager

It crashes with the following error:
/usr/bin/update-manager:28: PyGIWarning: Gtk was imported without specifying a version first. Use gi.require_version('Gtk', '3.0') before import to ensure that the right version gets loaded.
  from gi.repository import Gtk
/usr/lib/python3/dist-packages/UpdateManager/UnitySupport.py:29: PyGIWarning: Dbusmenu was imported without specifying a version first. Use gi.require_version('Dbusmenu', '0.4') before import to ensure that the right version gets loaded.
  from gi.repository import Dbusmenu, Unity
/usr/lib/python3/dist-packages/UpdateManager/UnitySupport.py:29: PyGIWarning: Unity was imported without specifying a version first. Use gi.require_version('Unity', '7.0') before import to ensure that the right version gets loaded.
  from gi.repository import Dbusmenu, Unity

(update-manager:4386): GLib-CRITICAL **: g_hash_table_destroy: assertion 'hash_table != NULL' failed

(update-manager:4386): GLib-CRITICAL **: g_hash_table_destroy: assertion 'hash_table != NULL' failed
Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/gi/overrides/GLib.py", line 253, in __del__
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 954, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 887, in _find_spec
TypeError: 'NoneType' object is not iterable

I have this problem on two different laptops.
How can I fixt it?


text:
Q: Cobertura check fails when maven run with Cobertura report and install goals I have Cobertura setup as following in my pom:
...
<build>
...
<plugins>
...
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>cobertura-maven-plugin</artifactId>
    <version>${cobertura-maven-plugin.version}</version>
    <configuration>
        <formats>
            <format>html</format>
        </formats>
        <outputDirectory>${project.build.directory}</outputDirectory>
        <check>
            <haltOnFailure>${testsAreRun}</haltOnFailure>
            <totalBranchRate>27</totalBranchRate>
            <totalLineRate>88</totalLineRate>
        </check>
        <instrumentation>
            <ignoreTrivial>true</ignoreTrivial>
            <excludes>
                <exclude>something/app/**/*.class</exclude>
                <exclude>something/config/**/*.class</exclude>
            </excludes>
        </instrumentation>
    </configuration>
    <executions>
        <execution>
            <phase>verify</phase>
            <goals>
                <goal>clean</goal>
                <!--<goal>cobertura</goal>-->
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>
...
<plugins>
...
<build>
...

If I run:
mvn clean cobertura:cobertura

Everything passes fine. If I run:
mvn clean install

Everything passes fine. However, if I run:
mvn clean cobertura:cobertura install

The build fails during the install saying that my code coverage is 0% i.e:
[ERROR] Oct 22, 2014 3:03:59 PM net.sourceforge.cobertura.coveragedata.CoverageDataFileHandler loadCoverageData
INFO: Cobertura: Loaded information on 8 classes.
Project failed check. Total branch coverage rate of 0.0% is below 27.0%
Project failed check. Total line coverage rate of 0.0% is below 88.0%

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 15.839 s
[INFO] Finished at: 2014-10-22T15:03:59+01:00
[INFO] Final Memory: 38M/469M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:cobertura-maven-plugin:2.6:check (default) on project something: Coverage check failed. See messages above. -> [Help 1]

Any ideas why?

A: When you run:

mvn cobertura:cobertura

It just generated the reports.
when you run

mvn install

It runs all the plugins you have set up there, including configurations you have set up which have the line and branch checks


text:
Q: UpdateMany operation specifying filter as _id in I have a series of ObjectIds and I want to update a property in all documents where there's a match with the ObjectIds. So basically the SQL equivalent of:
update collection set prop = false where id in (1,2,3)
The Query I have built for Mongo is:
List<BsonValue> output = GetValues();

var builder = Builders<MyCollection>.Filter;
var filter = builder.In("_id", output);
var update = Builders<MyCollection>.Update.Set("Prop", false);
var result = myCollection.UpdateMany(filter, update);

However, I get the following exception when I run:

Specified cast is not valid.

Any idea what I'm doing wrong? Thanks in advance!
UPDATE
So this query was fine... looks like the problem was with my class.
My class was:
public class MyCollection
{
    [BsonId]
    public ObjectId _id { get; set; }
    //Other properties
}

Apparently the ObjectId was not being mapped correctly. I didn't have an explicit need for it so I removed it and it started working thereafter.
Hope this helps someone else.

A: Answering my own question so that it may help someone else in the future.
My class was:
public class MyCollection
{
    [BsonId]
    public ObjectId _id { get; set; }
    //Other properties
}

The ObjectId property was not being mapped correctly. In my case, I didn't have need for it so I removed it and it started working thereafter.


text:
Q: Constructor with parameter in Controller - MVC I have read few articles on IOC and Unity and got my self confused :(
So going back to basics can some one tel me what the below code does?
private IStudent _student;
public HomeController(IStudent student)
{
     _student= student;
}

public interface IStudent
{
     // Some method
}

Itz Basic but am trying to understand from a layman view. What exactly the above code does?

A: HomeController has a dependency on Student because it delegates some responsibility to Student class.
One way to implement is:
public HomeController()
{
    private Student _student;
    public HomeController()
    {
        _student = new Student();
    }
}
public class Student
{
    // Some method
}

but then HomeController has a hard dependency on Student class. What if you wanted to use some other implementation of Student (e.g. wanted to mock Student while unit testing your HomeController). You will have to modify the Student class or HomeController class (or use some other not-so-good option). This means your HomeController is tightly-coupled to Student class.
The other way is the code you have posted:
public class HomeController
{
    private IStudent _student;
    public HomeController(IStudent student)
    {
        _student = student;
    }
}
public interface IStudent
{
    // Some method
}
public class Student : IStudent
{
    // Implementation of some method
}

Here, you can pass on any implementation of IStudent i.e. in your unit tests you can pass the mock object of IStudent, in your actual code you will pass object of Student class. So you HomeController is now dependent on the IStudent interface (abstraction) rather than on the Student class (an implementation).
This is inline with the OOP principles:

Program to interfaces, not implementations.
Depend on abstractions. Do not depend on concrete classes.

Also, it now has a soft dependency. It's no longer tightly-coupled to the Student class. It's loosely-coupled.
Now, generally you don't need to worry about which implementation of IStudent you should pass while instantiating your HomeController. That's something the Depedency Injection Container (Unity in your case) will take care of, as long as you register correct interface and classes with it.
_container.Register<IStudent, Student>();

So when a new instance of HomeController is required, the container will identify that an instance of IStudent is required. So it will instantiate the registered instance of IStudent and pass it as paramter while instantiating HomeController class.
Also, note that what you are referring to is 'Dependency Injection' (which is one specific form of IoC). There are other forms of IoC (e.g. callbacks, Observer pattern, etc.).
EDIT:
Don't forget to read the popular article on DI.

A: In IoC you need to register the interface and a class which is implementing the interface.
So once you register then whenever you have signature like above IoC will automatically create an instance of IStudent implemented class and inject it to the object while initializing the controller.
It saves the time and efforts to declare the members. In above case you just have one to declare, but it could be more in numbers and those all could need few more instances to pass to the controller.
Once we register those all correctly IoC do its work thereafter. Infact we can decide the Scope/Lifetime of the injected members. It can be PerInstance/Per Request/ Or Singleton.
There are saveral IoC frameworks available its up to you which one you want to go with.

A: In general it is called injecting the dependencies of a class , think about a class or to be precise a GOD class which handles all the stuff like ( Validating user input , coordinating with Database , generating HTML output etc) so you keep all your code in single place or you can say you develop all of your software using single class , isn't that good?
Answer depends upon the way you organize the things , do you think , organizing things where it belongs is beneficial than you will see the problem in the above GOD class.
So in terms of OOPS , A single class shd have a single reason to be changed but it is required  to get the work done than it shd take help from the services.
And your HomeController is doing the same thing since it does not want to be overworked , it has asked Student object to handle student.

A: When a new HomeController object is constructed by IOC resolver, it will take an object that implements IStudent interface provided by the IOC container(the one you registered) via its constructor.
You can read more about Constructor Injection here.


text:
Q: Disabled editmaskcontrol (powerbuilder) I am new in the world of powerbuilder
I wonder how to disabled editmask control based on the value/data inputted on the previous row?
long ll_row
long ll_rowback
long ll_rownext
string ls_display_name
ll_row = currentrow
 ll_rowback = ll_row - 1
 ll_rownext = ll_row + 1
 if ll_row = 0 then
ll_row = 1
end if

//uf_log( gs_log, ls_name + ' ll_row='+string(ll_row))

 if ll_row > rowcount() then
ll_row = 1
end if
datawindow ldw
ldw = this

if getitemstring( ll_row, 'param_type_param_type_flag' ) = 'N' then
//min and max value
dec ldc_min, ldc_max
ldc_min = getitemnumber( ll_row, 'param_value_param_value_min')
ldc_max = getitemnumber( ll_row, 'param_value_param_value_max')
 ls_display_name = describe( "evaluate('lookupdisplay    (element_attribute_param_value_key)', "+string(ll_rowback)+")" )

//jonel
if ls_display_name = 'No' or ls_display_name ='Not Known then
>>>what will be the systax here.

else
    uf_modify( ldw, "element_attribute_attrib_num_value.EditMask.SpinRange='" + string   (ldc_min) + "~~~~" + string(ldc_min) + "'")
end if
I try to have coded on the protect expression but nothing happen..
any idea would be appreciated.. Thanks

A: You were on the right track with coding an expression. I don't have my help/reference handy but setting "protect" or "taborder=0" or whichever attribute is applicable for disabling the editmask. I am assuming you mean an "editmask" edit style in a datawindow and not a separate control outside of the datawindow.
The trick is, that in your expression refer to the prior row using [-1] to refer to the next row you can use something like [+1]. Some people use this for highlighting duplicate value/rows, etc..  here is some code for hint...
element_attrib_num_value.protect=(if(getrow() <=1, 0, columnname_in_prior_row[-1]))
or
element_attrib_num_value.taborder=(if(getrow() <=1, 10, columnname_to_refer_to[-1]))

Don't quote my exact syntax. This method of referring to rows is only usable in expressions as far as I know, also you need to make sure to check that you aren't on the first (or none) row so the expression doesn't break. :)


text:
Q: AngularJS: How can I create a custom filter that can convert the numbers of a string to h:m format? I am loading a JSON list of movies into the scope and each movie has a duration. JSON snippet:
"duration": "PT157M"

This duration is displayed as a string where the number is the duration in min. How can I convert the number into the format "h:m". ex: 150 = "2:30" so that this is in the View?
I tried using javascript with dummy data (to see if it works), but I assume a custom filter is smarter?
.controller('MovieController', ['$scope', 'MovieFactory',
   function($scope, MovieFactory) {

MovieFactory.get().then(function(response) {

  $scope.movies = response.data;

  // extract numbers from string
  $scope.duration = 'PT150M';
  $scope.regex = /\d+/g;
  $scope.found = $scope.duration.match($scope.regex);
  console.log($scope.found);

  // convert number to hours:min
  function timeConvert(n) {
    $scope.num = n;
    $scope.hours = ($scope.num / 60);
    $scope.rhours = Math.floor($scope.hours);
    $scope.minutes = ($scope.hours - $scope.rhours) * 60;
    $scope.rminutes = Math.round($scope.minutes);
    return $scope.finalResult = $scope.num + " min = " + $scope.rhours + " hour(s) and " + $scope.rminutes + " minute(s).";
  }
  console.log(timeConvert($scope.found));

});

}]);

View:

Duration must be here: {{movie.duration}}

I've read a lot of documentation, sadly without any luck.

A: $scope.duration.match($scope.regex); returns the matched numbers as an array with one element (a string of "150" in this case).
You want something like this instead: parseInt($scope.duration.match($scope.regex)[0]);


text:
Q: Can't use the bot when 2 or more people are using the bot The bot is working well when 1 person is using the bot. If, someone starts to use the bot, the dPoints Integer starts to mess up. This is a test, that helps people the get their depression level.
I have an idea. Maybe I can maybe different dPoints.py file for each person that starts to use the bot.
e.g. user1_dPoints, user2_dPoints, etc..
If you want to test my bot out, to see what is the problem - here is my telegram: @kmuradoff
Bot made using TeleBot
# imports
import sys
import time
import os
import config
import telebot
from telebot import types

# vars
dPoints = 0

bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(commands = ['points'])
def showPoints(message):

    bot.send_message(message.chat.id, str(dPoints).format(
    message.from_user, bot.get_me()))

@bot.message_handler(commands=['start', 'help'])
def welcome(message):
    global dPoints
    dPoints = 0
    welcomeMarkup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    doTheTest = types.KeyboardButton("Начать тест")
    welcomeMarkup.add(doTheTest)
    bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!".format(
    message.from_user, bot.get_me()), reply_markup=welcomeMarkup)

@bot.message_handler(content_types=['text'])
def startingTest(message):

    UserName = message.from_user.first_name

    question0Heading = "----------- " + UserName + " -----------"

    question1Answer = "N/A"
    question2Answer = "N/A"
    question3Answer = "N/A"
    question4Answer = "N/A"
    question5Answer = "N/A"
    question6Answer = "N/A"
    question7Answer = "N/A"
    question8Answer = "N/A"
    question9Answer = "N/A"
    question10Answer = "N/A"
    question11Answer = "N/A"
    question12Answer = "N/A"
    question13Answer = "N/A"
    question14Answer = "N/A"
    question15Answer = "N/A"
    question16Answer = "N/A"
    question17Answer = "N/A"
    question18Answer = "N/A"
    question19Answer = "N/A"
    question20Answer = "N/A"

    q1 = types.ReplyKeyboardMarkup(row_width=1)
    q1s1 = types.KeyboardButton("Я не чувствую себя расстроенным, печальным.")
    q1s2 = types.KeyboardButton("Я расстроен")
    q1s3 = types.KeyboardButton("Я все время расстроен и не могу от этого отключиться.")
    q1s4 = types.KeyboardButton("Я настолько расстроен и несчастлив, что не могу это выдержать.")
    q1.add(q1s1, q1s2, q1s3, q1s4)

    q2 = types.ReplyKeyboardMarkup(row_width=1)
    q2s1 = types.KeyboardButton("Я не тревожусь о своем будущем.")
    q2s2 = types.KeyboardButton("Я чувствую, что озадачен будущим.")
    q2s3 = types.KeyboardButton("Я чувствую, что меня ничего не ждет в будущем.")
    q2s4 = types.KeyboardButton("Мое будущее безнадежно, и ничто не может измениться к лучшему.")
    q2.add(q2s1, q2s2, q2s3, q2s4)

    q3 = types.ReplyKeyboardMarkup(row_width=1)
    q3s1 = types.KeyboardButton("Я не чувствую себя неудачником.")
    q3s2 = types.KeyboardButton("Я чувствую, что терпел больше неудач, чем другие люди.")
    q3s3 = types.KeyboardButton("Когда я оглядываюсь на свою жизнь, я вижу в ней много неудач.")
    q3s4 = types.KeyboardButton("Я чувствую, что как личность я - полный неудачник.")
    q3.add(q3s1, q3s2, q3s3, q3s4)

    while message.text == str(q21s1.text) or str(q21s2.text) or str(q21s3.text) or str(q21s4.text):
        if message.chat.type == "private":
            global dPoints
            if message.text == "Начать тест":
                markup = telebot.types.ReplyKeyboardRemove()
                bot.send_message(message.chat.id, "ИНСТРУКЦИЯ".format(
                message.from_user, bot.get_me()), reply_markup=markup)
                time.sleep(1.5)
                bot.send_message(message.chat.id, "Группа #1".format(
                message.from_user, bot.get_me()), reply_markup=q1)
                break
            elif message.text == str(q1s1.text) or message.text == str(q1s2.text) or message.text == str(q1s3.text) or message.text == str(q1s4.text):
                if message.text == str(q1s1.text):
                    dPoints = dPoints + 0
                elif message.text == str(q1s2.text):
                    dPoints = dPoints + 1
                elif message.text == str(q1s3.text):
                    dPoints = dPoints + 2
                elif message.text == str(q1s4.text):
                    dPoints = dPoints + 3
                markup = telebot.types.ReplyKeyboardRemove()
                time.sleep(1)
                bot.send_message(message.chat.id, "Вы ответили на 1 из 21 вопросов".format(
                message.from_user, bot.get_me()), reply_markup=markup)
                time.sleep(2)
                bot.send_message(message.chat.id, "Группа #2".format(
                message.from_user, bot.get_me()), reply_markup=q2)
                break

            elif message.text == str(q2s1.text) or message.text == str(q2s2.text) or message.text == str(q2s3.text) or message.text == str(q2s4.text):
                if message.text == str(q2s1.text):
                    dPoints = dPoints + 0
                elif message.text == str(q2s2.text):
                    dPoints = dPoints + 1
                elif message.text == str(q2s3.text):
                    dPoints = dPoints + 2
                elif message.text == str(q2s4.text):
                    dPoints = dPoints + 3
                markup = telebot.types.ReplyKeyboardRemove()
                time.sleep(1)
                bot.send_message(message.chat.id, "Вы ответили на 2 из 21 вопросов".format(
                message.from_user, bot.get_me()), reply_markup=markup)
                time.sleep(2)
                bot.send_message(message.chat.id, "Группа #3".format(
                message.from_user, bot.get_me()), reply_markup=q3)
                break

print("Bot Started Successfully")

bot.polling(none_stop=True)

A: As you can see from example in GitHub repository of TeleBot library, they propose to use user_dict with values per chat_id. You can do the same.
What else I'd suggest, to use default_dict.

# YOUR IMPORTS HERE
from collections import defaultdict

import config
import telebot
from telebot import types

bot = telebot.TeleBot(config.TOKEN)

# dict that will store all information per chat
user_info = defaultdict(dict)

# Show current amount of points to user
@bot.message_handler(commands = ['points'])
def show_points(message):
    d_points = user_info[message.chat.id].get('d_points', 0)

    bot.send_message(message.chat.id, 'You have {} d_points'.format(d_points).format(message.from_user, bot.get_me()))

# You method where value should be changed
@bot.message_handler(content_types=['text'])
def message_method(message):
    points = 3
    d_points = user_info[message.chat.id].get('d_points', 0)
    user_info[message.chat.id] = d_points + points

    bot.send_message(message.chat.id, 'Now you have: {} d_points'.format(d_points).format(message.from_user, bot.get_me()))


text:
Q: Два блока рядом CSS Мне нужно расположить справа такой же блок. Пытался через float: left, но тогда основной блок уходит в упор влево.
Подскажите, как мне лучше сделать правильное расположение, чтобы основной блок остался по центру без изменений?

A:

.wrap{
  border: 1px solid #000;
  display: inline-block;
  padding: 10px;
}

h1,h2{
  margin: 0;
}

.men{
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: -o-flex;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.men_left img, .men_right img{
  width: 40px;
  height: 40px;
  margin-right: 5px;
}
.men_left{
 margin-right: 10px;
 border: 1px solid #000;
 padding: 10px;
 display: -webkit-flex;
 display: -moz-flex;
 display: -ms-flex;
 display: -o-flex;
 display: flex;
 -ms-align-items: center;
 align-items: center;
}

.men_right{
  border: 1px solid #000;
  padding: 10px;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: -o-flex;
  display: flex;
  -ms-align-items: center;
  align-items: center;
}

.token{
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
  padding: 10px;
  margin-top: 10px;
}

.sgen{
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: -o-flex;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  -ms-align-items: center;
  align-items: center;
}

.link > a{
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
  text-decoration: none;
  color: #000;
  padding: 8px;

}

.link_button > button{
  background-color: #3AAAF5;
  border: none;
  padding: 10px;
  color: #fff;
}

Панель управления

Личная информация

        MaYoR:D

        76561198967718926

        Настройка токенна

          тут ссылка123131312313

          <button href="#">Сгенерировать токен</button>


text:
Q: SQL - get rows where max price is 50% greater than min price I need to get the rows where the maximum price of a product in 2014 is at least 50% greater than the minimum price of that product.
I have a table Price History with 4 columns: shop ID, Product ID, date and price. Shops sell the same products at different prices. I don't know which query to use. Any help would be greatly appreciated!

A: Just take it step by step.
First get the max and min price by product
 SELECT shopID, productID, MAX(price) as maxPrice, MIN(price) as minPrice
 FROM pricehistory
 WHERE year(date) = 2014
 GROUP BY shopID, productID

I suggest you run just this and understand it.
Then select the ones you want from this query
SELECT *
FROM (
  SELECT shopID, productID, MAX(price) as maxPrice, MIN(price) as minPrice
  FROM pricehistory
  WHERE year(date) = 2014
  GROUP BY shopID, productID
) sub
WHERE minPrice * 1.5 < maxPrice


text: Q: JOGL OpenGL GLCanvas set to a fixed resolution I am using JOGL with a GLCanvas in a java app which is displayed fullscreen 1920x1080, is it possible to set the resolution of the GLCanvas or GL to say half this 960x540 and have the canvas/gl upscale it?


text:
Q: Save Bokeh Surface3d plot to png creates empty image I'm making a 3d surface plot using the code from http://docs.bokeh.org/en/latest/docs/user_guide/extensions_gallery/wrapping.html#userguide-extensions-examples-wrapping but when I try to save it using export_png, I get an empty image.
I see the plot when I use show rather than trying to save, so I know it makes the plot fine.
I can save a 2D version of the image without a problem, so I know it's not something inherent in the usage of export_png.
My code is
from pathlib import Path

import numpy as np

from bokeh.core.properties import Instance, String
from bokeh.io import show, export_png
from bokeh.models import ColumnDataSource, LayoutDOM
from bokeh.plotting import figure
from bokeh.util.compiler import TypeScript
from selenium import webdriver

TS_CODE = """
// This custom model wraps one part of the third-party vis.js library:
//
//     http://visjs.org/index.html
//
// Making it easy to hook up python data analytics tools (NumPy, SciPy,
// Pandas, etc.) to web presentations using the Bokeh server.

import {LayoutDOM, LayoutDOMView} from "models/layouts/layout_dom"
import {ColumnDataSource} from "models/sources/column_data_source"
import {LayoutItem} from "core/layout"
import * as p from "core/properties"

declare namespace vis {
  class Graph3d {
    constructor(el: HTMLElement, data: object, OPTIONS: object)
    setData(data: vis.DataSet): void
  }

  class DataSet {
    add(data: unknown): void
  }
}

// This defines some default options for the Graph3d feature of vis.js
// See: http://visjs.org/graph3d_examples.html for more details.
const OPTIONS = {
  width: '600px',
  height: '600px',
  style: 'surface',
  showPerspective: true,
  showGrid: true,
  keepAspectRatio: true,
  verticalRatio: 1.0,
  legendLabel: 'stuff',
  cameraPosition: {
    horizontal: -0.35,
    vertical: 0.22,
    distance: 1.8,
  },
}
// To create custom model extensions that will render on to the HTML canvas
// or into the DOM, we must create a View subclass for the model.
//
// In this case we will subclass from the existing BokehJS ``LayoutDOMView``
export class Surface3dView extends LayoutDOMView {
  model: Surface3d

  private _graph: vis.Graph3d

  initialize(): void {
    super.initialize()

    const url = "https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.js"
    const script = document.createElement("script")
    script.onload = () => this._init()
    script.async = false
    script.src = url
    document.head.appendChild(script)
  }

  private _init(): void {
    // Create a new Graph3s using the vis.js API. This assumes the vis.js has
    // already been loaded (e.g. in a custom app template). In the future Bokeh
    // models will be able to specify and load external scripts automatically.
    //
    // BokehJS Views create <div> elements by default, accessible as this.el.
    // Many Bokeh views ignore this default <div>, and instead do things like
    // draw to the HTML canvas. In this case though, we use the <div> to attach
    // a Graph3d to the DOM.
    this._graph = new vis.Graph3d(this.el, this.get_data(), OPTIONS)

    // Set a listener so that when the Bokeh data source has a change
    // event, we can process the new data
    this.connect(this.model.data_source.change, () => {
      this._graph.setData(this.get_data())
    })
  }

  // This is the callback executed when the Bokeh data has an change. Its basic
  // function is to adapt the Bokeh data source to the vis.js DataSet format.
  get_data(): vis.DataSet {
    const data = new vis.DataSet()
    const source = this.model.data_source
    for (let i = 0; i < source.get_length()!; i++) {
      data.add({
        x: source.data[this.model.x][i],
        y: source.data[this.model.y][i],
        z: source.data[this.model.z][i],
      })
    }
    return data
  }

  get child_models(): LayoutDOM[] {
    return []
  }

  _update_layout(): void {
    this.layout = new LayoutItem()
    this.layout.set_sizing(this.box_sizing())
  }
}

// We must also create a corresponding JavaScript BokehJS model subclass to
// correspond to the python Bokeh model subclass. In this case, since we want
// an element that can position itself in the DOM according to a Bokeh layout,
// we subclass from ``LayoutDOM``
export namespace Surface3d {
  export type Attrs = p.AttrsOf<Props>

  export type Props = LayoutDOM.Props & {
    x: p.Property<string>
    y: p.Property<string>
    z: p.Property<string>
    data_source: p.Property<ColumnDataSource>
  }
}

export interface Surface3d extends Surface3d.Attrs {}

export class Surface3d extends LayoutDOM {
  properties: Surface3d.Props
  __view_type__: Surface3dView

  constructor(attrs?: Partial<Surface3d.Attrs>) {
    super(attrs)
  }

  // The ``__name__`` class attribute should generally match exactly the name
  // of the corresponding Python class. Note that if using TypeScript, this
  // will be automatically filled in during compilation, so except in some
  // special cases, this shouldn't be generally included manually, to avoid
  // typos, which would prohibit serialization/deserialization of this model.
  static __name__ = "Surface3d"

  static {
    // This is usually boilerplate. In some cases there may not be a view.
    this.prototype.default_view = Surface3dView

    // The @define block adds corresponding "properties" to the JS model. These
    // should basically line up 1-1 with the Python model class. Most property
    // types have counterparts, e.g. ``bokeh.core.properties.String`` will be
    // ``String`` in the JS implementatin. Where the JS type system is not yet
    // as rich, you can use ``p.Any`` as a "wildcard" property type.
    this.define<Surface3d.Props>(({String, Ref}) => ({
      x:            [ String ],
      y:            [ String ],
      z:            [ String ],
      data_source:  [ Ref(ColumnDataSource) ],
    }))
  }
}
"""

# This custom extension model will have a DOM view that should layout-able in
# Bokeh layouts, so use ``LayoutDOM`` as the base class. If you wanted to create
# a custom tool, you could inherit from ``Tool``, or from ``Glyph`` if you
# wanted to create a custom glyph, etc.
class Surface3d(LayoutDOM):

    # The special class attribute ``__implementation__`` should contain a string
    # of JavaScript code that implements the browser side of the extension model.
    __implementation__ = TypeScript(TS_CODE)

    # Below are all the "properties" for this model. Bokeh properties are
    # class attributes that define the fields (and their types) that can be
    # communicated automatically between Python and the browser. Properties
    # also support type validation. More information about properties in
    # can be found here:
    #
    #    https://docs.bokeh.org/en/latest/docs/reference/core/properties.html#bokeh-core-properties

    # This is a Bokeh ColumnDataSource that can be updated in the Bokeh
    # server by Python code
    data_source = Instance(ColumnDataSource)

    # The vis.js library that we are wrapping expects data for x, y, and z.
    # The data will actually be stored in the ColumnDataSource, but these
    # properties let us specify the *name* of the column that should be
    # used for each field.
    x = String()

    y = String()

    z = String()

def writePlot(plot, plotName):
    """
    Write a plot to file. This setup requires chrome and chromedriver to be
    installed: https://docs.bokeh.org/en/latest/docs/user_guide/export.html
    :param plot: the plot to write to file
    :param plotName: the filename of the plot
    """
    driver = webdriver.Chrome()
    plotName = Path(plotName).with_suffix(".png")
    export_png(plot, filename=plotName, webdriver=driver)
    driver.close()
    del driver

x = np.arange(0, 300, 10)
y = np.arange(0, 300, 10)
xx, yy = np.meshgrid(x, y)
value = np.sin(xx / 50) * np.cos(yy / 50) * 50 + 50

source = dict(image=[value])
plot = figure()
plot.x_range.range_padding = plot.y_range.range_padding = 0
plot.image(source=source, image='image', x=0, y=0, dw=np.max(xx), dh=np.max(yy))
writePlot(plot, "test2d.png")

xx = xx.ravel()
yy = yy.ravel()
value = value.ravel()

source = ColumnDataSource(data=dict(x=xx, y=yy, z=value))
surface = Surface3d(x="x", y="y", z="z", data_source=source, width=600, height=600)
writePlot(surface, "test3d.png")

I'm using python3.9 in a venv on a centos7 system, I've got nodejs14 installed, and my pip freeze is
async-generator==1.10
attrs==21.2.0
bokeh==2.4.1
certifi==2021.10.8
cffi==1.15.0
cryptography==35.0.0
h11==0.12.0
idna==3.3
Jinja2==3.0.2
MarkupSafe==2.0.1
numpy==1.21.3
outcome==1.1.0
packaging==21.2
Pillow==8.4.0
pycparser==2.20
pyOpenSSL==21.0.0
pyparsing==2.4.7
PyYAML==6.0
selenium==4.0.0
six==1.16.0
sniffio==1.2.0
sortedcontainers==2.4.0
tornado==6.1
trio==0.19.0
trio-websocket==0.9.2
typing-extensions==3.10.0.2
urllib3==1.26.7
wsproto==1.0.0


text:
Q: AWS CLI: Attach an existing cloudwatch alarm to an existing auto scaling policy I'm having trouble attaching previously created alarms to an auto scaling group policy.  I have created the policy like so:
aws autoscaling put-scaling-policy --policy-name my-scaleout-policy --auto-scaling-group-name my-group --scaling-adjustment 2 --adjustment-type ChangeInCapacity

However, I can't seem to find the correct CLI command to attach an already created alarm my-cpu-alarm to the policy.

A: Update the existing alarm & add the policy ARN in --alarm-actions parameter.
You can use the put-metric-alarm command for this.
Note that you will have to give all the original parameters to update the alarm as they are overwritten.
You can get the alarm parameters using describe-alarm.


text:
Q: Setting the date to a variable in SQL to call in export file naming convention I have a working exporting script, however I want to improve it by adding todays date to the naming convention of the output. I have tried declaring getdate() to a variable and then calling it but I cannot get it to work.
I currently have:
@export on;
@export set filename="\path\to\file\currentdate.txt";
@export off;

I tried:
DECLARE @currentdate date = getdate()

Then in my export using @currentdate. But the file ended up being named @currentdate.txt.

A: seems like you can use DBVisulizaer Pre-defined Variables:
@export set filename="\path\to\file\${dbvis-date}$.txt";

or
@export set filename="\path\to\file\${myDate||now||Date}$.txt";

Using DbVisualizer Variables


text:
Q: PyBrain LSTM Example resultin in ValueError:Attempted relative import in non-package I'm trying to run an LSTM network for like two weeks now and I cant find a good framework to do so. I'm actually trying with PyBrain which has this directory hierarchy:
pybrain/
    ...
    examples/
        ...
        supervised/
            ...
            neuralnets+svm/
                ...
                example_rnn.py

but I'm getting this relative import error:
Traceback (most recent call last):
File "example_fnn.py", line 14, in <module>
from .datasets import generateGridData, generateClassificationData, plotData
ValueError: Attempted relative import in non-package

when make the call like this:
Lucass-MacBook-Pro:neuralnets+svm lucaslourenco$ python example_fnn.py

some of the answers about this same error say that I should make the call from the parent directory using the -m flag, like:
Lucass-MacBook-Pro:pybrain lucaslourenco$ python -m examples.supervised.neuralnets+svm.example_fnn

When I do it, I get this:
/Users/lucaslourenco/anaconda/bin/python: No module named examples.supervised.neuralnets+svm

*

*Am I just doing a simple mistake on the -m flag call?

*There is a simple way of correcting this without making changes on the framework(you know how bad can be the results of modifying a framework)?

*There are other options of frameworks to run an LSTM example in OSX or W7, preferable in python?

Thank you!

A: Change "from .datasets import" on top of the file to "from datasets import"
ideally the code wants to use a function from datagenerator.py and the location of the datasets folder does not seem to require the relative location i.e. .datasets.
I deduced the answer by looking at other examples pybrain/examples/supervised/backprop/parityrnn.py
While you are at it you might also run into touble with pylab, it seems that the location of functions like show, hold etc. have changed to matplotlib.pyplot instead of pylab


text:
Q: Find the expectation of lottery game I came across this problem from a probability practice book. Could someone give me a hint?
Suppose you have N balls and M of them are red(others aren't red). You keep picking one ball out and NOT putting it back until you get one red ball. Find the expectation of a number of balls you need to pick out.

My approach is to use recursion. Let $X_k$ denote the distribution of number of balls I need to pick to get a red ball with k balls in the pool. Then,

$E(X_k)=\frac{M}{k} + \frac{k-M}{k}(1+E(X_{k-1}))$ , with $E(X_M) = 1$

as with M ball left in the pool, it should be immediate to pick a red ball. But then I end up an equation that I couldn't solve.

$E(X_N) = 1+\frac{N-M}{N}(1+\frac{N-1-M}{N-1}(1+...(1+\frac{1}{M+1}(1+1))))$

can anyone give me a hint or guide me please?

A: Let $\tau$ be the number of balls drawn until the first red ball is drawn. Then for $1\leqslant n\leqslant N-M+1$ we have
$$
\mathbb P(\tau = n) = \frac M{N-(n-1)}\prod_{i=1}^{n-1}\frac{N-M-(i-1)}{N-(i-1)}
$$
So the expected number of balls drawn is
$$
\mathbb E[\tau] = \sum_{n=1}^{M-n+1} n\cdot\mathbb P(\tau = n) = \sum_{n=1}^{N-M+1}\frac M{N-(n-1)}\prod_{i=1}^{n-1}\frac{N-M-(i-1)}{N-(i-1)}.
$$
It turns out this expression has the closed form
$$
1 + \frac{N}{M+1},
$$
as explained in this answer: Expected Value Of Number of Removals From Urn

A: I liked your approach of searching for a recurrence relationship! Its definitely something I would have tried!
Let us think of a slightly different game which you should be able to see is identical to your one.
Let us get $N$ black cards and $M$ red cards. Lets shuffle these well. Notice that your problem is the same as the expected number of cards we must pick of the top until a red card appears.
Let us think of a way to answer that question. Firstly we can add a joker aswell that will be seen as a start position. We can consider the red and joker as "special cards" and the black cards as standard.
Now notice in a well shuffled deck we have  $M+1$ special cards, the $M$ red and $1$ joker and $N$ standard cards. Hence we have a total of $N+M+1$ cards. Hence the expected difference between consecutive special cards is $\frac{N+M+1}{M+1}$
So lets draw cards like this. We consider the joker as the "top of the deck" so we shuffle the cards then locate the joker and start drawing from there. We already saw that the expected difference between consecutive special cards, i.e the joker and the first red card is  $\frac{N+M+1}{M+1}$ so this is our answer.
$\frac{N+M+1}{M+1} = 1 + \frac{N}{M+1}$ if you wanted it in a more concise way
Quick notice that all this joker shinanigans does nothing to change the "randomness" or fairness. It is a perfectly valid way of dealing cards randomly. Try it out.


text:
Q: asp.net dropdown menu items from sql I have a drop down menu
 <asp:DropDownList ID="ddlUser" runat="server" CssClass="form-

control" AppendDataBoundItems="True" DataSourceID="SqlDataSource2"

DataTextField="Person" DataValueField="PersonID"

OnSelectedIndexChanged="ddlUser_SelectedIndexChanged" AutoPostBack="True">

        <asp:ListItem>Select User</asp:ListItem>

        </asp:DropDownList>

        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="

<%$ ConnectionStrings:IBS_6 %>" SelectCommand="SELECT DISTINCT PersonID, PLName

+ '

    ' + PFName + ',' + PMoNo AS Person, PFName, PLName, PMoNo, PEmail, PArea,

PCity, PAge, PGender, PType, PStatus, dbTstamp FROM tbl_persons ORDER BY

dbTstamp DESC"></asp:SqlDataSource>

if the value of any fields of file 'PMoNo' is blank or null then dropdown menu's item's display is blank. Howere the value of the item comes I can select the blank item.

A: If PfMoNo is null, then also PfName + ',' + PfMoNo is null, so DropDown sees Person null and does not display text. You should use
COALESCE(PfMoNo,'') instead of PfMoNo


text:
Q: How to make sure changing collectionview cells appear at the center of the phone screen? Scenario: I have a collection view that is reloaded every 15 seconds. There is no limit to the amount of cells that could be in this collection view, however, only one cell is highlighted at a time. There is only one section, and the collectionview scrolls horizontally. I need to make sure the highlighted cell is always in the center of the phone screen. For example, if the 24th cell is highlighted, it would be a bad user experience to have to scroll all the way until you find it. However, a completely different cell could be highlighted when the collection view gets reloaded in another 15 seconds.
See bottom portion of the image for a better idea of highlighted and unhighlighted cells.
Here's an idea of what I've tried that pertains to the index path of the highlighted cell and making sure it's in the center of the phone screen.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

  EZPlayerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlayerCellID" forIndexPath:indexPath];

  NSDictionary *rowData = [[_gameBoardDictionary objectForKey:@"players"] objectAtIndex:indexPath.row];

  if ([[rowData objectForKey:@"possession"] integerValue] == 1) {
     cell.isHighlighted = YES;
  } else {
     cell.isHighlighted = NO;
  }

  if (cell.isHighlighted) {

     self.highlightedCellIndexPath = [self.collectionView indexPathForCell:cell];

  } else {

  }

  return cell;
}

- (void)viewDidLayoutSubviews {

  [self.collectionView scrollToItemAtIndexPath:self.highlightedCellIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}

I've tried a number of things, but this should provide a reference for my train of thought. Any help would be appreciated. Thank you so much!

A: Please add a observer for the "contentSize" keypath of the collection view.
[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld context:NULL];

You can then move the scrolling code inside the observeValueForKeyPath method.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary  *)changeDict context:(void *)context
{
  [self.collectionView scrollToItemAtIndexPath:self.highlightedCellIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

A: Here's what solved the issue for me. Instead of trying to get the indexPath in cellForItemAtIndexPath, I got the indexPath based on my data and then scrolled to the cell at that indexPath.
NSArray *players = [_gameBoardDictionary objectForKey:@"players"];

self.itemNumber = [players indexOfObjectPassingTest:
                       ^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
                       {
                           return [[dict objectForKey:@"possession"] isEqual:@1];
                       }
                       ];

[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.itemNumber inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];


text:
Q: A continuous Function from $R$ to a Banach Space is Borel-Measurable I think the notation of my book is a bit odd, so I'm having trouble finding any other sources to help me with this proof. The thing I'm trying to prove is that a continuous function, $f$, from $R$ to a Banach Space, $B$, is Borel-Measurable. The definition that my book uses is that a function, $f$ is Borel-Measurable if there exists a sequence of functions that converges pointwise to $f$, s.t every entry of the sequence is the finite sum of scaled indicator sets of the $\sigma$-ring formed by the Borel subsets of $R$.
My thoughts so far are that any point, $b \in B$ is closed, and so the pre-image of $b$ under $f$ should also be a closed set, and thus $f^{-1}[b]$ is in my $\sigma$-field. As such, I could use the indicator function for this set and express $f$ as $f = \sum_{b \in B}b\dot E_{f^{-1}[b]}$ where $E_{f^{-1}[b]}$ is the indicator function for the set $f^{-1}[b]$. However, this sum may not be finite. My next thought was to instead of summing over $b \in B$, sum over balls of radius $\frac{1}{n}$ and then this would converge to my function in the pointwise limit. However, this would assume that my Banach Space is totally bounded. It seems no matter what I think of I'm missing something. Can anyone offer any advice or suggestions?
Thank you!

A: Fix $n$. Then $f([-n,n])$ is a compact set. hence it can be covered by a finite number of open balls of radius $\frac 1 n$, say $A_{n,1},A_{n,2},\cdots, A_{n,k}n$. Let $B_{n,1}=A_{n,1},B_{n,2}=A_{n,2}\setminus A_{n,1}$, $\cdots$, $B_{n,k_n}=A_{n,k_n}\setminus \cup_{j=1}^{k_n-1} A_{n,j}$. Then the sets $f^{-1}(B_{n,j})$ are Borel sets in $\mathbb R$ (because they are differences of two open sets). For $|t| \leq n$ define $f_n(t)=f(t)$ if $f(t) \in B_{n,j}$. Take $f_n(t)$ to be $0$ if $|t| >n$. I leave it to you to verify that this sequence has the required properties.


text:
Q: Line spacing on wrapped text I am currently building content in SharePoint, media & Content WebPart, using Calibri, font size 12pt. I notice that when text wraps it creates a spacing. I would like to have 0pt spacing between wrapped text, how would I accomplish this?
Best,
Lost & Confused

A: You can use css to style the line-height property of your html. Something like this:
<style>
.ms-rtestate-field{
    line-height:1.2;
}
</style>

That will change the line-height for all content-editors on your page. You might also want to apply that to some other selector as well, perhaps #s4-bodyContainer.
In general small line height is more difficult to read. And of course it depends upon the font as well.
Calibri has a fairly tall x-height -- the height of lower case letters, like x, compared to capital letters or letters with risers/descenders. The conventional wisdom is that fonts with tall x-height need a little bit more line spacing to help with legibility. So I would recommend not making it too small. (unless, of course, you don't want people to read it!)
Edit
Just realized that you might not know how to add css to a page....
Add a script editor webpart to your page. Edit the snippet and place the code from above. That will just change it for that one page.
If you want to change it for your whole site, you might create a css file using a text editor or something like dreamweaver. You can then put that file in your style library or site-assets folder. You can then add that style to your masterpage or page layouts.


text:
Q: odoo 12 psycopg2.OperationalError: could not translate host name "db" to address Impacted versions:
odoo 12 , postgresql 10
Steps to reproduce:
docker containers
odoo container was working pretty fine for months, but after trying to upgrade odoo version..
I got the following error..

psycopg2.OperationalError: could not translate host name "db" to address

*

*Postgresql container port:5432

*Both containers [odoo & Postgresql] joined same network

Current behavior:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
LOG :

File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 171, in init , self._cnx = pool.borrow(dsn) , File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 540, in _locked , return fun(self, *args, **kwargs) , File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 608, in borrow , **connection_info) , File "/usr/lib/python3/dist-packages/psycopg2/init.py", line 130, in connect , conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ,psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known - - - ,2019-09-15 15:01:26,057 1 INFO ? odoo.service.server: Initiating shutdown ,2019-09-15 15:01:26,058 1 INFO ? odoo.service.server: Hit CTRL-C again or send a second signal to force the shutdown. ,2019-09-15 15:01:30,959 1 INFO ? odoo: Odoo version 12.0-20190816 ,2019-09-15 15:01:30,960 1 INFO ? odoo: Using configuration file at /etc/odoo/odoo.conf ,2019-09-15 15:01:30,960 1 INFO ? odoo: addons paths: ['/var/lib/odoo/addons/12.0', '/mnt/extra-addons', '/usr/lib/python3/dist-packages/odoo/addons'] ,2019-09-15 15:01:30,961 1 INFO ? odoo: database: odoo@db:5432 ,2019-09-15 15:01:31,104 1 INFO ? odoo.addons.base.models.ir_actions_report: Will use the Wkhtmltopdf binary at /usr/local/bin/wkhtmltopdf ,2019-09-15 15:01:31,265 1 INFO ? odoo.service.server: HTTP service (werkzeug) running on 574638c2fd44:8069 ,2019-09-15 15:01:40,043 1 INFO ? odoo.http: HTTP Configuring static files ,2019-09-15 15:01:40,072 1 INFO ? odoo.sql_db: Connection to the database failed ,2019-09-15 15:01:40,079 1 INFO ? werkzeug: - - [15/Sep/2019 15:01:40] "GET / HTTP/1.1" 500 - 0 0.000 0.031 ,2019-09-15 15:01:40,086 1 ERROR ? werkzeug: Error on request: , File "/usr/lib/python3/dist-packages/odoo/http.py", line 1320, in call , return self.dispatch(environ, start_response) , File "/usr/lib/python3/dist-packages/odoo/http.py", line 1293, in call , return self.app(environ, start_wrapped) , File "/usr/lib/python3/dist-packages/werkzeug/wsgi.py", line 599, in call , return self.app(environ, start_response) , File "/usr/lib/python3/dist-packages/odoo/http.py", line 1453, in dispatch , self.setup_db(httprequest) , File "/usr/lib/python3/dist-packages/odoo/http.py", line 1376, in setup_db , httprequest.session.db = db_monodb(httprequest) , File "/usr/lib/python3/dist-packages/odoo/http.py", line 1537, in db_monodb , dbs = db_list(True, httprequest) , File "/usr/lib/python3/dist-packages/odoo/http.py", line 1504, in db_list , dbs = odoo.service.db.list_dbs(force) , File "/usr/lib/python3/dist-packages/odoo/service/db.py", line 375, in list_dbs , with closing(db.cursor()) as cr: , File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 657, in cursor , return Cursor(self.pool, self.dbname, self.dsn, serialized=serialized) , File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 171, in __init , self._cnx = pool.borrow(dsn) , File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 540, in _locked , return fun(self, *args, **kwargs) , File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 608, in borrow , **connection_info) , File "/usr/lib/python3/dist-packages/psycopg2/init.py", line 130, in connect , conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ,psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known - - -
  ''''

A: Here is the solution.

*

*@ odoo.conf I changed db_host = my_database_server_ip previous it was db_host = db

*restart container

It back to work :)

A: It seems that you are missing the --link option for docker command.
you first should have the postgresql container running:
$ docker run -d -e POSTGRES_USER=odoo -e POSTGRES_PASSWORD=odoo -e POSTGRES_DB=postgres --name db postgres:10

as you can see, the container name is db.
and then you should have the odoo instance up and running:
$ docker run -p 8069:8069 --name odoo --link db:db -t odoo
as you can see here the --link option is telling the odoo container to map all requests to db host to the container named db


text:
Q: How to fetch the JSON array values with condition when we do not have key-value pair     {
  "Data": {
    "pData": [
      {
        "label": "A",
        "value": "1",
        "data": [
          "S_1",
          "OB_1",
          "1.21",
          "2.00",
          "2.17",
          "199",
          "2",
          "96032",
          "687"
        ],
        "uom": null
      },
      {
        "label": "b",
        "value": "16",
        "data": [
          "S_5",
          "OB",
          "767",
          "120.00",
          "90.83",
          "0",
          "2",
          "960300",
          "687"
        ],
        "uom": null
      }
    ]
  },
  "Status": true,
  "Message": "Success"
}

**1 I would like to take the values $..data[3] only if $..data[6] is not equal to zero,Please help me with the expression
2 I would like to fetch $..data[*].value only if$..data[6] is not equal to zero **

A: I think you should go for JSON Extractor, the relevant Json Path expression would be something like:
$.Data.pData[?(@.data[6] == '0')].data[3]

More information: JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios


text:
Q: Remove sibling when image loads I have the following structure:

I want the div with class .image_inner to fade out when image with class .listImage loads.
There will be many of these instances on a page.
This is what I'm trying but it doesn't fade out .image_inner
$(window).on('load', function() {
    $(".listImage").on('load', function () {
        $(this).siblings('.image_inner').fadeOut();
    });
});

A: Note the considerable warnings in the jQuery documentation:

Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

*

*It doesn't work consistently nor reliably cross-browser

*It doesn't fire correctly in WebKit if the image src is set to the same src as before

*It doesn't correctly bubble up the DOM tree

*Can cease to fire for images that already live in the browser's cache

Are you confident that you're able to overcome these?

A: The reason is when window load event is fired all the images are already loaded, so their load event won't be fired again. Try
jQuery(function ($) {
    $(".listImage").on('load', function () {
        $(this).siblings('.image_inner').fadeOut();
    }).filter(function () {
        //trigger the load event for images which are already loaded
        retun this.complete;
    }).trigger('load');
});

A: Your code is working fine.
$(".listImage").on('load', function () {
    $(this).siblings('.image_inner').fadeOut();
});

You will need to call the JS at the end of the body. Please have a look at the jsFiddle: http://jsfiddle.net/giri_jeedigunta/3vkXQ/


text:
Q: IBM MobileFirst 7.0 with Sencha Touch in Windows Phone 8.1 showing errors I am using weinre is WEb INspector REmote for debugging IBM Worklight 7.0-sencha touch 2.4 App.
Tested in Windows Phone Emulator 8.1 WVGA 4 inch 512MB.

*

*When Application Starts it Shows :
Local storage capacity reached. Client logs will not be persisted
LocalStorage Quota exceeded, cannot store -x- wmapp0: /www/default/css/app.css locally
LocalStorage Quota exceeded, cannot store -x-wmapp0:/www/default/app.js locally
ondeviceready event dispatched
wlclient init started
CookieMgr read cookies: {}

*When We Call Worklight Adapter WL.Client.invokeProcedure Calls it Shows Errors Like:
WL.Utils.getSkinLoaderChecksum(..) should be supported only on environments that support direct update Error: WL.Utils.getSkinLoaderChecksum(..) should be supported only on environments that support direct update.

[/apps/services/api/myApplication/windowsphone8/query] exception. TypeError: Unable to get property 'notificationTitle' of undefined or null reference

Uncaught Exception: Unable to get property 'notificationTitle' of undefined or null reference at (compiled_code):3667

A: The first error has nothing to do with MobileFirst; if you're using localstorage in your app it seems you have over-used it.
The second error should not happen and sounds like a product defect. You need to open an IBM support ticket (PMR) and provide the following details: full version number (with build number), a test case app that reproduces the error.


text:
Q: split a string only on spaces that are outside curly braces I am new to regex and I need some help. I read some topics similar to this issue, but I could not figure out how to resolve it.
I need to split a string on every blank space that is not inside a pair of curly braces. Consecutive blank spaces outside the curly braces shall be considered as a single one:
{ TEST test } test { test test} {test test  }   { 123 } test  test

result:
{ TEST test }

test

{ test test}

{test test  }

{ 123 }

test

test

A: \{[^}]+\}|\S+

This matches either a run of any characters enclosed by curly braces, or a run of non-space characters. Grabbing all of the matches for it out of your string should provide you with what you want.

A: Here is exactly what you want...
string Source = "{ TEST test } test { test test} {test test } { 123 } test test";
List<string> Result = new List<string>();
StringBuilder Temp = new StringBuilder();
bool inBracket = false;
foreach (char c in Source)
{
    switch (c)
    {
        case (char)32:       //Space
            if (!inBracket)
            {
                Result.Add(Temp.ToString());
                Temp = new StringBuilder();
            }
            break;
        case (char)123:     //{
            inBracket = true;
            break;
        case (char)125:      //}
            inBracket = false;
            break;
    }
    Temp.Append(c);
}
if (Temp.Length > 0) Result.Add(Temp.ToString());

A: I solved my problem using:
StringCollection information = new StringCollection();
foreach (Match match in Regex.Matches(string, @"\{[^}]+\}|\S+"))
{
   information.Add(match.Value);
}

Thanks for your help guys !!!