text:
Q: python: Read a table from file (created from prettytable) and mantain spaces Let's say I have the following file.txt
$ cat file.txt
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

If I try reading the file like this:
with open('file.txt') as fp:
    lines = fp.readlines()

And then I try to display each line using the gtk2.0 textbuffer (similar to print):
for eachline in lines:
    if idx == 0:
        self.textbuffer.delete(start, end)
        end = self.textbuffer.get_end_iter()
        self.textbuffer.set_text(eachline)
    else:
        self.textbuffer.insert(end, eachline)
        end = self.textbuffer.get_end_iter()

I get the following output:
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide |  1295 |  1158259 |      600.5      |
| Brisbane  | 5905  |  1857594   |      1146.4     |
| Darwin   | 112  |   120900   |      1714.7     |
| Hobart   | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne  | 1566 |  3806092   |      646.9      |
| Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

Any suggesstion how to make it look prettier (like the first table) ?
Thanks in advance!

A: you might want to format your strings like the following:
Python: Format output string, right alignment
the with in the output like
for align, text in zip('<^>', ['left', 'center', 'right']):
    '{0:{fill}{align}16}'.format(text, fill=align, align=align)

in the output, you can specify the with (or get that based on the length of your inputs).
I have not worked with gtk2.0 myself but perhaps it will help https://docs.python.org/3/library/string.html#formatstrings


text:
Q: fetching data from multiple mysql tables through nodejs into hbs file hello i have three different mysql tables in my mysql database and iam trying to  fetch data from these three mysql tables  through nodejs into my homepage without joining,i used UNION for this issue,i tried one sql query for that but its not working its just giving me data only from first table and not from other tables. what will be the right syntax for this issue?
homepage

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <base href='/'>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="css/style.css">
    <title>homepage</title>

Homepage

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarresponsive"
            aria-controls="navbarresponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Home

                    Register

                    Login

    {{!-- jumbotron --}}

        {{#each userData}}

{{title}}

{{status}}

{{description}}

        <video src="http://localhost:5000/images/videos/{{video}}" width="340" height="240" type="video/mp4"></video>

        {{/each}}

routes for homepage

const express = require("express");
const router = express.Router();
const db = require("../config/db_config");
const { ensureAuthenticated } = require("../config/auth");

//  homepage
router.get("/", (req, res) => {
    db.query(
        "SELECT a.title, a.status, a.description FROM posts a UNION ALL SELECT b.images,b.age,b.address FROM images b UNION ALL SELECT c.video,c.address,c.landmark FROM videos c",
        (err, results) => {
            if (err) throw err;
            console.log(results);
            res.render("index", {
                userData: results,
            });
        }
    );
});

// profile page
router.get("/profile", ensureAuthenticated, (req, res) => {
    res.render("profile");
});

// route for update data
router.post("/update", (req, res) => {
    let sql =
        "UPDATE posts SET title ='" +
        req.body.title +
        "', status='" +
        req.body.status +
        "', description='" +
        req.body.description +
        "' WHERE id=" +
        req.body.id;

    let query = db.query(sql, (err, results) => {
        if (err) throw err;
        res.redirect("/post/spost");
    });
});

// //route for delete data
router.post("/delete", (req, res) => {
    let sql = "DELETE FROM posts WHERE id=" + req.body.id + "";
    db.query(sql, (err, results) => {
        if (err) throw err;
        res.redirect("/post/spost");
    });
});

module.exports = router;

redpajama_set_name: RedPajamaStackExchange


text:
Q: sqlalchemy.exc.OperationalError: (OperationalError) unable to open database file None None I am running a program from another person who are inconvenience ask for help from. The program is a website. Server end is written by python and flask (module, http://flask.pocoo.org/). The program has been successfully run on the server. What I need to do is modify something on it. Since the production server is not allowed for test, I tested it in development server locally via flask. However, I could not run even the original program. Below is from python.
(venv)kevin@ubuntu:~/python/public_html$ python index.wsgi

Traceback (most recent call last):
      File "index.wsgi", line 6, in
      from app import app as application

File "/home/kevin/python/public_html/app.py", line 27, in <module>
app = create_app()

File "/home/kevin/python/public_html/app.py", line 12, in create_app
database.init_db()

File "/home/kevin/python/public_html/database.py", line 24, in init_db
Base.metadata.create_all(engine)

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/schema.py", line 2793, in create_all
  tables=tables)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1478, in _run_visitor
with self._optional_conn_ctx_manager(connection) as conn:

File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1471, in _optional_conn_ctx_manager
with self.contextual_connect() as conn:

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1661, in contextual_connect
self.pool.connect(),

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 272, in connect
return _ConnectionFairy(self).checkout()

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 425, in __init__
rec = self._connection_record = pool._do_get()

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 857, in _do_get
return self._create_connection()

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 225, in _create_connection
return _ConnectionRecord(self)

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 318, in __init__
self.connection = self.__connect()

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 368, in __connect
connection = self.__pool._creator()

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/strategies.py", line 80, in connect
return dialect.connect(*cargs, **cparams)

File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 283, in connect
return self.dbapi.connect(*cargs, **cparams)

sqlalchemy.exc.OperationalError: (OperationalError) unable to open database file None None

In the config.py file

LOGFILE = '/tmp/ate.log'
      DEBUG = True
      TESTING = True
      THREADED = True
      DATABASE_URI = 'sqlite:////tmp/ate.db'
      SECRET_KEY = os.urandom(24)

Hence, I created a folder called "tmp" under my user and an empty file called "ate.db". Then, ran it again. It said

IOError: [Errno 2] No such file or directory: '/home/kevin/log/ate.log'

Then, I created the log folder and the log file. Run it, but nothing happened like

(venv)kevin@ubuntu:~/python/public_html$ python index.wsgi
  (venv)kevin@ubuntu:~/python/public_html$ python index.wsgi
  (venv)kevin@ubuntu:~/python/public_html$

If it is successful, the website should be available on http://127.0.0.1:5000/. However, it did not work. Does anybody know why and how to solve it? The codes should be fine since it is now available online. The problem should be a local problem. Thank you so much for your help.
The code of where the program is stuck
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker

engine = None
db_session = None
Base = declarative_base()

def init_engine(uri, **kwards):
    global engine
    engine = create_engine(uri, **kwards)
    return engine

def init_db():
    global db_session
    db_session = scoped_session(sessionmaker(bind=engine))
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import models
    Base.metadata.create_all(engine)

A: I had this issue with sqlite. The process trying to open the database file needs to have write access to the directory as it creates temporary/lock files.
The following structure worked for me to allow www-data to use the database.
%> ls -l
drwxrwxr-x  2 fmlheureux www-data     4096 Feb 17 13:24 database-dir

%> ls -l database-dir/
-rw-rw-r-- 1 fmlheureux www-data 40960 Feb 17 13:28 database.sqlite

A: My database URI started rocking after adding one dot in between ////. Working on windows 7. I had directory and db-file created prior to calling this.
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./dbdir/test.db'

A: Replace:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////dbdir/test.db'

With:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///dbdir/test.db'

A: finally figured it out, had help tho
 import os

file_path = os.path.abspath(os.getcwd())+"\database.db"

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+file_path
 db = SQLAlchemy(app)

A: I think I've seen errors like this where file permissions were wrong for the .db file or its parent directory. You might make sure that the process trying to access the database can do so by appropriate use of  chown or chmod.
This is specifically about Django, but maybe still relevant: https://serverfault.com/questions/57596/why-do-i-get-sqlite-error-unable-to-open-database-file

A: I just met this same problem and found that I make a stupid circular reference .
./data_model.py

from flask.ext.sqlalchemy import SQLAlchemy
from api.src.app import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database/user.db')

db = SQLAlchemy(app)

./app.py

...
from api.src.data_model import db
db.init_app(app)

Then I removed the app.py/db and it works.

A: For those looking for a solution to the OperationalError, not necessarily caused by being unable to open database file None None - you might try adding a pool_pre_ping=True argument to create_engine, i.e.
engine = create_engine("mysql+pymysql://user:pw@host/db", pool_pre_ping=True)

see sqlalchemy documentation:

Pessimistic testing of connections upon checkout is achievable by using the Pool.pre_ping argument, available from create_engine() via the create_engine.pool_pre_ping argument
The "pre ping" feature will normally emit SQL equivalent to "SELECT 1" each time a connection is checked out from the pool; if an error is raised that is detected as a "disconnect" situation, the connection will be immediately recycled, and all other pooled connections older than the current time are invalidated, so that the next time they are checked out, they will also be recycled before use.

A: You're not managing to find the path to the database from your current level. What you need to do is the following:
DATABASE_URI = 'sqlite:///../tmp/ate.db'

That means go up to the root level .. and then navigate down to the database (the relative path is /tmp/ate.db in this case).

A: I had this same issue when trying to start the central scheduler for luigi (python module) with task history enabled.
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

I was attempting to use the following configuration from their documentation:
[task_history]
db_connection = sqlite:////user/local/var/luigi-task-hist.db

However, /user/local/* did not exist on my machine and I had to change the configuration to:
[task_history]
db_connection = sqlite:////usr/local/var/luigi-task-hist.db

Kind of a dumb mistake, but easily overlooked. Might save someone some time. This change got rid of the error in my case and luigid started with no errors.

A: I am doing a course of Python and I have the same problem. Affortunately in the course put the right way to determined the path of the database URI
So it works for me even in the 2022 year.
You need to change:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

to:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<name of database>.db'

I hope that it works for someone.

A: This is the problem related to your file path. If you want to save your file in your root directory itself, then write file_name itself right after '/' -
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///file_name.db'

A: I was able to overcome the same error by running sudo python :)


text:
Q: Accessing a property of a sibling project dependency Let's say I have
<properties>
...
    <module.deployPath>/admin</module.deployPath>
...
</properties>

in the pom.xml of the project A.
And now I'd like to access ${module.deployPath} in another project B where project A is listed as dependency of project B.
Is this possible somehow without using external property files or settings.xml?
Thank you for your help!
Cheers,
b

A: Staying strictly within Maven's property access mechanism, I'm almost certain you can't do that. If you were to add the GMaven plugin and write some Groovy code, then it would probably be possible to get and parse the dependency's pom to get at the property you're looking for.


text:
Q: How to get a React Component reference to change its class using classList? I have create a React Component using the following code. In this i am creating tab and added the class and storing its reference to in a global namespace Interface for further processing.
var TabBody = React.createClass({
  getInitialState: function() {
    return {
      class: 'tabBody tab activeTab'
    }
  },
  render: function() {
    Interfaces.tabBody = this;
    tabSelectionInfo.tabBody = this;
    return (
      React.createElement('div', {
          className: this.state.class,
          onClick: handleTabClick
        },
        React.createElement('span', {}, "Body"))
    );
  }
});

now using the following function, To add a class to the above component and console is showing an error undefined. how i store the refrance of this component in order to change its class later.
handleTabClick = function() {
  Interfaces.tabBody.classList.add('tabPreviewComplete');
}

A: That's because this is the reference to your class instance, not a DOM element. To access DOM elements (since React uses a virtual DOM) you need to create a reference, i.e:
React.createElement('div', {
  ref: 'tabBody'

You can then access it via this.refs.tabBody
You shouldn't pass this reference outside of the class however. Instead you can pass the reference to handleTabClick when the event happens:
React.createElement('div', {
  ref: 'tabBody'
  onClick: e => this.props.handleTabClick(e, this.refs.tabBody)

Then you can do:
handleTabClick = function(e, tabBody) {
    tabBody.classList.add('tabPreviewComplete');
}

Personally I would change the state though, so that if the component re-renders it has the correct class.
Fiddle: http://jsfiddle.net/ferahl/dpvb1h3y/

A: As you have specified in your code that your class name is used using a state variable named 'class' containing the value 'tabBody tab activeTab'
className: this.state.class,

Thats why you must have to use setState() method to change your className. As you have the reference to your class instance in global namespace named 'Interface.tabBody' which can be used to set your className by calling setState() e.g
Interface.tabBody.setState({class: 'tabBody tab activeTab disabled'});

This method is used when you want to access class instance outside of the React.
if you are using handleclick() in your react then you can use the following code
handleTabClick = function() {
  this.setState({class: 'tabBody tab activeTab disabled'});
}

By calling setState() the React will detect changes and re-renders component.

A: Above 16.8, using useRef hooks for functional components,
// useRef takes initialValue as param
const fooBarRef = useRef(null);

//DOM Usage

Hello

Usage of reference for useRef after mounting node element,
//Getting node element
const fooBarNode = fooBarRef.current

//Adding class to node element
fooBarNode.classList.add('bar');

Above 16.3, using createRef for class components,
// Creating ref in a constructor
this.fooBarRef = React.createRef();

// DOM usage

Hello

Usage of reference for createRef after mounting node element,
//Getting node element
const fooBarNode = this.fooBarRef.current

//Adding class to node element
fooBarNode.classList.add('bar');

Below 16.3, using callBackRef,
// Creating ref in a constructor
this.fooBarRef = null;
this.setFooBarRef = (ref) => {
  this.fooBarRef = ref;
}

// DOM usage

Hello

Usage of reference after mounting node element,
//Adding class name
this.fooBarRef.classList.add('bar');


text:
Q: Save PDF from PowerPoint (.pptx) with transparent background I am doing a presentation with Beamer and I want to use some pictures I've made for an old PowerPoint presentation.
The way I am doing it now is:

*

*I put each figure in one slide, then I save the whole .pptx in .pdf format

*I use pdftk to separate the slides in different files

*I use pdfcrop for each of these files to trim the empty areas out

The problem is that I am putting these .pdf files in a document where the background is not white, and they were saved as white, not transparent
I've tried this with no success. Maybe there would be a built-in PowerPoint option or any other utilities for making it transparent since the .pptx conversion phase?

A: I had the same issue and found that selecting the figure and using the Save As Image approach detailed in this SO answer produced incorrect results when the output format is set to PDF (using Office for Mac 2016).
The workaround I found was to post-process the PDFs with Inkscape in the following way:

*

*open the pdf in Inkscape

*select everything with Ctrl+a

*hit Ctrl+Shift+g repeatedly to ungroup the elements in the PDF

*deselect everything

*select the background layer and delete it

*Ctrl+s to save the PDF again


text:
Q: expanding a dataframe based on start and end columns (speed) I have a pandas.DataFrame containing start and end columns, plus a couple of additional columns. I would like to expand this dataframe into a time series that starts at start values and end at end values, but copying my other columns. So far I came up with the following:
import pandas as pd
import datetime as dt

df = pd.DataFrame()
df['start'] = [dt.datetime(2017, 4, 3), dt.datetime(2017, 4, 5), dt.datetime(2017, 4, 10)]
df['end'] = [dt.datetime(2017, 4, 10), dt.datetime(2017, 4, 12), dt.datetime(2017, 4, 17)]
df['country'] = ['US', 'EU', 'UK']
df['letter'] = ['a', 'b', 'c']

data_series = list()
for row in df.itertuples():
    time_range = pd.bdate_range(row.start, row.end)
    s = len(time_range)
    data_series += (zip(time_range, [row.start]*s, [row.end]*s, [row.country]*s, [row.letter]*s))

columns_names = ['date', 'start', 'end', 'country', 'letter']
df = pd.DataFrame(data_series, columns=columns_names)

Starting Dataframe:
       start        end country letter
0 2017-04-03 2017-04-10      US      a
1 2017-04-05 2017-04-12      EU      b
2 2017-04-10 2017-04-17      UK      c

Desired output:
         date      start        end country letter
0  2017-04-03 2017-04-03 2017-04-10      US      a
1  2017-04-04 2017-04-03 2017-04-10      US      a
2  2017-04-05 2017-04-03 2017-04-10      US      a
3  2017-04-06 2017-04-03 2017-04-10      US      a
4  2017-04-07 2017-04-03 2017-04-10      US      a
5  2017-04-10 2017-04-03 2017-04-10      US      a
6  2017-04-05 2017-04-05 2017-04-12      EU      b
7  2017-04-06 2017-04-05 2017-04-12      EU      b
8  2017-04-07 2017-04-05 2017-04-12      EU      b
9  2017-04-10 2017-04-05 2017-04-12      EU      b
10 2017-04-11 2017-04-05 2017-04-12      EU      b
11 2017-04-12 2017-04-05 2017-04-12      EU      b
12 2017-04-10 2017-04-10 2017-04-17      UK      c
13 2017-04-11 2017-04-10 2017-04-17      UK      c
14 2017-04-12 2017-04-10 2017-04-17      UK      c
15 2017-04-13 2017-04-10 2017-04-17      UK      c
16 2017-04-14 2017-04-10 2017-04-17      UK      c
17 2017-04-17 2017-04-10 2017-04-17      UK      c

Problem with my solution is that when applying it to a much bigger dataframe (mostly in terms of rows), it does not achieve a result fast enough for me. Does anybody have any ideas of how I could improve? I am also considering solutions in numpy.

A: First we can build the dates you need, while keeping track of the number of days in each row via the list deltas:
dates = [pd.Series(pd.bdate_range(row[1].start, row[1].end))
         for row in df[['start', 'end']].iterrows()]
deltas = [len(x) for x in dates]
dates = pd.Series(pd.concat(dates).values, name='date')

then use np.repeat to build up the data matrix with the proper segment lengths:
df2 = pd.DataFrame(np.repeat(df.values, deltas, axis=0), columns=df.columns)
df2 = df2.astype(dtype={"start": "datetime64", "end": "datetime64"})

then insert the dates into the front of the dataframe:
df2 = pd.concat([dates, df2], axis=1)

Test Code:
import pandas as pd
import numpy as np
import datetime as dt

df = pd.DataFrame()
df['start'] = [dt.datetime(2017, 4, 3), dt.datetime(2017, 4, 5),
               dt.datetime(2017, 4, 10)]
df['end'] = [dt.datetime(2017, 4, 10), dt.datetime(2017, 4, 12),
             dt.datetime(2017, 4, 17)]
df['country'] = ['US', 'EU', 'UK']
df['letter'] = ['a', 'b', 'c']

dates = [pd.Series(pd.bdate_range(row[1].start, row[1].end))
         for row in df[['start', 'end']].iterrows()]
deltas = [len(x) for x in dates]
dates = pd.Series(pd.concat(dates).values, name='date')

df2 = pd.DataFrame(np.repeat(df.values, deltas, axis=0), columns=df.columns)
df2 = df2.astype(dtype={"start": "datetime64", "end": "datetime64"})
df2 = pd.concat([dates, df2], axis=1)
print(df2)

Results:
         date      start        end country letter
0  2017-04-03 2017-04-03 2017-04-10      US      a
1  2017-04-04 2017-04-03 2017-04-10      US      a
2  2017-04-05 2017-04-03 2017-04-10      US      a
3  2017-04-06 2017-04-03 2017-04-10      US      a
4  2017-04-07 2017-04-03 2017-04-10      US      a
5  2017-04-10 2017-04-03 2017-04-10      US      a
6  2017-04-05 2017-04-05 2017-04-12      EU      b
7  2017-04-06 2017-04-05 2017-04-12      EU      b
8  2017-04-07 2017-04-05 2017-04-12      EU      b
9  2017-04-10 2017-04-05 2017-04-12      EU      b
10 2017-04-11 2017-04-05 2017-04-12      EU      b
11 2017-04-12 2017-04-05 2017-04-12      EU      b
12 2017-04-10 2017-04-10 2017-04-17      UK      c
13 2017-04-11 2017-04-10 2017-04-17      UK      c
14 2017-04-12 2017-04-10 2017-04-17      UK      c
15 2017-04-13 2017-04-10 2017-04-17      UK      c
16 2017-04-14 2017-04-10 2017-04-17      UK      c
17 2017-04-17 2017-04-10 2017-04-17      UK      c

A: Inspired by @StephenRauch's solution I'd like to post mine (which is pretty similar):
dates = [pd.bdate_range(r[0],r[1]).to_series() for r in df[['start','end']].values]
lens = [len(x) for x in dates]

r = pd.DataFrame(
        {col:np.repeat(df[col].values, lens) for col in df.columns}
    ).assign(date=np.concatenate(dates))

Result:
In [259]: r
Out[259]:
   country        end letter      start       date
0       US 2017-04-10      a 2017-04-03 2017-04-03
1       US 2017-04-10      a 2017-04-03 2017-04-04
2       US 2017-04-10      a 2017-04-03 2017-04-05
3       US 2017-04-10      a 2017-04-03 2017-04-06
4       US 2017-04-10      a 2017-04-03 2017-04-07
5       US 2017-04-10      a 2017-04-03 2017-04-10
6       EU 2017-04-12      b 2017-04-05 2017-04-05
7       EU 2017-04-12      b 2017-04-05 2017-04-06
8       EU 2017-04-12      b 2017-04-05 2017-04-07
9       EU 2017-04-12      b 2017-04-05 2017-04-10
10      EU 2017-04-12      b 2017-04-05 2017-04-11
11      EU 2017-04-12      b 2017-04-05 2017-04-12
12      UK 2017-04-17      c 2017-04-10 2017-04-10
13      UK 2017-04-17      c 2017-04-10 2017-04-11
14      UK 2017-04-17      c 2017-04-10 2017-04-12
15      UK 2017-04-17      c 2017-04-10 2017-04-13
16      UK 2017-04-17      c 2017-04-10 2017-04-14
17      UK 2017-04-17      c 2017-04-10 2017-04-17

A: Timings + 3 another solutions:
#original solution
In [163]: %%timeit
     ...: data_series = list()
     ...: for row in df.itertuples():
     ...:     time_range = pd.bdate_range(row.start, row.end)
     ...:     s = len(time_range)
     ...:     data_series += (zip(time_range, [row.start]*s, [row.end]*s, [row.country]*s, [row.letter]*s))
     ...:
     ...: columns_names = ['date', 'start', 'end', 'country', 'letter']
     ...: df3 = pd.DataFrame(data_series, columns=columns_names)
     ...:
1 loop, best of 3: 634 ms per loop

#Stephen Rauch solution, a bit changed because warnings
In [164]: %%timeit
     ...: dates = [pd.Series(pd.bdate_range(row[1].start, row[1].end))
     ...:          for row in df[['start', 'end']].iterrows()]
     ...: deltas = [len(x) for x in dates]
     ...: dates = pd.Series(pd.concat(dates).values, name='date')
     ...: df2 = pd.DataFrame(np.repeat(df.values, deltas, axis=0), columns=df.columns)
     ...: df2['start'] = pd.to_datetime(df2['start'])
     ...: df2['end'] = pd.to_datetime(df2['end'])
     ...: df2 = pd.concat([dates, df2], axis=1)
     ...:
1 loop, best of 3: 669 ms per loop

#maxu solution
In [165]: %%timeit
     ...: dates = [pd.bdate_range(r[0],r[1]).to_series() for r in df[['start','end']].values]
     ...: lens = [len(x) for x in dates]
     ...: r = pd.DataFrame(
     ...:         {col:np.repeat(df[col].values, lens) for col in df.columns}
     ...:     ).assign(date=np.concatenate(dates))
     ...:
1 loop, best of 3: 609 ms per loop

#jezrael solution1
In [166]: %%timeit
     ...: df1 = pd.concat([pd.Series(r.Index,
     ...:                            pd.bdate_range(r.start, r.end))
     ...:                            for r in df.itertuples()]).reset_index()
     ...: df1.columns = ['date','idx']
     ...: df2 = df1.set_index('idx').join(df).reset_index(drop=True)
     ...:
1 loop, best of 3: 632 ms per loop

#jezrael solution2 (improved maxu solution)
In [167]: %%timeit
     ...: dates = [pd.bdate_range(r[0],r[1]) for r in df[['start','end']].values]
     ...: lens = [len(x) for x in dates]
     ...:
     ...: df4 = pd.DataFrame(
     ...:         {col:np.repeat(df[col].values, lens) for col in df.columns}
     ...:     )
     ...: df4.insert(0, 'date', np.concatenate(dates))
     ...:
1 loop, best of 3: 583 ms per loop
#jezrael solution 3
In [207]: %%timeit
     ...: dates = [pd.bdate_range(r[0],r[1]) for r in df[['start','end']].values]
     ...: lens = [len(x) for x in dates]
     ...: r = np.repeat(df.index.values, lens)
     ...: df2 = pd.DataFrame(df.values[r], df.index[r], df.columns).reset_index(drop=True)
     ...: df2['start'] = pd.to_datetime(df2['start'])
     ...: df2['end'] = pd.to_datetime(df2['end'])
     ...: df2.insert(0, 'date', np.concatenate(dates))
     ...:
1 loop, best of 3: 609 ms per loop

Code for timings:
import datetime as dt

df = pd.DataFrame()
N = 100
#N = 1
df['start'] = [dt.datetime(2017, 4, 3), dt.datetime(2017, 4, 5), dt.datetime(2017, 4, 10)]*N
df['end'] = [dt.datetime(2017, 8, 10), dt.datetime(2017, 5, 12), dt.datetime(2017, 5, 17)]*N
df['country'] = ['US', 'EU', 'UK']*N
df['letter'] = ['a', 'b', 'c']*N

A: For your dataframe:
df = pd.DataFrame()
df['start'] = [dt.datetime(2017, 4, 3), dt.datetime(2017, 4, 5), dt.datetime(2017, 4, 10)]
df['end'] = [dt.datetime(2017, 4, 10), dt.datetime(2017, 4, 12), dt.datetime(2017, 4, 17)]
df['country'] = ['US', 'EU', 'UK']
df['letter'] = ['a', 'b', 'c']

       start        end country letter
0 2017-04-03 2017-04-10      US      a
1 2017-04-05 2017-04-12      EU      b
2 2017-04-10 2017-04-17      UK      c

First, set new index using pd.date_range or DatetimeIndex(), with limits first and last values:
index = pd.date_range(df['start'].iloc[0], df['end'].iloc[-1])
# or
index = pd.DatetimeIndex(start=df['start'].iloc[0], end=df['end'].iloc[-1], freq='D')

>>
index = pd.DatetimeIndex(['2017-04-03', '2017-04-04', '2017-04-05', '2017-04-06',
               '2017-04-07', '2017-04-08', '2017-04-09', '2017-04-10',
               '2017-04-11', '2017-04-12', '2017-04-13', '2017-04-14',
               '2017-04-15', '2017-04-16', '2017-04-17'],
              dtype='datetime64[ns]', freq='D')

Then reindex() with method=ffill and reset_index and rename:
df2 = df.set_index(['start']).reindex(index, method='ffill')
df2['Date'] = df2.index
df2.reset_index().rename(columns={'index':'start'})

        start        end country letter       Date
0  2017-04-03 2017-04-10      US      a 2017-04-03
1  2017-04-04 2017-04-10      US      a 2017-04-04
2  2017-04-05 2017-04-12      EU      b 2017-04-05
3  2017-04-06 2017-04-12      EU      b 2017-04-06
4  2017-04-07 2017-04-12      EU      b 2017-04-07
5  2017-04-08 2017-04-12      EU      b 2017-04-08
6  2017-04-09 2017-04-12      EU      b 2017-04-09
7  2017-04-10 2017-04-17      UK      c 2017-04-10
8  2017-04-11 2017-04-17      UK      c 2017-04-11
9  2017-04-12 2017-04-17      UK      c 2017-04-12
10 2017-04-13 2017-04-17      UK      c 2017-04-13
11 2017-04-14 2017-04-17      UK      c 2017-04-14
12 2017-04-15 2017-04-17      UK      c 2017-04-15
13 2017-04-16 2017-04-17      UK      c 2017-04-16
14 2017-04-17 2017-04-17      UK      c 2017-04-17

# Time:
0.009 s

Old answer:
Use, reindex() on column start and expand using asfreq():
df2 = df.set_index(['start']).asfreq('D').fillna(method='ffill').reset_index()
>>>
       start        end country letter
0 2017-04-03 2017-04-10      US      a
1 2017-04-04 2017-04-10      US      a
2 2017-04-05 2017-04-12      EU      b
3 2017-04-06 2017-04-12      EU      b
4 2017-04-07 2017-04-12      EU      b
5 2017-04-08 2017-04-12      EU      b
6 2017-04-09 2017-04-12      EU      b
7 2017-04-10 2017-04-17      UK      c

asfreq documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.asfreq.html

A: Since the goal here is speed, we should vectorize every step. A single for-loop can slow the code by multiple orders-of-magnitude. A vectorized solution is provided below:
cols = list(df.columns)

df['data_id'] = np.arange(0, len(df))

data_id = df['data_id']
start = df['start']
end = df['end']

diff = ((end-start) / np.timedelta64(1, 'D')).astype('int') + 1
repeated_id = np.repeat(data_id, diff)
time_df = pd.DataFrame(data={'data_id': repeated_id})
time_df = pd.merge(left=time_df, right=df[['data_id', 'start']], on=['data_id'])
time_df['day_id'] = np.arange(0, len(time_df))

min_day_id = time_df.groupby('data_id')['day_id'].min().reset_index().rename(columns={'day_id': 'min_day_id'})
time_df = pd.merge(left=time_df, right=min_day_id, on=['data_id'])
days_to_add = (time_df['day_id'] - time_df['min_day_id']) * np.timedelta64(1, 'D')
time_df['date'] = time_df['start'] + days_to_add

time_df = time_df[time_df['date'].dt.dayofweek < 5]

df = pd.merge(left=df, right=time_df[['data_id', 'date']], on=['data_id'])
df = df[['date']+cols]

The vectorized version works as follows:

*

*Give each row of the original dataframe an 'id' column (the dataframe index could also work)

*Create a new dataframe which expands each row to the number of days in the range

*Enumerate each group of expanded rows with integers 0..N

*Add this number of days to the start date to get the actual date

*Filter business days

*Merge the expanded dataframe with dates back to the original dataframe on the 'id' column

When comparing jezrael's timed runs, the 'original method' took 1.15s on my machine, while the vectorized version took 56.9ms, a 20-fold speedup.


text:
Q: Ctrl+C and Ctrl+V for copy and paste not working on Ubuntu 22.04 I am not able to use the shortcuts keys Ctrl+C and Ctrl+V for copy and paste, respectively, on my Ubuntu 22.04. However, Ctrl+A works fine. Ctrl+Alt+T also does not work.

A: I had the same problem in Ubuntu 22.04.
Some Ctrl functions worked, but Ctrl+C, Ctrl+V and Ctrl+Z didn't work (not talking about the terminal, which has a different behavior with shortcuts). Both shortcuts, Ctrl+Insert and Shift+Insert worked.
After several hours of unuseful googling and trying things (and multiple times coming to your question...), the solution was quite simple and weird:
I went to Configuration > Keyboard > Shortcuts > Custom Shortcuts (I use it in Spanish, in this link shows how to do it)
There were three custom shortcuts (although I customized none of them...), Ctrl+C, Ctrl+V and Ctrl+Z. When I disabled or deleted them, they started to work as expected.


text:
Q: Python Dictionary: Sorting Trouble I thought i found away to sort a dictionary by clearing it then reassemble it in the order i wanted but for some reason it reorders itself the way it started out.
Here is the code if somebody can help me out
from operator import itemgetter

n = {}
d = {
 'a': ['2', 'ova', 'no'],
 'b': ['23', 'movie', 'yes'],
 'c': ['5', 'show', 'yes'],
 'd': ['17', 'ova', 'yes'],
 'e': ['1', 'movie', 'no']
}

for i in d:
    print i, d[i]

print '\n'

l = d.items()
l.sort(key=itemgetter(1)) #l is now sorted by the value of the string holding the integers
d.clear()

for i in l:
    print i[0], i[1]
    d[i[0]] = i[1]

print '\n'

for i in d:
    print i, d[i] #Why does the dictionary come out to be the same it started from

A: As Jon points out, dictionaries have no order.  You get fast lookups by giving up ordering.  You might not need it to keep an order though, since you have a sort order you like:
d = {'a':['2', 'ova', 'no'], 'b':['23', 'movie', 'yes'], 'c':['5', 'show', 'yes'], 'd':['17', 'ova', 'yes'], 'e':['1', 'movie', 'no']}
sorted_items = sorted(d.items(), key=itemgetter(1))
for i,v in sorted_items:
    print i, v

A: Dictionaries are inherently un-ordered (as they use hash keys - which are unique but arbitary) [this is a FAQ] - you may want to consider using an OrderedDict (in 2.7+) which retains insertion order or a recipe from PyPi - otherwise, if you require order, you need to keep entries in a list or other sequence.


text:
Q: Building efficient multi geometry type database with PostGIS? I'm trying to build a PostGIS database which must be able to store (multi)points, (multi)linestrings and (multi)polygons. The goal is to efficiently querying the data with ST_Intersects and other related functions.
My first look was at GeometryCollection. I thought that was tailor-made for my needs, i thought i'll just dump various geometry types to a GeometryCollection, create an index and forget about it. Well, then i realized that ST_Intersects does not support GeometryCollection.
So my plan B is to store each data type independently in a column (with indexes of course) and query the database using OR clauses for each data type column like:
WHERE (ST_Intersects(a_geometry, point_geometry) OR ST_Intersects(a_geometry, linestring_geometry) OR ST_Intersects(a_geometry, polygon_geometry))
With proper indexes set, this looks efficient, but in this day and age i suspect there must be some better way? Some better approach that is common enough but i am not aware of?
All queries on database will be SELECTs. Data insertion will be a one time process.

A: I think you may have misunderstood the docs.  A geometry collection is something of the form:
GEOMETRYCOLLECTION(....).
Just because you have a mix of multipoints, multilinestrings and multipolygons in the same geometry column doesn't make them a geometry collection.  multis are not considered geometry collections either.
If you truly plan to have GEOMETRYCOLLECTIONs in your geometry column,
You can use ST_DWithin with a small tolerance or no tolerance.  ST_DWithin works with geometry collections -
http://postgis.net/docs/manual-2.2/ST_DWithin.html
So replace your ST_Intersects with (0 or low tolerance)
ST_DWithin(a_geometry, point_geometry, 0);

A: I think your plan to store each data subtype independently in a column is the right choice. As written in the book "PostGIS in Action", the use of the GeometryCollection subtype is not recommended: "In real-world applications, you should rarely define a data column as geometry-collection . Although having a collection is perfectly reasonable for storage purposes, using it within a function rarely makes any sense [...] You should be prepared to work with them, but avoid using them in your table design." (Obe R. and Hsu L., 2015).


text:
Q: How would I fill this dimensional array in C# with an for loop? I have an dimensional array which is hardcoded which i would like to make an for loop for so randomized characters get inserted.
And then show it in the console as 3 by 3 with an foreach (that is what i tried):
a b c
d b a
a b d
So i can count them since i need to make a pointing system as they have specific points. (this i can
manage on my own) But i was stuck with the dimensional array. It worked with a single dimension array but i need a 3 by 3 pointing game system.
Random random = new Random();
String chars = "ABCD";

// the array i want to make a for loop for
string[,] main = new string[3, 3];

// the example array how it should look after the for loop inserted data.
string[,] main_example = new string[3, 3] { { "c", "b", "a" }, { "d", "a", "b" }, { "a", "d", "a" }
};

// inserts a or b or c or d.
for (int i = 0; i < cards9.Length; i++) {
    main[i, i] += chars[random.Next(chars.Length)];
}

// the foreach to display the data in the console
foreach (string i in main) {
   System.Console.Write("{0} ", i);
}

A: Just use nested for loop, GetLowerBound, and GetUpperBound:
var array = new string[3, 3];

for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
{
    for (var j = array.GetLowerBound(1); j <= array.GetUpperBound(1); j++)
    {
        // replace guids to your initialization code
        array[i, j] = Guid.NewGuid().ToString();
    }
}

A: Single loop:
  for (int i = 0; i < cards9.Length; i++) {
        var c = chars[random.Next(chars.Length)].ToString();
        main[i / 3, i % 3] = c;
    }

The above code calculates all possible indexes of 3x3 array.
if print using below code then it will printout as follows
   for (var i = main.GetLowerBound(0); i <= main.GetUpperBound(0); i++)
    {
        for (var j = main.GetLowerBound(1); j <=main.GetUpperBound(1); j++)
        {
            // replace guids to your initialization code
            Console.Write(main[i,j] + " ");
        }

        Console.WriteLine();
    }

B B D
C C D
A A C

You can check this fiddle -- https://dotnetfiddle.net/6vEu8f

A: First issue is that you would liketo have lower case characters, but your chars contains only uppercase. Also, you want to have array of chars and we know that string is basically it, but more clear way would be to use char[].
Second, it would simplify the code, if you could define number of rows and columns for your multidimensional array in one place and then use just parameters.
Third, to loop over mutlidimensional array, you need to use nested loop.
Putting it all together, I would suggest such changes to the code:
private static char[,] GenerateRandomCharArray()
{
    var rnd = new Random();
    var chars = new char[] { 'a', 'b', 'c', 'd' };
    var charLength = chars.Length;
    var rows = 3;
    var columns = 3;
    var result = new char[rows, columns];
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            result[i, j] = chars[rnd.Next(charLength)];

    return result;
}


text:
Q: How to bind data from dropdown list in asp.net 6 MVC I have 2 models name BTBNewLien2 & BuyerSelectList. Now I want to bind "BuyerSelectList" data at the BTBNewLien2 model. How can I do that? All the necessary codes are given below:  My Question is where should I use ViewBag for Binding Data? I can create all the related views. I just need help with the Controller.
BTBNewLien2.cs Model:
public class BTBNewLien2
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [DisplayName("Buyer")]
        public int BuyerSelectListId { get; set; }

        [ForeignKey("BuyerSelectListId")]
        [ValidateNever]
        public BuyerSelectList BuyerSelectList { get; set; }
    }

BuyerSelectList.cs Model :
public class BuyerSelectList
    {
        [Key]
        public int Id { get; set; }
        [DisplayName("BUYER")]
        public string Buyer { get; set; }
    }

BTBNewLien2Controller :
public class BTBNewLien2Controller : Controller
    {
        private readonly IUnitOfWork _unitOfWork;
        public BTBNewLien2Controller(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public IActionResult Index()
        {
            IEnumerable<BTBNewLien2> objBTBNewLienList = _unitOfWork.BTBNewLien2.GetAll();
            return View(objBTBNewLienList);
        }
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(BTBNewLien2 obj)
        {
            if (ModelState.IsValid)
            {
                _unitOfWork.BTBNewLien2.Add(obj);
                _unitOfWork.Save();
                TempData["success"] = "Row Created Successfully!";
                return RedirectToAction("Index");
            }
            return View(obj);
        }
        public IActionResult Edit(int? id)
        {
            if (id == null || id == 0)
            {
                return NotFound();
            }
            var objBTBNewLienList = _unitOfWork.BTBNewLien2.GetFirstOrDefault(c => c.Id == id);
            if (objBTBNewLienList == null)
            {
                return NotFound();
            }
            return View(objBTBNewLienList);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(BTBNewLien2 obj)
        {
            if (ModelState.IsValid)
            {
                _unitOfWork.BTBNewLien2.Update(obj);
                _unitOfWork.Save();
                TempData["success"] = "Row Edited Successfully!";
                return RedirectToAction("Index");
            }
            return View(obj);
        }
        public IActionResult Delete(int? id)
        {
            if (id == null || id == 0)
            {
                return NotFound();
            }
            var objBTBNewLienList = _unitOfWork.BTBNewLien2.GetFirstOrDefault(c => c.Id == id);
            if (objBTBNewLienList == null)
            {
                return NotFound();
            }
            return View(objBTBNewLienList);
        }
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeletePOST(int? id)
        {
            var obj = _unitOfWork.BTBNewLien2.GetFirstOrDefault(c => c.Id == id);
            if (obj == null)
            {
                return NotFound();
            }
            _unitOfWork.BTBNewLien2.Remove(obj);
            _unitOfWork.Save();
            TempData["success"] = "Row Deleted Successfully!";
            return RedirectToAction("Index");
        }
    }

BTBNewLien2Repository:
public class BTBNewLien2Repository : Repository<BTBNewLien2>, IBTBNewLien2Repository
    {
        private ApplicationDbContext _db;
        public BTBNewLien2Repository(ApplicationDbContext db) : base(db)
        {
            _db = db;
        }

        public void Update(BTBNewLien2 obj)
        {
            var objFromDb = _db.BTBNewLien2.FirstOrDefault(c => c.Id == obj.Id);
            if (objFromDb != null)
            {
                objFromDb.BuyerSelectListId = obj.BuyerSelectListId;
            }
        }
    }


text:
Q: (Proof Verification) $E(X) = \int_0^{\infty}(1-F(x))dx$ Let continuous random variable $X \ge 0$ and $E(X) \lt \infty$.
Let cumulative density function $F(X)$ is differentiable at all points of X,
show that
$E(X) = \int_0^{\infty}(1-F(x))dx$

Since $F'(x) = f(x)$,
$E(X) = \int_0^{\infty}xf(x)dx = \int_0^{\infty} xF'(x)dx$
Using integration by parts, we get
$\int_0^{\infty} xF'(x)dx = 1- \int_0^{\infty} F(x)dx =  \int_0^{\infty}(1-F(x))dx$

A: HINT
As someone wrote in the comments IBP doesn't work here cause of the boundary term.
Write $$X = \int_0^\infty I(X > x)dx$$
where $I$ is the indicator function.

A: A lot of probability problems boil down to writing the number "1" in the right way. Here, we recognize that $1 = \lim_{x \to\infty} F(x)$ and write
$$ \int_0^\infty (1 - F(x)) \,\mathrm{d}x = \int_0^\infty \int_x^\infty f(t) \,\mathrm{d}t \,\mathrm{d}x = \int_0^\infty \int_0^t f(t) \,\mathrm{d}x \,\mathrm{d}t = \int_0^\infty tf(t) \,\mathrm{d}t = \mathbb{E}[X], $$
where the interchange of integrals is permissible by the positivity of $f$.
Edit: this equality also holds if $\mathbb{E}[X] = \infty$; that is, one need not know that $\mathbb{E}[X]$ exists a priori before computing the integral. This is because Fubini's theorem does not demand an $L^1$ condition when the integrand is positive.


text:
Q: SAML - Triggering Single Logout (SLO) when session times out at the identity provider Let's say I have Saleforce set up as an Identity Provider with a session timeout of 15 minutes. I set up a connected app with SAML and SLO. I use SSO to access a connected app and start working only on the other application for 30 minutes. My questions:

*

*Will my Salesforce session time out after 15 minutes

*If it does, will I be logged out of the external application

I didn't manage to find any documentation on this. I know that if you purposely logout of Salesforce all connected app sessions will be terminated, but not sure what happens in a session time out.

A: The answer is yes to both questions.
However, the important thing to note about the timeout value is that you shouldn't necessarily expect perfect timing due to how the system checks for activity as noted in the description of timeout value here

The last active session time value isn't updated until halfway through
  the timeout period. So if you have a 30-minute timeout, the system
  checks for activity when 15 minutes have passed. If you update a
  record after 20 minutes, your timeout resets because it's 5 minutes
  after the active session time is checked. In that scenario, you have
  another 30 minutes before log out occurs, for a total of 50 minutes.
  But if you update a record after 10 minutes, logout occurs 20 minutes
  later (30 minutes total) because there was no activity in the past 15
  minutes.

The help doc concerning managing session policies also states the following for understanding which timeout policies will affect your connected app if you don't set one on the connected app itself:

You can control how long a user's session lasts by setting the timeout
  value for the connected app, user profile, or org's session settings
  (in that order). If you don't set a value or you select None (the
  default), Salesforce uses the timeout value in the user's profile. If
  the user's profile doesn't specify a timeout value, Salesforce uses
  the timeout value in the org's Session Settings.


text:
Q: How to delete a line using sed? I have a input file with following pattern-
    8799,,2015-06-29 04:00:00+0000,
    FIT-I6-INL-PCG,['3.MYFIT-LTR-DYN'],2015-03-11 04:00:00+0000,

Here I copied three different field separated by , (comma) I wanted to delete every line which has empty field. in above case 1st line has an empty field SO the o/p should be
   FIT-I6-INL-PCG,['3.MYFIT-LTR-DYN'],2015-03-11 04:00:00+0000,

A: You can use this sed:
sed -i.bak -E '/^,|,,/d' file

cat file
FIT-I6-INL-PCG,['3.MYFIT-LTR-DYN'],2015-03-11 04:00:00+0000,

/^,|,,/d will delete a line if comma is 1st char or if there are 2 commas together.

A: With grep:
grep -v '^,\|,,' file

With sed:
sed '/^,\|,,/d' file

If you want to change the file in-place, then:
sed -i.bak '/^,\|,,/d' file
# Or with grep:
# echo "$(grep -v '^,\|,,' file)" >file


text:
Q: Server refused our key error I try to connect Ubuntu 16.04 using ssh following this tutorial.
In my version of putty there is only one RSA option so I used that. I generated a key beginning with ssh-rsa, but I always getting this error:
Server refused our key error

A: I solved the issue myself.
I misspelled the file authorised_keys instead of authorized_keys in ~/.ssh/
Silly but true.


text:
Q: Php Api Client Authorization Bearer I am using the following function to call API Service that uses Authorization Bearer for authentication. I am getting Authentication Failed.
function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    // curl_setopt($curl, CURLOPT_USERPWD, "username:password");
    curl_setopt($curl, CURLOPT_HTTPHEADER, "Authorization: Bearer a9esthaVUjOuvzTCSTXsJUCK0lCMCk");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    echo $result;

    return $result;
}

A: It had to be
array('authorization: Bearer a9esthaVUjOuvzTCSTXsJUCK0lCMCk')


text:
Q: Domain filter based on field in res.users for Odoo XML tree view My question is:
How can I reference a field in res.user and use it as a custom filter when opening a tree view in Odoo 10?
I extended res.user to add a field called: assigned_office. This is a Selection field.
I am now trying to use this value to filtering records when calling a specific window action to filter records by default.
I have tried adding the following to my Window Action, but it gave me an error
(NameError: name 'user' not defined).
<field name="domain">[('responsible_office','=',user.assigned_office)]</field>

I have tried to modify the search view by adding variations of this to the existing filter:
('responsible_office','=',user.assigned_office)
('responsible_office','=',ref='self.assigned_office))
('responsible_office','=',ref=assigned_office)

But I am also getting errors:

Error: Failed to evaluate search criterions:
  {"code":400,"message":"Evaluation
  Error","data":{"type":"local_exception","debug":"Local evaluation
  failure\nExpected \")\", got \"(name)\"\n\n{\"domains\":[[],\"[
  ('expiration_date','<=',(context_today())
  ,('responsible_org','=',ref='self['assigned_org']')
  ]\"],\"contexts\":[{\"lang\":\"en_US\",\"tz\":false,\"uid\":1,\"search_default_weekly_expirees_filter\":1,\"params\":{\"action\":205}},{}],\"group_by_seq\":[]}"}}

I am obviously doing something wrong and I hope there is a simple answer.
Here is my code:
Window Action:
<record id="my_tool_weekly_expirees_action" model="ir.actions.act_window" >
  <field name="name">Weekly Expirees</field>
  <field name="res_model">my_tool.member</field>
  <field name="view_type">form</field>
  <field name="view_mode">tree,form</field>
  <field name="context">{"search_default_weekly_expirees_filter":1}</field>
  <field name="view_id" ref="weekly_expirees_view"/>
</record>

SEARCH:
<record id="members_search_view" model="ir.ui.view" >
  <field name="name">Search</field>
  <field name="model">my_tool.member</field>
  <field name="arch" type="xml">
      <search>
          <field name="first_name"/>
          <field name="last_name"/>

          <field name="expiration_date" string="weekly_expirees" filter_domain="[('expiration_date','<=',(context_today())]"/>
          <separator/>
          <filter string="Weekly Expirees" name="weekly_expirees_filter" domain="[('expiration_date','<=',(context_today())]" help="..."/>
          <separator/>

          <field name="expiration_date"/>
          <field name="responsible_office"/>
      </search>
  </field>
</record>

TREE VIEW
<record id="members_list_view" model="ir.ui.view" >
  <field name="name">members.list</field>
  <field name="model">my_tool.member</field>
  <field name="arch" type="xml">
      <tree>
      <field name="first_name"/>
      <field name="middle_name"/>
      <field name="last_name"/>
      <field name="expiration_date"/>
      <field name="responsible_office"/>
      <field name="country"/>
    </tree>
  </field>
</record>

I have searched stackoverflow.com and the forums at odoo.com and found complicated approaches that I either do not understand or want to do:
The most promising is, but it still seems to be a hack work around:
Odoo v9 domain filter with value user.id throws error that user is not defined
Another one that I found that might be even better is.
how to filter tree view with dynamic field odoo-10

A: The most 2 simple ways to get your domain working will be:

*

*Create a Security ir.rule record for the model where you will be able to use the variable user to refer to the current user in the domain_force field, like:
<record id="my_tool_member_rule" model="ir.rule">
    <field name="name">My Tool Members Rule</field>
    <field name="model_id" ref="my_tool.member"/>
    <field name="domain_force">[('responsible_office','=',user.assigned_office)]</field>
    <field name="perm_read" eval="True"/>
    <field name="perm_create" eval="False"/>
    <field name="perm_write" eval="False"/>
    <field name="perm_unlink" eval="False"/>
</record>

*Override the model my_tool.member search method to add the custom domain, like:

from odoo import api, models
class MyToolMember(models.Model):
    _name = 'my_tool.member'

    def search(self, args, offset=0, limit=None, order=None, count=False):
        args.append(('responsible_office', '=', self.env.user.assigned_office))
        return super(MyToolMember, self).search(args, offset=0, limit=None, order=order, count=False)


text:
Q: Flow deployment error in Copado "you must specify a record filter or a formula" I have a very simple Record Triggered flow.
When deploying a flow using Copado I am getting an error
Because All Conditions are Met or Any Conditions are Met is specified, you must specify a record filter or a formula

This is my configuration page. There is no Entry Condition

This is the criteria at the Decision Node

I am not sure where what record filter or formula I need to specify and where ?
Can someone help me in understanding this specific deployment error?

A: @SumitKumar I deleted the flow and rebuilt a new flow without formula and deployed. Fortunately for me I could use basic criteria instead of formula.
However at least 4 other folks working on other projects encoutered this issue. Some of the resolutions are as follows

*

*Deploying through Change set is fine

*Copado is still on Metadata version 54, they're not switching to v55 until next week. Updating the API version in the project level sfdx-project.json file seems to have done the trick

*it work when you use sfdx and specify the version as 55 in your package.xml when retrieving and deploying

Hope this helps.


text:
Q: MKMapView crash in ios6 at the first time MKMapView crash in iOS 6 for the first time when app is launched in my device. after crash it runs smoothly. It only happens on the first launch of app in any device.
Example: app launches in my iPhone 4S. Crashed.
I again tap on app and it is running smoothly.
Please help me. i am not able to debug it as it is not entering into view controller. I am using storyboard and MKMapView is there in storyboard.

A: this issue is only storyboard related. Try resetting simulator and run again.

A: First Add Mapkit/Mapkit.h framework to the project at buildsettings. And then import the mapkit framework to the project. set the MKmapviewDelegate at in .h file. And then Create outlet for the MKmapview. Drag and drop the Mapview to the xib file and connect the outlet to the xib mapview object.
import
import
@interface ViewController : UIViewController
{
IBOutlet MKMapView *mapview;

}

A: Sorry for my late answer.may be it will helpful to someone else.
I faced the same problem. I found its solution. It is crashing only for Storyboard.
Try the following:
1. create outlet for Mapview
2. Set its delegate in viewDidLoad
3. Try loading the map with delay. (In my case it helped)
4. remove delegate on dealloc.


text:
Q: Where do I ask questions related to producing print-ready graphics? I recently posted a post on creating covers for books for Software Recommendations. I wondered if there are Stack Exchange communities out there that also help fellow Stack Exchangers about the issues related to the printing of those softcopies.
I mean questions like how are the soft copies taken to printing, do they convert our PNG format to something else, how do they handle the hardware with the CMYK when the softcopy had an RGB, etc.

A: If you are talking about printing by professionals (printing and publishing), it looks like these questions are on topic on Graphic Design; as always, check their Help Center before posting there.
Checking the Help Center is especially important as it seems that the focus of Graphic Design Stack Exchange is more on creating than on publishing.
Depending on circumstance, some of it might also be on-topic on Writers Stack Exchange.
For printing by end-users, on their home printer, you can go to Super User. Super User is a pretty busy site, so take care that your question is not too broad. Make sure it addresses a specific problem. There's a good chance that generic printing questions will be downvoted and closed there. It should help a lot if your question identified a problem on a specific model (or model series) of printer.

A: Printing related questions are certainly welcome on Graphic Design, please have a look through previous questions first as there are a number of questions about color conversion, file formats, preparing files for print etc.
Questions about home printers may be ok if you're asking about preparing your files or design considerations, but questions related to the printer itself ("Tech Support" questions are specifically off-topic) would probably be better asked on Super User.


text:
Q: Sorting of set of objects is incorrect When I print the whole set, the result is unsorted AND it contains one duplicate.
The object Person has a surname, a familyname and year of birth (all 3 are strings). I first sort by year of birth, then by familyname and then by surname. Per se, there are no identical persons (but even if was the case, it should be eliminated as they get inserted into the set ).
To be more concrete, I create a set of persons like this:
std::set <Person> greatUncles;

and insert them like this:
greatUncles.insert(Person("bla", "bla", "1900"));

Here's are the essential things from class Person:
class Person {
public:
  //...

  Person(std::string s, std::string f, std::string y)
    :surname(s), familyname(f), yearOfBirth(y)
  {
  }

  //...

  std::string getSurname() const {
    return surname;
  }

  std::string getFamilyname() const {
    return familyname;
  }

  std::string getYearOfBirth() const {
    return yearOfBirth;
  }

private:
  std::string surname;
  std::string familyname;
  std::string yearOfBirth;
};

//to print the set, overload the '<<' operator
std::ostream &operator<<(std::ostream &o, const Person &person) {
  o << person.getSurname() << " "
    << person.getFamilyname() << " "
    << person.getYearOfBirth() << std::endl;
  return o;
}

//to order the set, overload the '<' operator
bool operator< (Person const &p1, Person const &p2) {
  int compareYearOfBirth = p1.getYearOfBirth().compare(p2.getYearOfBirth());

  if (compareYearOfBirth == 0) {
    int compareFamilyname = p1.getFamilyname().compare(p2.getFamilyname());
    if (compareFamilyname == 0) {
      return p1.getSurname().compare(p2.getSurname());
    } else
      return compareFamilyname;
  } else
    return compareYearOfBirth;
}

and here is how I print the set of great-uncles:
void printGreatUncles(std::set <Person> &greatUncles) {
    std::ofstream outputFile;
    outputFile.open("greatuncle.dat");

    if (outputFile.is_open()) {
      for(Person const & person:greatUncles) {
        outputFile << person;
      }
      outputFile.close();
    }
  }

Now the output in a certain case should look like this (sorted by year):
Sebastian Furtweger 1942
Nikolaus Furtweger 1951
Archibald Furtweger 1967

but it looks like this:
Archibald Furtweger 1967
Sebastian Furtweger 1942
Nikolaus Furtweger 1951
Archibald Furtweger 1967

I can't figure it for my life what (things) I'm doing wrong.

A: std::set requires the comparator provides a strict weak ordering.  Part of that is if a < b == true then b < a == false but you don't have this.  Lets imagine the birth year and the family names are the same, and only the surnames are different.  In you example you would return some positive or negative number which is converted to true since only 0 is false.  If you run the check backwards then you get the opposite value in the integer, but it still results in true.
To fix this C++11 offers std::tie that you can use to build a std::tuple of the members and its operator < is built to do the right thing.  That makes you code look like
bool operator< (Person const &p1, Person const &p2) {
  return std::tie(p1.getYearOfBirth(), p1.getFamilyname(), p1.getSurname()) <
         std::tie(p2.getYearOfBirth(), p2.getFamilyname(), p2.getSurname());
}

If you ever want to do this going forward and can use C++20 then you can add to Person
auto operator<=>(const Person&) const = default;

and that will automatically give you operators ==, !=, <, <=, >, and >= for Person and they will "do the right thing" as long as you want all members compared in the order they are defined in the class.

A: You are returning the int returned by std::string::compare as a bool. That's not what you want, as both 1 and -1 are converted to true.
The correct comparison code would be:
//to order the set, overload the '<' operator
bool operator< (Person const &p1, Person const &p2) {
  int compareYearOfBirth = p1.getYearOfBirth().compare(p2.getYearOfBirth());

  if (compareYearOfBirth == 0) {
    int compareFamilyname = p1.getFamilyname().compare(p2.getFamilyname());
    if (compareFamilyname == 0) {
      return p1.getSurname().compare(p2.getSurname()) < 0;
    } else
      return compareFamilyname < 0;
  } else
    return compareYearOfBirth < 0;
}

The std::tie option by NathanOliver is significantly less error-prone than the above (although you can still easily mess up any copy-pasted stuff - I've done it before).
In C++20 there will be an even simpler solution (see cppreference):
class Person {
  // ...
public:
  auto operator<=>(const Person &) const = default;
}

This will basically provide all comparisons exactly as if you manually implemented them via comparisons on all members std::tied together.


text:
Q: does the Linux distribution matters for noarch packages? I need httplib2 v0.7 RPM for RHEL 5.7, but can't find one. So,

*

*do you by chance know where can I get some?

*I see such RPMs but for other distros (e.g. Mandrake). Since it is python-only lib (noarch) does the distro matters? Can I get any and use it?

Python 2.6

A: Yes, it does matter.
noarch marks a package as usable for every CPU architecture, usually when there are no compiled binaries in it.
But the distribution matters in general. A noarch package from another distro may or may not work. It depends e.g. on package names, directories where to put the stuff, ...
A package only works safely if the distribution and the distribution version matches.


text:
Q: cisco 2500 series controller keeps dropping devices I have a cisco 2504 controller with 3502 ap's. This is all configured and works a lot faster than our old system already except these seem to drop clients every 20-30mins or so for a few seconds.
What could cause this issue. I have removed all other access points and using 1 on its own so i know it can't be switching between ap's. What else could cause this and has anyone else had this issue?
Thanks

A: I found the problem. By default it was adding a timeout to each ssid of 1800 seconds. Just uncheck that and works fine.
Thanks everyone


text:
Q: Text replacement in gulp test I am trying to create a gulp build system so that I can test both src file and the minimized file. Say I have foo.src.js and foo.min.js, my test file is test.js, which contains something like
var Foo = require(../FOO);
...

Then in my gulp file I have
var replace = require('gulp-replace');
var mocha = require('gulp-mocha');

gulp.task('test-prepare', function() {
  return gulp.src('test.js')
    .pipe(replace(/FOO/g, 'foo'))
    .pipe(gulp.dest('build'));
});

gulp.task('test-build-prepare', function() {
  return gulp.src('test.js')
    .pipe(replace(/FOO/g, 'foo.min'))
    .pipe(gulp.dest('build'));
});

gulp.task('test', ['test-prepare'], function() {
  return gulp.src('build/test.js').pipe(mocha());
});

gulp.task('test-build', ['test-build-prepare'], function() {
  return gulp.src('build/test.js').pipe(mocha());
});

After I run gulp test I can see that build folder and the test.js file has the FOO been replaced with foo correctly. However the test is not running correctly as there is zero test cases been run. It shows:
[12:04:44] Using gulpfile ~/Projects/genEnum/gulpfile.js
[12:04:44] Starting 'test-prepare'...
[12:04:44] Finished 'test-prepare' after 23 ms
[12:04:44] Starting 'test'...

  0 passing (0ms)

[12:04:44] Finished 'test' after 5.82 ms

Anyone know where is the problem?

A: Found the problem. In my code it was not 'build/test.js', instead it was BUILD_PATH+TEST_FILE. While BUILD_PATH is ./build and TEST_FILE is test.js, and there miss one / after they concatenated.
Changing it to BUILD_PATH + '/' + TEST_FILE fixed the issue and now I can run the test against both src file and minimized file.
BTW the gulpfile.js I referred to in this question could be found at https://github.com/greenlaw110/enumjs/blob/master/gulpfile.js


text:
Q: Batch program not running correctly in Windows 7 I am currently trying to figure out how to get a batch file to run correctly in Windows 7.  I have looked on the Internet and have not had much success in finding any useful information on the issue I am encountering.
BATCH FILE – The batch file is to open a window to allow students to test on a TDSM server created by ETS eCBT – The test is a CLEP Exam.  The batch file is to open the workstation for students to use and it looks like it loads but the Welcome/Login Screen never appears as it should.
WSK_LOAD.BAT
@echo off
rem--------------------------------------------------------------------
rem  !!! DO NOT REMOVE OR MODIFY THIS FILE   !!!
rem  !!! THIS FILE IS USED BY THE eCBT SYSTEM !!!
rem--------------------------------------------------------------------
SET ECBT_DEFAULT_SERVER_NAME=WR-TESTING1
SET ECBT_BATCH_HOME=C:\ETSBATCH
SET ECBT_HOME=\\WR-TESTING1\tdms
set ECBT_LOGFILE=%ECBT_BATCH_HOME%\wsk.log
SET ECBT_CLIENT_VERSION=4.0
rem----------------------------------------------------------------------
if exist %ECBT_HOME%\client\bin\wks.bat goto avail
echo Cannot access %ECBT_HOME%!
echo Attempting to open the share …
echo If you see the share window, please close it to proceed …
rem------------------------------------------------------------------------
:avail
%ECBT_HOME%\client\bin\wks.bat

I have tried everything I can think of:  Run as Administrator, Moved files to run from the HD, made sure all files and folders associated with the program were shared with users and computers, had Windows 7 run compatibility which says it does not contain an .exe file to run, and re-wrote the file.
I know it is connecting to the TDMS server as I can see it on the server.  The only thing it does not do is bring up the window which is necessary to login to the testing server.  The window opens like it should but does not produce the login boxes.
Any and all help is appreciated,
Jennifer

A: I doubt this helps you at this point, but after contacting ETS, I found that the client side workstation script is not compatible with Windows 7 64-bit. Although it does work with Windows 7 32-bit.

A: Well my first recommendation is to try debugging your "WKS_LOAD.BAT" script to check for errors or mistakes that you may have over-looked.

A: Make sure your server is started.
If you are on the server it may not ever find the server (itself) automatically. You should find it automatically on a client install, but will have to specify it on the server manually. Luckily the default settings work when connecting from the host server.
I contacted their support line and received worthless, uninformed advice that led nowhere.
If you do not get the prompt to specify a server, something else is wrong. This system relies heavily on Java. That batch script calls another batch script which checks for updates, then loads a jar executable into the JVM.


text:
Q: Full postback from UpdatePanel only if true I am trying to do a login system whereby if the user keys in a default password, it will prompt for a update of password.
The controls are all in an UpdatePanel, and i am able to force full postback from the control within the UpdatePanel by using for example at onLoad:
ScriptManager.GetCurrent(Me).RegisterPostBackControl(btnClose)

However, i have another button which is btnLogin, and this will do the check if the password keyed in is the default. If it is not, then i will do a full postback. Below is my designer code:

Sign in with your username and password

                                <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
                                    <ContentTemplate>
                                    <asp:TextBox ID="txtUsername" runat="server" class="form-control" placeholder="Username"/>

                                    <asp:TextBox ID="txtPassword" runat="server" class="form-control" placeholder="Password"  textmode="Password" />

                                    <asp:TextBox ID="txtNewPassword" runat="server" class="form-control" placeholder="Update Password"  textmode="Password" Visible="false"/>

                                        <asp:Button ID="btnLogin" runat="server" class="btn btn-primary" Text="Sign in" onclick="btnLogin_Click" />

                                        <asp:Button ID="btnClose" runat="server" Text="Close" class="btn btn-primary"  Visible ="true" OnClick="btnClose_Click"/>
                                    </ContentTemplate>
                                </asp:UpdatePanel>

And this is my code behind:
 If dbPwd = "pwd123" Then

                    txtNewPassword.Visible = True
                    txtUsername.Text = username
                    txtPassword.Text = pwd

                Else

                    Dim signIn As Control = FindControl("signIn")
                    Dim logOut As Control = FindControl("logOut")

                    signIn.Visible = False
                    logOut.Visible = True

                    Session("loginDetails") = dbUsername & "," & dbGroup & "," & dbModify & "," & dbRead & "," & dbWrite
                    'MsgBox(Session("loginDetails"))
                    txtPassword.Text = ""
                    txtUsername.Text = ""
                    dbUsername = ""
                    dbPwd = ""

                    btnLogin.Visible = True

                End If

The question is how to conditionally register it as a control for full postback?


text:
Q: transparent background-image with a background-color I'm having a problem with the background property. It should look like this:
http://s14.directupload.net/file/d/3425/zbutcmqw_jpg.htm
The triangle has to be transparent and I need the possibility to set the position of this triangle.
When I use background: url('images/nav.png') no-repeat #1d1d1d; the triangle isn't transparent anymore.
Is there any solution?

A: You need to set up a width and a height to your picture to review it.
CSS
 .class,#id{
    background: url('images/nav.png') no-repeat #1d1d1d;
    height:100px;
    width:100px;
    position:absolute; /* need it to set up the z-index and display your image above the nav menu */
    z-index:100;
    opacity:0.4; /* set up opacity */
    filter:alpha(opacity=40); /* ie */
    }


text:
Q: Multiple Developers for TestFlight We are two developers each with an Individual apple developer membership. One of us (developer A) set up a test flight and was able to distribute the app. Then, A added developer B to developer A's team through App Store Connect under Users and Access. We added developer B as an App Manager.
Now, both developer A and B can build the app with the same bundle identifier. However, when developer B tries to upload to TestFlight through Product > Archive > Distribute App, the following error occurs

ERROR ITMS-90159: "Invalid provisioning profile. This app contains an embedded provisioning profile that is not associated with your account. Please use a provisioning profile associated with Team ID 6UM2GR5MVA."

I have no idea what this means.
Our goal is just to each be able to build and push to TestFlight.
What's the right way to set this up with two individual apple developer memberships?

A: You don't need two developer memberships to use same bundle identifier in two different Macs. Most probably your B developer is logged in using his Apple ID which is now associated with two developer programs and trying to use his own signing certificate with developer A's provisioning profile. That won't work.
Apps need following things to build on a device or to archive.

*

*A valid signing certificate

*A bundle identifier

*A valid provisioning profile which links step #1 and step #2

Your developer B can not use a signing certificate created with his account and link it with your developer A's provisioning profile.
These are the steps you should follow now: (Note these steps are only for distribution certificates required for archiving process. If your dev B wants to build on device, then you have to do these step for developer certificates too.)

*

*You will find a signing certificate with 6UM2GR5MVA id in dev A's keychain. Format should be "iPhone Distribution: Develper_Name_Here (6UM2GR5MVA)" Export that signing certificate and import it to developer B's keychain. (both public and private keys together).

*Send correct distribution provisioning profile to develper B. Or they can log into developer portal and download it from there. Then click it to open in Xcode.

*Now go to your Xcode project settings section and open 'Signing and Capabilities' section. And select correct team with 6UM2GR5MVA id. (You might have to untick 'automatically manage signing' checkbox). Under 'Signing(Release)' section, select correct provisioning profile.

*If those fields are not editable in step #3 you have to do this in 'build settings' section because sometimes Xcode gets confused when you use multiple accounts.

*When distributing select the correct Distribution Certificate and Profile which should now appear in the list.
You have to repeat these steps (#1 to #4) for Developer Signing Certificate as well to set correct settings in 'Signing(Debug)' section.


text:
Q: Including remote PHP file functions in local PHP file Gone through related posts and found turning allow_url_include will does the trick. However when I did this :
remote file file.php at http://www.courierscripts.com
$content = file_get_contents('http://www.courierscripts.com/folder/file.php');

on my functions.php, was not able to use the functions of file.php. I also  don't want to change my file.php to file.txt because everyone can see it.
Any other way?

A: If the file is on the same server, use absolute or relative path to it, not an url. Otherwise:
Short answer:
No, it's not possible.
Long answer:
Actually possible with conditions but I bet you won't like them.
It's obviously impossible if you don't have access to the target server (otherwise storing passwords in php config files like Wordpress does would be just one big security flaw).
First of all, file_get_contents returns a string. So you could eval it, but eval is very bad (you can search SO for the clues why).
OK, suppose you agree to eval what's coming from that server even after considering that someone might change the code and do whatever he wants on your machine. BUT you make an http request that is handles by the server (Apache, Nginx or whatever else).
The server knows that *.php files should not be handles as static files. For example, fastcgi. You can turn that off, for example, with RemoveHandler in Apache. But that would let everyone see the source code of files you expose this way.
So, after removing handlers and evaling the result, you could get the result. But be ready that someone you work with will punch you in the face for doing that ;)
UPD
For code sharing, use  Composer to create a package and use it as a dependency.


text:
Q: How to resize input size for Conv1DTranspose layer in Keras? I'm using Keras to build GAN based on Conv1DTranspose layers. I would like to implement a GAN model (especially for the generator). However, I couldn't make the right architecture. Could you help me for these points:
(1) The problem is the size of my input (noise) does not match as per Keras documentation. So, I couldn't build the network from the beginning.
(2) How to perform "reshape" from Conv1DTranspose layer output to Conv1D layer ?
Thank you,,
The generator architecture which I want to replicate:

This is my code:
# define generator model
def define_generator(latent_dim, n_outputs=1):
    model = Sequential()

    # reshape layer
    model.add(Dense(1 * 10 * 10, activation="relu", input_dim=(latent_dim)))
    model.add(Reshape((10, 10, 1)))

    # 1D Transposed Convolutional Layer
    model.add(Conv1DTranspose(filters=32, kernel_size=4, strides=1))
    model.add(BatchNormalization(momentum=0.8))
    model.add(LeakyReLU(alpha=0.1))

    model.add(Conv1DTranspose(filters=64, kernel_size=4, strides=1))
    model.add(BatchNormalization(momentum=0.8))
    model.add(LeakyReLU(alpha=0.1))

    model.add(Conv1DTranspose(filters=128, kernel_size=4, strides=1))
    model.add(BatchNormalization(momentum=0.8))
    model.add(LeakyReLU(alpha=0.1))

    # 1D Convolutional Layer
    model.add(Conv1D(filters=128, kernel_size=4, strides=1))
    model.add(BatchNormalization(momentum=0.8))
    model.add(LeakyReLU(alpha=0.1))

    model.add(Conv1D(filters=64, kernel_size=4, strides=1))
    model.add(BatchNormalization(momentum=0.8))
    model.add(LeakyReLU(alpha=0.1))

    model.add(Conv1D(filters=32, kernel_size=4, strides=1))
    model.add(BatchNormalization(momentum=0.8))
    model.add(LeakyReLU(alpha=0.1))

    # output layer
    model.add(Dense(n_outputs, activation='sigmoid'))

    print('Generator')
    model.summary()

    return model

The error messages:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-70-a8709ad0f7a6> in <module>()
      1 latent_dim = 100
      2
----> 3 generator = define_generator(latent_dim)

6 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/convolutional.py in build(self, input_shape)
    944     if len(input_shape) != 3:
    945       raise ValueError('Inputs should have rank 3. Received input shape: ' +
--> 946                        str(input_shape))
    947     channel_axis = self._get_channel_axis()
    948     if input_shape.dims[channel_axis].value is None:

ValueError: Inputs should have rank 3. Received input shape: (None, 10, 10, 1)

A: the Conv1DTranspose return a tensor with shape (None, 10, 10, 1), so before the 1D Convolutional layer try to add one Reshape layer to squeeze it back to 3D tensor with the appropriate shape


text:
Q: Create one element Set the same way (if applicable) as create single element list To create a single item list we can use Collections.singletonList(s), Are there any way to create a single item Set

A: Yes, there is. Just use Collections.singleton(s).
As per Javadoc:

Returns an immutable set containing only the specified object. The returned set is serializable.

(I know the name isn't very suggestive)


text:
Q: Best Practice: Separate Tables for Separate Info on Same User I am designing a database for student information. I wish to implement the best practices regarding separate tables and use of Primary and Foreign Keys.
Let's say I have the following tables (High Level):

*

*Users

*Student Information

*Student Transcripts

*Student Records

There will be different users with different levels. Also, the information in Student Info/Transcripts/Records will all have a Foreign Key with the ID that's in Users.
SO, it would be dumb to just clump all the tables into one big table, wouldn't it? Is it a good idea to keep all this information separate and just use Primary/Foreign keys to link things together, as well as maybe Joins? I just personally think a big table would be quite messy and through this way, it allows one to keep similar data together with its own kind.
Thanks for all input on the matter!


text:
Q: String chunking algorithm with natural language context I have a arbitrarily large string of text from the user that needs to be split into 10k chunks (potentially adjustable value) and sent off to another system for processing.

*

*Chunks cannot be longer than 10k (or other arbitrary value)

*Text should be broken with natural language context in mind

*

*split on punctuation when possible

*split on spaces if no punction exists

*break a word as a last resort

I'm trying not to re-invent the wheel with this, any suggestions before I roll this from scratch?
Using C#.

A: This may not handle every case as you need, but it should get you on your way.
    public IList<string> ChunkifyText(string bigString, int maxSize, char[] punctuation)
    {
        List<string> results = new List<string>();

        string chunk;
        int startIndex = 0;

        while (startIndex < bigString.Length)
        {
            if (startIndex + maxSize + 1 > bigString.Length)
                chunk = bigString.Substring(startIndex);
            else
                chunk = bigString.Substring(startIndex, maxSize);

            int endIndex = chunk.LastIndexOfAny(punctuation);

            if (endIndex < 0)
                endIndex = chunk.LastIndexOf(" ");

            if (endIndex < 0)
                endIndex = Math.Min(maxSize - 1, chunk.Length - 1);

            results.Add(chunk.Substring(0, endIndex + 1));

            startIndex += endIndex + 1;
        }

        return results;
    }

A: I'm sure this will probably end up being more difficult than you're expecting (most natural language things), but check out Sharp Natural Language Parser.
I'm currently using SharpNLP, it works pretty well, but there's always 'gotcha's'.
Let me kow if this isn't what you're looking for.
Mark


text:
Q: How to make a properly looking 3D 2-sided rotating cube-like effect? I currently succeeded in making something close to what I want - click here, but it still looks so crappy and unrealistic. I want to make it like a navbar where you see the logo and onhover it 3D rotates and the links show up from the bottom. It looks so bad, I don't know what's wrong. Here's my code:

.navbar {
  position: fixed;
  width: 500px;
  height: 80px;
  background: red;
  text-align: center;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
}

.navbar .logo_side {
  position: absolute;
  width: 100%;
  height: 100%;
  background: blue;
  box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.3);
  transform-origin: top;
  transition: 1s ease-in;
}

.navbar .logo_side img {
  height: 100%;
}

.navbar:hover > .logo_side {
  transform: rotateX(90deg);
  transition: 1s ease-out;
}

.navbar .links_side {
  position: absolute;
  width: 100%;
  height: 100%;
  background: orange;
  box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.3);
  transform: rotateX(90deg);
  transform-origin: bottom;
  transition: 1s ease-out;
}

.navbar .links_side a {

}

.navbar:hover > .links_side {
  transform: rotateX(0deg);
  transition: 1s ease-in;
}

MY LOGO

  Home
  About
  Contact Us

For example, it currently looks like in Fig 1 and I was hoping to get it something like in Fig 2:

A: I found THIS on codpen and modified it a bit take a look at it and see if you can apply it on your code

var cube = document.querySelector('.cube');
var currentClass = '';
var side = "front";

function changeSide() {
  side = side == "front" ? "top" : "front";
  var showClass = 'show-' + side;
  if (currentClass) {
    cube.classList.remove(currentClass);
  }
  cube.classList.add(showClass);
  currentClass = showClass;
}
* {
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
}

.scene {
  width: 200px;
  height: 200px;
  border: 1px solid #CCC;
  margin: 80px;
  perspective: 400px;
}

.cube {
  width: 200px;
  height: 200px;
  position: relative;
  transform-style: preserve-3d;
  transform: translateZ(-100px);
  transition: transform 1s;
}

.cube.show-front {
  transform: translateZ(-100px) rotateY( 0deg);
}

.cube.show-top {
  transform: translateZ(-100px) rotateX( -90deg);
}

.cube__face {
  position: absolute;
  width: 200px;
  height: 200px;
  border: 2px solid black;
  line-height: 200px;
  font-size: 40px;
  font-weight: bold;
  color: white;
  text-align: center;
}

.cube__face--front {
  background-color: red;
}

.cube__face--top {
  background-color: blue;
}

.cube__face--front {
  transform: rotateY( 0deg) translateZ(100px);
}

.cube__face--top {
  transform: rotateX( 90deg) translateZ(100px);
}

label {
  margin-right: 10px;
}

front

top


text:
Q: Cannot login into openfire account via XMPP I have a very simple Java application that sends messages to an openfire server using a custom account called "thesis.dimfccs.sensors", who is seding a message to another custom account called "thesis.dimfccs".
I am using openfire 3.9.1 and my Java application is able to connect to the server, but it is unable to login into it. When I try to login, I get the following error:
Initializing connection to server localhost, port 5222, service gmail.com
Connected: true
Logging in: thesis.dimfccs.sensors, thesis.dimfccs.sensors.pwd
Exception in thread "main" No response from the server.:
    at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:73)
    at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:357)
    at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:243)
    at org.jivesoftware.smack.Connection.login(Connection.java:366)
    at javacodegeeks.XmppManager.performLogin(XmppManager.java:76)
    at javacodegeeks.XmppLocalTest.main(XmppLocalTest.java:44)

I know that the password and name for the test account are correct because I can enter the Spark IM client using them.
However, what really blows my mind, is that if I do the exact same thing using the "admin" account, everything works!
I have double checked the thesis.dimfccs.sensors password and gave it admin access, but it is still not enough.
Here is the code:
Main.java:
public class XmppLocalTest {

    //Total number of messages sent during one minute.
    public static final int MESSAGES_NUMBER = 120;

    //Each message will have a random number between 0 and MAX_RANDOM.
    public static final int MAX_RANDOM = 100;

    private static final String SENDER_USERNAME = "thesis.dimfccs.sensors";
    private static final String SENDER_PASSWORD = "thesis.dimfccs.sensors.pwd";

    public static void main(String[] args) throws Exception {

        String username = SENDER_USERNAME;
        String password = SENDER_PASSWORD;
        XmppManager xmppManager = new XmppManager("localhost", 5222,
                "gmail.com");

        xmppManager.init();

        xmppManager.performLogin(username, password);
        System.out.println("Login performed with success, setting status.");
        xmppManager.setStatus(true, "Let the pain begin!");

        System.out.println("Setting up receivers");
        xmppManager.createEntry("thesis.dimfccs", "thesis.dimfccs");

        //go message!
        xmppManager.sendMessage("Hello world!", "thesis.dimfccs@gmail.com");

        xmppManager.destroy();
    }
}

XmppManager.java:
package javacodegeeks;

/**
 * Main class with all the logic of the connection. Followed from the tutorials:
 * http://www.javacodegeeks.com/2010/09/xmpp-im-with-smack-for-java.html
 * */

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;

public class XmppManager {

    private static final int packetReplyTimeout = 500; // millis

    private String server;
    private int port;
    private String service;

    private ConnectionConfiguration config;
    private XMPPConnection connection;

    private ChatManager chatManager;
    private MessageListener messageListener;

    public XmppManager(String aServer, int aPort, String aService) {
        server = aServer;
        port = aPort;
        service = aService;
    }

    public XmppManager(String server, int port) {
        this(server, port, null);
    }

    public void init() throws XMPPException {

        System.out.println(String.format("Initializing connection to server " +  server + ", port " + port
                + ", service " + service));

        SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);

        if(service != null)
            config = new ConnectionConfiguration(server, port, service);
        else
            config = new ConnectionConfiguration(server, port);

//      config.setSASLAuthenticationEnabled(false);
//      config.setSecurityMode(SecurityMode.disabled);
//      SASLAuthentication.supportSASLMechanism("PLAIN", 0);
        config.setSASLAuthenticationEnabled(true);
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);

        connection = new XMPPConnection(config);
        connection.connect();

        System.out.println("Connected: " + connection.isConnected());

        chatManager = connection.getChatManager();
        messageListener = new MyMessageListener();

    }

    public void performLogin(String username, String password) throws XMPPException {

        if (connection!=null && connection.isConnected()) {
            System.out.println("Logging in: " + username + ", " + password);
            connection.login(username, password);
        }
    }

    public void setStatus(boolean available, String status) {

        Presence.Type type = available? Type.available: Type.unavailable;
        Presence presence = new Presence(type);

        presence.setStatus(status);
        connection.sendPacket(presence);

    }

    public void destroy() {
        if (connection!=null && connection.isConnected()) {
            connection.disconnect();
        }
    }

    public void sendMessage(String message, String buddyJID) throws XMPPException {
        System.out.println(String.format("Sending message " + message + " to user " + buddyJID));
        Chat chat = chatManager.createChat(buddyJID, messageListener);
        chat.sendMessage(message);
    }

    public void createEntry(String user, String name) throws Exception {
        System.out.println(String.format("Creating entry for buddy " + user + " with name " + name));
        Roster roster = connection.getRoster();
        roster.createEntry(user, name, null);
    }

    private class MyMessageListener implements MessageListener {

        @Override
        public void processMessage(Chat chat, Message message) {
            String from = message.getFrom();
            String body = message.getBody();
            System.out.println(String.format("Received message " + body + " from " + from));
        }

    }

}

What am I doing wrong? How can I fix this?

NOTE: If you believe this question is poor, please leave a comment and suggest an edit instead of down-voting it. This way I can actually improve the question and everyone gets happy!

A: The problem was that my server seemed to be inconsistent somehow. After deleting and re.creating the users, the problem got fixed !


text:
Q: Weighted sum of arrangements I was pondering this problem (not a homework):

What are the coefficients {a_i} that cancel all powers except the biggest one ?
The values for n=1,2,3 are easy to find, Wolfram-alpha helped find the next ones.
Is there a formula to generate them?

A: We have that
$$\sum_{k=1}^n {n\brace k} x^{\underline{k}} =
\sum_{k=1}^n {n\brace k} \frac{x!}{(x-k)!} = x^n.$$
with the Stirling numbers of the second kind.
To see this combinatorially write it as
$$\sum_{k=1}^n {x\choose k} {n\brace k} k! = x^n.$$
Let $x$ be the number of elements of some set. Then $x^n$ counts the
number of $n$-tuples with components chosen from this set. This is the
RHS. The LHS  classifies the tuples according to the number of different
values that  appear, say there are $k$ of these. Then we must first
choose these values which  gives ${x\choose k}.$ Next we partition the
$n$ slots into $k$  non-empty disjoint subsets where the slots in a
subset all hold the same value  from the $k$ that we have chosen. We can
assign the latter to the subsets  in $k!$ different ways. This gives the
factor ${n\brace k}\times k!$ and  hence the LHS. (We have shown that it
holds  for positive integers $x.$ With both sides being polynomials in
$x$ it  holds for all $x$ where we define ${x\choose k} =
x^{\underline{k}}/k!.$)


text:
Q: Making an app for a single iPad I'm looking for some clarification on developing for a single iPad. I have an app in the app store, however I want to make my own app for personal use that won't be submitted to the app store.
Is it possible for me to develop the app and get a certificate to "test" the app on my iPad, and just keep it on? I don't want to have to pay $299 for an enterprise account to publish private apps for a single iPad to use the app!
I've had a read about and I'm probably more confused now than I was before!
Any help appreciated.
Thanks,
Gary

A: If you enter the iOS Developer Program (99$ a year), you will be able to do what you mention: you will be able to generate a certificate and a provisioning profile and install the app on your device (actually, up to 100 devices).
The only thing is that you will need to create a new certificate/provisioning profile and rebuild/reinstall your app when the certificate expries.

A: No matter how you do it, you will always have to sign your app to be able to run it on a device.
All Provisioning Profiles expire, except the ones for the App Store (which you can't use without publishing your App in the App Store). So paying $299 for an Enterprise Account wouldn't even help you in this case.
However, if you want to run the App only on this single device, you could consider jailbreaking it. This would allow unsigned apps to run.


text:
Q: Prove a function could be written as a power series Suppose $S(z)=\sum a_n z_n $ has radius of convergence $>0 $, $a_0\not= 0$, prove that the function:
$$f(z)=\dfrac 1 {S(z)}$$ can be developed into power series at 0.
I don't have an idea of the condition, any help?
Thanks~

A: You can do this by long division, or by multiplying both sides by $S(z)$ and discovering the coefficients required.
For example, if $$\sum x_n z^n \sum a_n z^n = 1$$
then we must have:

*

*$x_0 = \frac{1}{a_0}$ by considering the $z^0$ coefficient;

*$x_1 a_0 + x_0 a_1 = 0$ by considering the $z^1$ coefficient, so we can extract $x_1$ without any further division by anything except $a_0$;

*$x_2 a_0 + x_1 a_1 + x_0 a_2 = 0$ by considering the $z^2$ coefficient, so we can extract $x_2$ without any further division by anything except $a_0$;

*repeat inductively.

This constructs a power series; it trivially converges at $0$ because the first coefficient is $\frac{1}{a_0}$. This power series is $\frac{1}{S(z)}$ by just multiplying out the product of the two and obtaining $1$.


text:
Q: phonegap/web database errorcodes Explanation? I want to show correct errors to the user if a transaction with a web database (I´m using Phonegap) fails. In the Error-Callback I ask for the error.code value to determine what went wrong.
The Documentations says this about it. However, I have a case where the transaction fails because a unique constraint is violated by inserting a value that already exists.
function saveErrorCB(err){
    console.log(err.code + " " + err.message + " ");
}

err.code shows:

1

err.message shows here:

could not execute statement (19 constraint failed)

My point is, I want to know about other codes like "1". The Phonegap documentation doesnt mention it.

A: I think the Phonegap documentation does (eventually) link to a W3C page which then says...

*

*UNKNOWN_ERR = 0

*DATABASE_ERR = 1

*VERSION_ERR = 2

*TOO_LARGE_ERR = 3

*QUOTA_ERR = 4

*SYNTAX_ERR = 5

*CONSTRAINT_ERR = 6

*TIMEOUT_ERR = 7

It seems err.message is more useful - thanks for telling me about it!