text:
Q: How to loop a data in php I want to loop my data Like this
Like this

Not like this

My Controller:
function bills($patient_id){
    $data['payments'] = $this->model_patient->getpayments($patient_id);
    $this->load->view('includes/header');
    $this->load->view('billing', $data);
    $this->load->view('includes/footer');
}

My Model: // joining my 3 tables, i want to display the procedures made by this patients and all the payments made.
function getpayments($patient_id){
    $this->db->select('*');
    $this->db->from('treatmentrecord as tr');
    $this->db->join('patientprofile as pr','pr.patient_id = tr.patient_id');
    $this->db->join('billedrecord as br','br.treatment_id = tr.treatment_id');
    $this->db->where('tr.patient_id', $patient_id);

    $query = $this->db->get();

    return $query->result();
}

My View:

        Procedures
        Payments

<?php foreach ($payments as $payments): ?>

        <?php echo $payments->procedures; ?>
        <?php echo $payments->bill_paid; ?>

<?php endforeach ?>

I hope someone can help me with this.
OP:
    Array(
    [0] => stdClass Object
        (
            [treatment_id] => 1
            [procedures] => ProcedureName1
            [patient_id] => 1
            [bill_id] => 3
            [bill_paid] => 500
        )
[1] => stdClass Object
    (
        [treatment_id] => 5
        [procedures] => ProcedureName3
        [patient_id] => 1
        [bill_id] => 4
        [bill_paid] => 2323
    )

[2] => stdClass Object
    (
        [treatment_id] => 1
        [procedures] => ProcedureName1
        [patient_id] => 1
        [bill_id] => 5
        [bill_paid] => 2555
    )

[3] => stdClass Object
    (
        [treatment_id] => 6
        [procedures] => ProcedureName2
        [patient_id] => 1
        [bill_id] => 6
        [bill_paid] => 2555
    )

[4] => stdClass Object
    (
        [treatment_id] => 1
        [procedures] => ProcedureName1
        [patient_id] => 1
        [bill_id] => 7
        [bill_paid] => 23232
    )

[5] => stdClass Object
    (
        [treatment_id] => 5
        [procedures] => ProcedureName3
        [patient_id] => 1
        [bill_id] => 8
        [bill_paid] => 2323
    )

)

A: *

*First sort the $payments with respect to procedures like below:

Snippet:
usort($payments,function($a,$b){
    return strcmp($a->procedures,$b->procedures);
});

*

*Now, you can take help of the index of the element while looping. So if it's first index or name doesn't match with previous index, just print it, else print an empty string.

Snippet:

        Procedures
        Payments

<?php foreach ($payments as $index => $payment): ?>

        <?= $index === 0 || $payment->procedures != $payments[$index - 1]->procedures  ? $payment->procedures : ''; ?>
        <?= $payment->bill_paid; ?>

<?php endforeach; ?>

A: controller
function bills($patient_id){
    $payments = $this->model_patient->getpayments($patient_id);

    $result = array();
        foreach ($payments as $element) {
            $result[$element->treatment_id][] = $element;
        }

    $data['payments'] = $result;
    $this->load->view('includes/header');
    $this->load->view('billing', $data);
    $this->load->view('includes/footer');
}

view

                Procedures
                Payments

            <?php
            foreach ($payments as $index => $payment) {
                foreach ($payment as $key => $pay) {
                    ?>

                            <?php
                            if ($key == 0) {
                                echo $pay->procedures;
                            }
                            ?>

                        <?php echo $pay->bill_paid; ?>

                    <?php
                }
            }
            ?>


text:
Q: Как сопоставить пользователя и его ответ в процессе диалога пользователя и telebot? Использую код в котором в переменные 'item' и 'phone_number' сохраняется необходимая информация от пользователя бота,но проблема в том что если ботом одновременно пользуются более одного человека, то информация в переменную падает от последнего пользователя который написал боту. Поэтому нужно сопоставлять сообщение и айди юзера который написал. Предполагаю что это можно сделать через словарь, но как именно написать код не понимаю.
import telebot
from telebot import types

bot = telebot.TeleBot('token')
item = ''
phone_number = ''

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("Фрукты")
    btn2 = types.KeyboardButton("Овощи")
    markup.add(btn1, btn2)
    bot.send_message(message.chat.id, text="Привет, {0.first_name}! Что бы вы хотел купить?".format(message.from_user), reply_markup=markup)

@bot.message_handler(content_types=['text'])
def func(message):
    global item
    chat_id=message.chat.id
    if(message.text == "Фрукты"):
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton("Яблоко")
        btn2 = types.KeyboardButton("Бананы")
        markup.add(btn1, btn2)
        bot.send_message(message.chat.id,text='А конкретнее?', reply_markup=markup)

    elif(message.text == "Бананы"):
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton("Микробанан 220 р/кг")
        btn2 = types.KeyboardButton("Банан 150 р/кг")
        markup.add(btn1, btn2)
        bot.send_message(message.chat.id, text="Выбирайте", reply_markup=markup)
        bot.send_photo(chat_id, caption="Микробанан 220 р/кг",photo=open('media/minibanana.jpg', 'rb'))
        bot.send_photo(chat_id, caption="Банан 150 р/кг",photo=open('media/banana.jpg', 'rb'))

    elif(message.text == "Банан 150 р/кг"):
        item = message.text
        bot.send_message(message.chat.id, text=f"Вы выбрали {item}. Чтобы оформить заказ введите свой номер телефона и наш менеджер свяжется с вами")
        bot.register_next_step_handler(message, get_number)

def get_number(message):
    global item
    global phone_number
    phone_number = message.text
    keyboard = types.InlineKeyboardMarkup();
    key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes')
    keyboard.add(key_yes)
    key_no= types.InlineKeyboardButton(text='Нет', callback_data='no')
    keyboard.add(key_no)
    question = 'Вы хотите купить '+item+' , ваш номер телефона '+phone_number+'?'
    bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)

@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    global item
    global phone_number
    chat_id = (admin_id)
    if call.data == "yes":
        bot.send_message(call.message.chat.id, 'Ожидайте звонка, наш менеджер свяжется с вами')
        bot.send_message(chat_id, f'вот заказ {item}, номер телефона {phone_number}')

bot.polling(interval=0)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not able to toggle  using jQuery I am trying to create a button that will toggle a div which contains certain replies to comments. I want to be able to hide and show the replies to comments on clicking the button. And the "show all replies" button will only be shown if there are more than one replies to a comment. But whenever I click the button, nothing happens. The console also doesn't show any errors. Here is the code:
<?php
if($numberOfReplies>=1){
?>
    <button id="repliestogglebutton">show all replies</button>

<?php
}
?>

  (all replies to a comment are displayed here)

jQuery:
$(document).ready(function(){
    jQuery("#repliestogglebutton").click(function() {
        jQuery("#allrepliesdiv").toggle();
    });
});

Thanks in advance!

A: Your given code looks fine to me. There might be any thing else causing the problem.
PFA. A working code you may test in a new file. ("slow" is the applied animation on toggle. )

<button id="repliestogglebutton">show all replies</button>

Comment 1

Comment 2

Comment 3

Comment 4

A: This should do the trick.

$(document).ready(function(){
 $(".button").click(function(){
   $(".answer-container").toggleClass("visible");
  });
});
.button{
  width:100px;
  height:20px;
  line-height:20px;
  text-align:center;
  border:1px solid #CCCCCC;
  background-color:#FFFFFF;
  cursor:pointer;
}

.button:hover{
   background-color:#FFEEEE;
}

.visible{
  display:block !important;
}

.answer-container{
  display:none;
}

Show all

Extra Comments

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

I used a div for the button but you can use anything.

A: you can use any one method:
jQuery(document).ready(function(){
    jQuery("#repliestogglebutton").click(function() {
        jQuery("#allrepliesdiv").slideToggle();
    });
});

$(document).ready(function(){
    $("#repliestogglebutton").click(function() {
        $("#allrepliesdiv").slideToggle();
    });
});

//If jquery conflict then use this method
var $j = jQuery.noConflict();
 $j(document).ready(function(){
     $j("#repliestogglebutton").click(function() {
         $j("#allrepliesdiv").slideToggle();
    });
});


text:
Q: can I use a clustering model written in python in an iOS application? I wrote a code with python that uses clustering to detect colours in an image, is there any API's or techniques that I can use the code in my ios application that I want to publish?

A: If the algorithm uses a library such as OpenCV, you can keep using that (but from C++). Otherwise, you have to rewrite the algorithm in Swift, Objective-C, or C/C++.


text:
Q: I keep getting an empty task list APScheduler I am writing a website on a Flask, I use it to run uwsgi + nginx. It was necessary to write a timer to periodically execute tasks. For this I used uwsgidecorators. The task should check the status of the scheduler tasks. To get a list of tasks, I used get_jobs(). But the list I keep getting empty.
webapp/__init__.py:
# -*- coding: utf-8 -*-

from gevent import monkey

monkey.patch_all()
import grpc.experimental.gevent

grpc.experimental.gevent.init_gevent()

from flask import Flask, session, request
from config import DevelopConfig, MqttConfig, MailConfig, ProductionConfig
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_script import Manager
from flask_socketio import SocketIO
from flask_mqtt import Mqtt
from flask_login import LoginManager
from flask_babel import Babel
from flask_babel_js import BabelJS
from flask_babel import lazy_gettext as _l
from apscheduler.schedulers.gevent import GeventScheduler

app = Flask(__name__)
app.config.from_object(ProductionConfig)
app.config.from_object(MqttConfig)
app.config.from_object(MailConfig)
db = SQLAlchemy(app)
migrate = Migrate(app, db, render_as_batch=True)
mail = Mail(app)
mqtt = Mqtt(app)
manager = Manager(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'auth'
login_manager.login_message = _l("Необходимо авторизоваться для доступа к закрытой странице")
login_manager.login_message_category = "error"
scheduler = GeventScheduler()
scheduler.start()
scheduler.add_job(publish_async, args=["Hello"], id="job", trigger='interval', seconds=2)

socketio = SocketIO(app, async_mode='gevent_uwsgi')  # Production Version
babel = Babel(app)
babeljs = BabelJS(app=app, view_path='/translations/')
import webapp.views

@babel.localeselector
def get_locale():
    # if the user has set up the language manually it will be stored in the session,
    # so we use the locale from the user settings
    try:
        language = session['language']
    except KeyError:
        language = None
    if language is not None:
        print(language)
        return language
    return request.accept_languages.best_match(app.config['LANGUAGES'].keys())

from webapp import models

def publish_async(message):
    print(message)

webapp/tasks.py:
from uwsgidecorators import timer

@timer(10, target='spooler')
def check_run_tasks(args):
    _list_schedulers = _scheduler_method.get_jobs()
    print(_list_schedulers)

wsgi.ini:
[uwsgi]
env = PYTHONIOENCODING=UTF-8
module = wsgi:app

master = true
# processes = 5
enable-threads = true
gevent = 1024
gevent-monkey-patch = true
buffer-size=32768
# lazy-apps = true

socket = /home/sammy/projectnew/projectnew.sock
socket-timeout = 30
chmod-socket = 664
thunder-lock = true
spooler = /home/sammy/projectnew/webapp/mytasks
import = webapp/tasks.py

vacuum = true

die-on-term = true

wsgi.py:
# -*- coding: utf-8 -*-

from webapp import app, socketio

if __name__ == '__main__':
    socketio.run(app, use_reloader=False)


text:
Q: Flask-SQLAlchemy - get distinct elements in QuerySelectField? So I am populating the queryselectfield from my database.
def place_query():

    return Place.query

class CreateItineraryForm(FlaskForm):

   opts = QuerySelectField('Select a city',query_factory=place_query,allow_blank=True,get_label='city',validators=[DataRequired()])

   days = IntegerField('Enter the number of days of stay',validators=[DataRequired()])

   submit = SubmitField("Generate Itinerary")

But since my database has multiple tuples with the same city. So in my select field the same city shows up multiple times. Is there a way I can select only distinct city names?
This is the schema if that's helpful -
class Place(db.Model):

__tablename__ = 'places'

id = db.Column(db.Integer,primary_key=True)

name = db.Column(db.String(64),nullable=False,index=True)

lat = db.Column(db.Float,nullable=False)

long = db.Column(db.Float,nullable=False)

city = db.Column(db.String(30),nullable=False,index=True)

user_reviews = db.relationship('Review',backref='subject',lazy=True)

def __init__(self,name,lat,long,city):

self.name = name

self.lat = lat

self.long = long

self.city = city

Thanks for the help!

A: So the trick was to not use QuerySelectField but to use SelectField.
This is the new code -
# this returns a tuple of the form (city_name,)
cities = db.session.query(Place.city).group_by(Place.city).order_by(Place.city).all()

city_list = []

# here we create a list from the tuple
def create_list(cities):
    for city in cities:
        city_list.append(city[0])

    return city_list

And the new select field looks like this -
opts = SelectField('Select a city',validators=[DataRequired()],choices=create_list(cities))


text:
Q: How to downgrade/rollback migration in Universal Windows Platform with Entity Framework using Package Manager Console? I modified a property in the model and it turned out it is not supported by the version of SQLite. This is the error. {"SQLite does not support this migration operation ('DropColumnOperation'). For more information, see http://go.microsoft.com/fwlink/?LinkId=723262."}
So I decided to roll it back by using the command Update-Database Migration "MyFirstMigration" but an error shows up on the console which states Update-Database shouldn't be used with Universal Windows Platform apps. Instead, call DbContext.Database.Migrate() at runtime.. This code recommended is already the code executed at the first run of the application that generates the first error above.
I am really going into circle here. Can someone suggest how I can rollback/downgrade MySecondMigration ti MyFirstMigration?

A:
Can someone suggest how I can rollback/downgrade MySecondMigration ti MyFirstMigration?

For the same DbContext, just execute Remove-Migration command on your package manager console, it will remove the last migration of this DbContext. It is your MySecondMigration which will be removed and only MyFirstMigration left.

Update-Database shouldn't be used with Universal Windows Platform apps. Instead, call DbContext.Database.Migrate() at runtime

For this, just as this error shown, DbContext.Database.Migrate() applies any pending migrations for the context to the database, include what Update-Database did (Updates the database to a specified migration). By testing on my side, for the same DbContext, every new migration is the updating based on the old one. DbContext.Database.Migrate() will apply all the migrations for updating. If you don't want the latest update, just remove it for roll back.


text:
Q: Using browsersync with gulp/nodemon I'm trying to get Browsersync (version 2.12.5) to work with gulp-nodemon/watching files. These are my gulp tasks. I can't seem to get any of my files to update/reload the browser.
  var $ = require('gulp-load-plugins')();
  var browserSync = require('browser-sync');
  var gulp = require('gulp');
  // load in gulp tasks etc......

  gulp.task('server', function() {
    return $.nodemon({
      script: 'server.js'
    });
  });

  gulp.task('browser-sync', ['server'], function() {
    browserSync.init({
      proxy: 'http://localhost:3000',
      port: 4000,
      open: false,
      notify: false,
      logConnections: false,
      reloadDelay: 1000
    });
  });

  gulp.task('watch', ['browser-sync'], function() {
    var scripts = 'public/static/scripts/**/*.js';
    var styles  = 'public/static/styles/**/*.styl';

    gulp.watch(scripts, ['scripts']);
    gulp.watch(styles,  ['styles']);
  });

  gulp.task('scripts', function() {
    return gulp.src('public/static/scripts/**/*.js')
      .pipe($.plumber())
      .pipe(gulp.dest('build/static/scripts'));
  });

  gulp.task('styles', function() {
    return gulp.src('public/static/styles/app.styl', {base: 'public'})
      .pipe($.stylus())
      .pipe(gulp.dest('build'))
  });

What is the recommended way to use Browsersync with nodemon?

A: Apparently, it seems Browser sync refreshes the browser, before nodemon starts the server.
Here's a log from my command line that shows nodemon and Browser sync, you'll see nodemon started late
[18:21:09] Finished 'jade' after 5.32 μs
[18:21:09] [nodemon] restarting due to changes...
>> node restart
[BS] Reloading Browsers...
[18:21:09] [nodemon] restarting due to changes...
>> node restart
[BS] Reloading Browsers...
[18:21:09] [nodemon] restarting due to changes...
>> node restart
[BS] Reloading Browsers...
[18:21:09] [nodemon] starting `node ./bin/www`
nodemon started

I had this same problem. Below was my solution
// Initialize browserSync
var browserSync   = require('browser-sync').create(),
    reload        = browserSync.reload;

// watcher
gulp.task('watch', function() {
  var scripts = 'public/static/scripts/**/*.js';
  var styles  = 'public/static/styles/**/*.styl';

  gulp.watch(scripts, ['scripts']);
  gulp.watch(styles,  ['styles']);
  gulp
    .watch('public')
    .on('change', reload); // the static files you want to watch and reload
});

// browser-sync
gulp.task('browser-sync', function() {
  browserSync.init({
    proxy: 'http://localhost:3000',// Don't use proxy
    port: 4000, // Desired PORT address.
    open: false,
    notify: false,
    logConnections: false,
    reloadDelay: 1000
    server: 'public', // Your compiled static directory
  });
})

gulp.task('default', ['scripts', 'styles', 'browser-sync', 'watch']) // This builds my script, styles and other static assets(img), starts browser-sync and watches for changes.


text:
Q: Pass Pandas df as table to SQL query I want to pass a local df as a table to inner join to an SQL server like so.
sql = """
select top 10000 *
from Table1 as t
inner join {} as a on t.id= a.id
""".format(pandas_df)

results = pd.read_sql_query(sql,conn)

This is obviously not the way to do it.
Any ideas?
Thanks!

A: Can use df.to_sql to load it to the df.

A: You need to convert your dataframe to a SQL table before reading it.
Use pd.pandas_df.to_sql(name_of_table, con)

A: I see two main options, depending on the data size of your id's. The simplest way would be to add the id to an IN clause in your SQL statement.
This approach is useful if you don't have write permission on the database, but you limited by the maximum batch size of SQL, which iirc is around 256Mb.
From your id series, you create a tuple of id's you're interested in, then cast the tuple to a string to concatenate with you sql statement.
sql = """
select top 10000 *
from Table1 as t
where t.id in """ + str(tuple(pandas.df['id'].values))

results = pd.read_sql_query(sql,conn)


text:
Q: UINavigationBar height and landscape mode If I use a UINavigationController to display my UINavigationBar, this bar is much slimmer in landscape mode than in portrait mode.
Everything fine so far, as I want this behavior, but I have one view which isn't handled by an UINavigationController and so I just dragged and dropped a UINavigationBar from Interface Builder into the view but this one has always the same size and I can't see a way to tell the UINavigationBar that it should resize.
Anyone knows how to achieve this?

A: You can resize the the navigation bar in the layoutSubviews method of your UIView, like so:
- (void)layoutSubviews {
    [super layoutSubviews];

    // Let navBar tell us what height it would prefer at the current orientation
    CGFloat navBarHeight = [navBar sizeThatFits:self.bounds.size].height;

    // Resize navBar
    navBar.frame = CGRectMake(0, 0, self.bounds.size.width, navBarHeight);
}


text:
Q: iOS: Archive fails I'm trying to distribute my iOS app. I'm trying to build the archive. The app runs fine, but when I try to archive it, it tells me it can't find ".h" files that it no problem finding for Build > Run.
They are ".h" files from different projects and libraries I have included in my project.
What's going on?

A: I've never come across this problem when archiving, but what I can offer to you is to take a look at the accepted answer in the following thread to see if it helps you resolve the issue you are experiencing:  Compile, Build or Archive problems with Xcode 4 (and dependencies)


text:
Q: Google Drive API 1.8.1 - Large file upload/download issue When I upload or download a large file and it lasts more than one hour, the upload/download interrupts with the following error message after exactly one hour:
Google.GoogleApiException: Google.Apis.Requests.RequestError
Invalid Credentials [401]
Errors [
    Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global]
]

There is no difference whether I run this with Web Authorization or Service Account Authorization.
I am not sure if it relates to the AuthToken expiration, because if I upload smaller files, then I am able to upload many files, and there is no interruption after an hours. For small files, everything runs smoothly and works for a very long time.
It looks like a similar issue is described here, but that question has not been answered.
My code is as following:
DriveService service;

// ....

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();

A: The problem is on the Google Drive endpoint and can't be fixed in your code.
Some guy filed an issue about this at Jan 13, 2013, and more than one year has passed, it seems no updates from Google about this, and others still meet this problem.

This is an issue with the backend and not with the API or with your code. As you deduced, if the upload goes too long the access_token expires and at that point the resumable upload can't be continued. There is work on progress to fix this issue right now, I will update this bug once the issue is fixed on the server side.

And here's another report about this issue.

A: This is the real issue where it's being tracked: Issue 5700 of GData API.
As of April 30, the answer from a Google engineer is:

Thanks for everyone's patience—I'm told that the underlying issue should now be fixed in production. As long as the OAuth 2 access token is valid at the start of the upload, the upload should complete successfully. An access token that expires in the middle of an upload will no longer cause an HTTP 401 response.
Please let us know if you're still seeing any issues. I'll leave this bug open until I can confirm from your feedback that it's resolved in your applications.

Apparently problems still exist, so if you're having problems with this please comment on Issue 5700.


text:
Q: Insert from DataTableAdapter is not reflected in the MS Access Database! I am using MS Access as my Database and using Dataset for retrieval and update for my WPF app.
The data is shown in a datagrid without issues.
However, when i try to insert data using the following code, the insert is completed successfully, but the new row cannot be seen in the Access file.
var add = new AddressBookDataSet();
            adc.Fill(add.Address);
            var v = add.Address.NewAddressRow();
            v.StreetAddress = textBoxStreetAddress.Text;
            v.AtPost = textBoxAtPost.Text;
            v.Taluka = textBoxTaluka.Text;
            v.District = textBoxDistrict.Text;
            v.State = textBoxState.Text;
            v.Pincode = textBoxPincode.Text;
            v.PhoneNumber1 = textBoxContact1.Text;
            v.PhoneNumber2 = textBoxContact2.Text;
            v.PhoneNumber3 = textBoxContact3.Text;
            v.PhoneNumber4 = textBoxContact4.Text;
            v.FaxNumber1 = textBoxFax1.Text;
            v.FaxNumber2 = textBoxFax2.Text;
            add.Address.AddAddressRow(v);
            add.Address.AcceptChanges();
            //adc.Insert(textBoxStreetAddress.Text, textBoxAtPost.Text, textBoxTaluka.Text, textBoxDistrict.Text, textBoxState.Text, textBoxPincode.Text, textBoxContact1.Text, textBoxContact2.Text, textBoxContact3.Text, textBoxContact4.Text, textBoxFax1.Text, textBoxFax2.Text);

What could be the issue here? I checked the .accdb is not marked read-only!
here, 1 field v.Id has been ommitted as the Id field is an autonumber!
also, before going with creating a new Row, I tried the adc.Insert (i.e. TableAdapter.Insert) yet it doesn't update in the DB!!

A: Although this was not a real issue, yet the solution:
The Access file which gets modified while debugging is present in the /Project/bin/debug folder, and not the location used for storage of the file!!
So the changes are visible in the copy of the accdb file in the Debug folder.


text:
Q: Laravel 4: Save data into database using ajax from a bootstrap modal I'm upgrading an old php project into a laravel 4 project. I have a function that adds company data using ajax from a bootstrap modal. But this code is not suitable for my current laravel project because i have used mysql_connect and mysql_select_db on this file. I have tested it and it still works but i want to use named routes like companies.store. I'm currently using restful routing for the project and it works perfectly. Here is my old code combined with the current laravel project, which actually works perfectly by the way.
create.blade.php
function addNewCompany(){
        var ajaxRequest;

        try{

            ajaxRequest = new XMLHttpRequest();
        } catch (e){

            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){

                    alert("Your browser doesn't support ajax!");
                    return false;
                }
            }
        }

        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                //txtMessage is used to show message returned from the ajaxRequest
                document.getElementById('txtMessage').value = ajaxRequest.responseText;
            }
        }

        var companyName = document.getElementById('txtCompanyName').value;

        ajaxRequest.open('POST', '{{ URL::asset("assets/query/saveCompany.php") }}');
        ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajaxRequest.send("companyName=" + companyName);

    }

saveCompany.php //which i placed inside the public/assets/query folder
<?php

$companyName = $_POST["companyName"];

  $con=mysql_connect("localhost","root","");
  mysql_select_db("dbname", $con);

  $sql = "INSERT INTO `companies` (`companyName`)
    VALUES ('$companyName')";

  $result = mysql_query($sql, $con);
  if($result)
  {
    echo "Company added successfully";
  }
  else
  {
    echo mysql_error();
  }
?>

So instead of sending the ajax request to a saveCompany.php file, how can i use resourceful routing by sending the request to say, company.store.

A: First of all you have to config database connection in app/config/database.php file.
Then put in routes.php:
Route::controller('companies', 'CompanyController');

models/Company.php
<?php
class Company extends Eloquent{
   protected $table = 'companies';
   protected $guarded = [''];
}

controllers/CompanyController.php
<?php
class CompanyController extends Controller {
   public function getAddCompany(){
      return View::make('create');
   }

   public function postCompany(){
      $company = new Company(Input::all());
      $company->save();
      return Redirect::action('CompanyController@getAddCompany');
   }
}

create.blade.php
 function addNewCompany(){
    var ajaxRequest;

    try{

        ajaxRequest = new XMLHttpRequest();
    } catch (e){

        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){

                alert("Your browser doesn't support ajax!");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            //txtMessage is used to show message returned from the ajaxRequest
            document.getElementById('txtMessage').value = ajaxRequest.responseText;
        }
    }

    var companyName = document.getElementById('txtCompanyName').value;

    ajaxRequest.open('POST', '{{ URL::action("CompanyController@postCompany") }}');
    ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajaxRequest.send("companyName=" + companyName);
}


text:
Q: How to convert vectors of varying lengths to one scalar? I am trying to calculate the emotion of paragraphs by measuring the emotion of its individual sentences. But this ends in vectors of varying length, as a paragraph might be as short as 1 sentence or as long as 30 sentences. how would you suggest converting these vectors to scalars?
The first option is taking average, but this biases the results: It turns out shorter paragraphs have a higher score and longer ones a score around the mean.
The second option is summing up the values, but this biases the results again, as longer paragraph will have bigger scores
The third option is using a method used in VADER, which is summing up and then normalizing, but I could not find a reliable resource that explains how the results are normalized. The only thing I found is the following formula from VADER code:
norm_score = score / math.sqrt((score * score) + alpha)

VADER sets alpha to 15, but how this number should be changed and based on what? Also , where does this normalization method come from?


text:
Q: Как вставить java-апплет на HTML-страницу? Я на страницу своего сайта попробовал вставить простейший java код. Вот, что у меня получилось!
Там пусто!
Я пробовал сделать это с помощью тега <applet>
Вот это код:
<applet code="
class OneMoreHello {
public static void main(String[] args) {
byte age=12;
char sex='м';
double weight=41.2;
int height=145;
System.out.println("Персональные данные пользователя:");
System.out.println("Возраст: "+age+" лет");
System.out.println("Пол(м/ж): "+sex+".");
System.out.println("Вес: "+weight+" кг");
System.out.println("Рост: "+height+" см");
}
}
" >

Как сделать правильно?
A: Вот здесь написано, что атрибут:

code: URL - Specifies the file name of a Java applet
codebase: URL- Specifies a relative base URL for applets specified in the code attribute

Т.е. для работы в качестве апплета, вам необходимо создать сам апплет, откомпилировать его в Java, получив файл your_app.class и к нему указать путь в code.


text:
Q: Owl carousel with bootstrap grid and card

$('.slider').owlCarousel({
  loop: true,
  margin: 10,
  nav: true,
  responsive: {
    0: {
      items: 3
    },
    600: {
      items: 3
    },
    1000: {
      items: 3
    }
  }
})
.main-content {
  background-image: url("https://d3ertfc829vzop.cloudfront.net/img/topo-map-50.png");
  background-color: #efefef;
}

.subheading-wrapper .subheading {
  font-size: 15px;
  color: #9AC133;
  text-transform: uppercase;
}

.heading-wrapper .heading {
  font-size: 2rem;
  color: #656565;
  font-weight: 500;
  text-transform: capitalize;
}

.card-img-overlay {
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-img-overlay .card-title a {
  color: white;
}

.card-img-overlay .card-title a:hover {
  text-decoration: none;
}

.floating-wrapper {
  transform: translateX(0px) translateY(-100px);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" rel="stylesheet">

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Recusandae asperiores pariatur dignissimos itaque necessitatibus nam minus laudantium porro inventore cum ullam nisi, veniam, fugit deleniti explicabo nemo accusamus. Alias distinctio quisquam
        aperiam, voluptatem aliquid neque nisi minus dicta, ut beatae vitae vero labore cumque ad. Adipisci eaque tenetur veniam eius, ipsam minima fugiat deleniti est facere quasi consequuntur, odit doloremque deserunt veritatis, corporis nobis reiciendis
        eligendi. Saepe, eos nesciunt, impedit pariatur necessitatibus natus id harum et beatae, voluptatum nam odio! Doloribus sit quia deserunt. Soluta earum velit laudantium iusto deserunt eum iste illum nemo tempora consequatur amet voluptatum ut,
        exercitationem reiciendis sequi. Ipsum, assumenda laudantium! Soluta pariatur dolorum, quia ut tempora exercitationem placeat? Ratione animi laboriosam suscipit adipisci natus quo! Similique optio quidem animi amet nostrum, fugiat, repudiandae
        non laudantium consectetur aliquam recusandae velit quis nemo doloribus voluptas sunt ab incidunt! Id dolore consectetur repudiandae quidem dicta maiores illo, error eius tenetur eveniet consequatur esse voluptate cum, quaerat possimus odit alias
        ab, sit minus mollitia? Fugit labore dolorem voluptatem maxime reprehenderit fugiat assumenda, vero dicta, qui corporis minus! Sit consequuntur rerum est reprehenderit voluptatum sequi cupiditate. Qui ipsam saepe at dolor eos. Sequi voluptatem
        laborum impedit quis sapiente neque. Soluta!

          Lorem ipsum dolor.

            Lorem ipsum dolor sit.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptas, magnam facere inventore culpa suscipit ducimus exercitationem doloremque mollitia quod voluptate ipsa dolorem enim sint eaque quos debitis sapiente ipsam architecto velit sed!

Card title

Card title

Card title

The above code snippet is from app's html template. Here I'm trying to implement owl carousel to card items.
The layout of the section should be like this as per the wireframe:

I have achieved the following layout but after adding the owl carousel classes owl-carousel owl-theme the layout is disfigured. Specially cards and couldn't figure-out the cause.
I've recreated the layout in the codepen here

A: The problem is that you have class col-4 inside the owl-item. You do not need that because the owl-item has already a calculated width ( so you have 3 items visible )
The col-4 class from bootstrap adds a width:33.33% to that element. So it will have 33.33% width of the owl-item but you need 100%.
You can either change it to col-12 ( if you need it to be flex ) or remove that class and everything will work as intended.

Card title

See codepen ( changed for the first two items )
https://codepen.io/MihaiTCode/pen/RwbyWVX


text:
Q: Symfony Doctrine: Use of subquery with "HAVING" clause without using EXISTS In a Symfony project I'm trying to make a query with a calculated field. Simplify a lot my SQL would be something like that:
SELECT o.id, (p.price_a + p.price_b) as total_price
FROM objects o
INNER JOIN prices p
ON o.id = p.object_id
HAVING total_price > 10

My calculated field is more complex and use external values that change and I cannot pre-calculate it.
As I want only the distinct object.id I've added the upper code as a subquery:
SELECT DISTINCT o_id
FROM (
  SELECT o.id as o_id, (p.price_a + p.price_b) as total_price
  FROM object o
  INNER JOIN price p
  ON o.id = p.object_id
  HAVING total_price > 10)

In Symfony I want that this query returns only the distinct "Object"s.
I've tried many options with query builder but I cannot add a subquery to the "FROM" clause.
I'm tryng to avoid using the inefficient EXISTS clause:
SELECT DISTINCT o.id
FROM objects o
WHERE EXISTS (
  SELECT p.*, (p.price_a + p.price_b) as total_price
  FROM prices p
  WHERE o.id = p.object_id
  HAVING total_price > 10)

Is there any way to do this with Query Builder without using "EXISTS"?

A: I've resolved the problem thanks to the HIDDEN keyword. With HIDDEN you can mark a field to avoid the ORM fetching. It's perfect to remove calculated fields.
With DQL:
SELECT o, (p.price_a + p.price_b) AS HIDDEN total_price
FROM TestObjectBundle:Object o
INNER JOIN TestObjectBuncle:Price p
GROUP BY o
HAVING total_price > 10


text:
Q: add simple 7 second delay before javascript variable is called custom modal I would like for the below variable to fire after a 7 second delay. My chaining attempt failed.
$(function(){
    var inst = $.remodal.lookup[$('[data-remodal-id=modal]').data('remodal')];
    inst.open();
});

Attempt:
    inst.delay(7000).open();

A: Maybe I'm thinking this is simpler than it actually is, but couldn't you just wrap the piece you wish to delay inside a setTimeout()?
setTimeout(function() {
     inst.open();
}, 7000);

A: try a setTimeout
$(function(){
    var inst = $.remodal.lookup[$('[data-remodal-id=modal]').data('remodal')];
    setTimeout(function(){
        inst.open();
    }, 7000); // 7000 ms = 7 seconds
});


text:
Q: Equation $\left\lfloor \frac{y-y^2}{1+\frac{y2}x}\right\rfloor = a$
Let $a \in \mathbb N$. Find all the integer values $x$ for which equation
$$\left\lfloor \frac{y-y^2}{1+\frac{y2}x}\right\rfloor = a$$ has solutions in integers.

My work so far:
I proved that $$-2a-1 \le x \le -1$$

A: This answer proves the following :

For a given $a\ge 1$, $x$ has to satisfy
  $$-2a\le x\le -1$$

Suppose that $x\gt 0$. Then, since $y-y^2\le 0$ and $y^2\ge 0$ for all $y\in\mathbb Z$, we get
$$\frac{y-y^2}{1+\frac{y^2}{x}}\le 0\implies a=\left\lfloor\frac{y-y^2}{1+\frac{y^2}{x}}\right\rfloor\le 0$$
which contradicts that $a\ge 1$. Therefore, we have $x\le -1$.
Suppose that $x\le -2a-1$. Since $1+\frac{y^2}{x}$ has to be negative, we have
$$\begin{align}x\le -2a-1&\implies 0\gt 1+\frac{y^2}x\ge 1+\frac{y^2}{-2a-1}\\&\implies \frac{1}{1+\frac{y^2}{x}}\le\frac{1}{1+\frac{y^2}{-2a-1}}\\&\implies a+1\gt\frac{y-y^2}{1+\frac{y^2}{x}}\ge\frac{y-y^2}{1+\frac{y^2}{-2a-1}}\\&\implies (a+1)\left(1+\frac{y^2}{-2a-1}\right)\lt y-y^2\\&\implies (a+1)(-2a-1+y^2)\gt (y-y^2)(-2a-1)\\&\implies ay^2+(-2a-1)y+(a+1)(2a+1)\lt 0\tag1\end{align}$$
Now the discriminant of $ay^2+(-2a-1)y+(a+1)(2a+1)=0$ is
$$(-2a-1)^2-4a(a+1)(2a+1)=-(2a+1)(4a^2+a+(a-1))$$
This is negative for $a\ge 1$. Hence, there is no $y$ satisfying $(1)$.
Therefore, we have $-2a\le x\le -1$.


text:
Q: In what basis does the Compton scattering measure a photon? For example, the state of a right-handed polarized photon is:
\begin{equation}
|R\rangle = \frac{1}{\sqrt{2}}(|x\rangle + i|y\rangle)
\end{equation}
So theoretically, if we measure the photon in $\langle x|$ or $\langle y|$ basis, it has half the probability of giving x or y polarization. But the x and y directions are user-defined and the polarization takes a definite objective direction after measurement, how do we know which basis a photon is measured when it be Compton scattered? (since the differential cross-section is relevant to the polarization direction)


text:
Q: Getting "TypeError: 'builtin_function_or_method' object is not iterable" when trying to reverse dictionary with non-unique values I want to reverse the dictionary with non-unique values. I am getting error:

TypeError: 'builtin_function_or_method' object is not iterable

my_dict1={"House": "A", "Apartment": "A", "Condo": "B"}
my_dict2={}
for k,v in my_dict1.items:
    my_dict2[v]= my_dict2.get(v,[])
    my_dict2[v].append(k)

print my_dict2

Desired output: {'A':['House','Apartment'],'B':['Condo']}

A: You're missing () on items:
In [78]:

my_dict1={"House": "A", "Apartment": "A", "Condo": "B"}
my_dict2={}
for k,v in my_dict1.items(): #<- missing ()
    my_dict2[v]= my_dict2.get(v,[])
    my_dict2[v].append(k)
my_dict2
Out[78]:
{'B': ['Condo'], 'A': ['Apartment', 'House']}

A: Call the function my_dict1.items(). You are just having a function object there and hence the error. That is the line
for k,v in my_dict1.items:

should be:
for k,v in my_dict1.items():

A: You need to add parens to call the method.
Also, you can use a defaultdict:
from collections import defaultdict
my_dict2 = defaultdict(list)
for k,v in my_dict1.iteritems():
    my_dict2[v].append(k)

print my_dict2
# defaultdict(<type 'list'>, {'A': ['House', 'Apartment'], 'B': ['Condo']})

Also for python2 you should use iteritems().

A: You can use the following one-liner:
{v: [k for k, v2 in a.items() if v2 == v] for v in set(a.values())}

A: Here's another way to do it.
This function uses the setdefault method of a dictionary, so that it creates a key if it is not defined yet.
def invert(d):
    res = {}
    {res.setdefault(v, []).append(k) for k, v in d.items()}
    return res


text:
Q: How to synchronize reasoner in OWLAPI I got a small ontology with the individuals. Some of these individuals should be connected with each other through symmetric ObjectProperty .
I need to use Pellet reasoner, so that it could synchronize and attach symmetric ObjectProperty to the individuals.
I use the OWLAPI to create the ontology. My code for the creation of ObjectProperty is:
// create the OWLObjectProperty isLinkedTo
OWLObjectProperty isLinkedTo = factory.getOWLObjectProperty(IRI.create(ontologyIRI + "#" +hasLinkStr));
// create a set for the axioms (OPAS - Obj.Prop.Axioms Set)
Set<OWLAxiom> isLinkedOPAS = new HashSet<OWLAxiom>();
// add the OWLObjectProperty isLinkedTo to the set isLinkedOPAS
OWLNamedIndividual prevNamedInd = factory.getOWLNamedIndividual(prevIndividual, pm);
isLinkedOPAS.add(factory.getOWLSymmetricObjectPropertyAxiom(isLinkedTo));
//setting the object property for the current (namedInd) and previous (prevNamedInd)individuals
isLinkedOPAS.add(factory.getOWLObjectPropertyAssertionAxiom(isLinkedTo, namedInd, prevNamedInd));
manager.addAxioms(ontology, isLinkedOPAS);

The individuals are created one after each other. Every next individual isLinkedTo previous one with the symmetrical property.
Then, I start the reasoner, but I am not sure if I do it in the right way:
OWLReasoner reasoner = reasonerFactory.createReasoner(ontology, config);
// I am not sure which of these commands is necessary for checking the ObjectProperty assertions
reasoner.precomputeInferences();
reasoner.precomputeInferences(InferenceType.OBJECT_PROPERTY_ASSERTIONS);
reasoner.precomputeInferences(InferenceType.OBJECT_PROPERTY_HIERARCHY);
boolean consistent = reasoner.isConsistent();
System.out.println("Consistent: " + consistent);

When I open this ontology in Protege, it shows me the individuals, but not "connected" symmetrically with the ObjectProperty isLinkedTo:

It shows the right way only after the running reasoner in Protege:

So the question is: What should I write in the code in order to obtain the ontology where the Object Properties are synchronized by the reasoner?

A: These three lines:
reasoner.precomputeInferences();
reasoner.precomputeInferences(InferenceType.OBJECT_PROPERTY_ASSERTIONS);
reasoner.precomputeInferences(InferenceType.OBJECT_PROPERTY_HIERARCHY);

Can be replaced with:
reasoner.precomputeInferences(InferenceType.OBJECT_PROPERTY_ASSERTIONS,
                              InferenceType.OBJECT_PROPERTY_HIERARCHY);

However, for most reasoners this is not different from:
reasoner.precomputeInferences(InferenceType.values());

In order to see the inferred axioms without running a reasoner you can use an
    org.semanticweb.owlapi.util.InferredPropertyAssertionGenerator:
InferredPropertyAssertionGenerator generator = new InferredPropertyAssertionGenerator();
Set<OWLAxiom> axioms = generator.createAxioms(factory, reasoner);

This will provide the inferred axioms to add to the ontology.


text:
Q: How to use bootstrap carousel with Angular correctly There are many questions on stackoveflow. I've gone through some of them:

*

*How to implement bootstrap corousel with angular ng-repeat?

*How to use carousel with Angular : 9 months, no answer.

*Slides in Bootstrap Carousel are not ... only : 1+ year, no proper answer

Then I tried following this article:

*

*How to use bootstrap 4 carousel in angular 5 | 6
and many more.

My code is not working properly. My images are stacked one over the other without animation. No error or warning on console.
Here is my code:
carousel.component.html

    <ngb-carousel>
      <ng-template ngbSlide>

10 seconds between slides...

This carousel uses customized default values.

      </ng-template>
      <ng-template ngbSlide>
         OTHER 4-5 slides
      </ng-template>
    </ngb-carousel>

carousel.component.ts
import { Component, OnInit } from '@angular/core';
import { NgbCarouselConfig } from '@ng-bootstrap/ng-bootstrap';

@Component({
  ...
  providers: [ NgbCarouselConfig ]
})
export class CarouselComponent implements OnInit {

  constructor(config: NgbCarouselConfig) {
    config.interval = 2000;
    config.wrap = true;
    config.keyboard = false;
    config.pauseOnHover = false;
  }

  ngOnInit() {
  }
}

app.module.ts
import { ... } from '@angular/core';
...
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  imports:      [ BrowserModule, FormsModule, NgbModule ],
  ...
})
export class AppModule { }

Looking into my code this way can very painful. So here is a stackblitz.
And here is the screenshot (Zoomed out to 30% to accommodate everything in one image):

Please help me.
Right now I'm calling images from the internet but later I'll keep images locally in my assets/images folder.
And bootstrap is not hard and fast. Please feel free to suggest some other options also.

A: Your problem is that you have not initialized the carousel module in your app.module file so the app doesnt know what a carousel is.
you will need to add  the following module to your global declarations
import { NgbdCarouselBasic } from './carousel-basic';
@NgModule({
  imports: [BrowserModule, NgbModule],
  declarations: [NgbdCarouselBasic],
  exports: [NgbdCarouselBasic],
  bootstrap: [NgbdCarouselBasic]
})

A: You have forgotten styles:)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

But the better way store this style locally and add them to angular.json
"styles": [
  "src/styles.css",
  "src/bootstrap.min.css"
],


text:
Q: JQuery parse JSON I'm fairly new to JQuery. The code below works and I can see the correct JSON response in Firebug. But I couldn't find a way how to get and parse it in the code. Alert window only shows
"[object Object]" but not any json text.
<script>

$.ajaxSetup({ cache: false });

var _token;

function make_token_auth(user, token) {
  var tok = user + ':' + token;
  return "Token " + tok;
}

$.ajax
  ({
    type: "GET",
    url: "url",
    dataType: 'json',
    beforeSend: function (xhr){
        xhr.setRequestHeader('Auth', make_token_auth('userid', 'token'));
    },
    success: function (data){
        alert(data);
    }
});

</script>

A: The fact you precised
dataType: 'json',

tells jQuery to parse the received answer and give it as a javascript object to your success callback.
So what you have here is fine and what is alerted is correct (this is an object, so
alert simply prints the result of data.toString()).
Use console.log to see what it is exactly :
success: function (data){
    console.log(data);
}

and open the developer tools in Chrome or the console in Firebug to browse the properties of the object.

A: don't use alert() for debugging -- it's often unhelpful (as in this case), and also has serious issues when used with asyncronous code (ie anything Ajax) because it interrupts the program flow.
You would be much better off using the browser's console.log() or console.dir() functions, and seeing the object displayed in the console. It is much more functional, and doesn't interrupt the flow of the program.
So instead of alert(myjsonvar) use console.log(myjsonvar).

A: The alert function expects you to pass in a string or number.
Try doing something like this:
for(x in data) {
    alert(x + ': ' + data[x]);
}

Update in response to comments:  You can use alert in development or production to see string and number values in the object returned by the server-side code.
However, carefully rereading your question, it looks like what you really want to see is the actual JSON text.  Looking at @dystroy's answer above, I think that if you remove the dataType: 'json' from your $.ajax invokation, jQuery will treat the response as plain text instead of automatically converting it to an Object.  In this case, you can see the text by passing it to the alert function.

A: You can get the json string by using JSON.stringify
var jsonstr = JSON.stringify(data);
alert(jsonstr);

A: Try using
data = JSON.parse(data)

Then do whatever you want with the data.
Source: JSON.parse() (MDN)


text:
Q: Android AlertDialog with image inside I'm retrieving an Uri from an activity (via startActivityForResult) and I'd like to display it in a dialog but I can't get it to work, I get a NullPointerException for the ImageView when I try to set its URI.
Here's what I tried to do:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    final Uri imageUri = imageReturnedIntent.getData();

    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    LayoutInflater inflater = LayoutInflater.from(this);
    final View view = inflater.inflate(R.layout.image_dialog, null);
    adb
        .setTitle("Confirm picture?")
        .setView(view)
        .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sumthin) {
                uploadDocument(imageUri);
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
            }
        });

    AlertDialog dialog = adb.create();
    // This fails:
    ((ImageView) dialog.findViewById(R.id.dialog_imageview)).setImageURI(imageUri);
    dialog.show();
}

Here's the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dialog_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Did I miss something?
EDIT:
I also tried retrieving the bitmap directly from the intent, as stated in the Android doc (https://developer.android.com/training/camera/photobasics.html):
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);

But I get the samre result (empty/blank space).

A: Use the View object to refer to the element in the layout
 ((ImageView) view.findViewById(R.id.dialog_imageview)).setImageURI(imageUri);

A: Use this
ImageView imageView = ((ImageView) view.findViewById(R.id.dialog_imageview));
Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.placeholder)
       .resize(imgWidth, imgHeight)
       .centerCrop()
       .into(imageView);

A: I think is best idea create a custom dialog using DialogFragment.
https://developer.android.com/reference/android/app/DialogFragment.html


text:
Q: Error while trying Pandas series split using a Dictionary that has the Split info Pandas series split using a Dictionary that has the Split info
I have the below data frame
columns = ['ID','DESIGN_APPROVER','PLAN APPROVER','FINAL_APPROVER']
data = [['ID_001','Sheldon,US','Leonard,Canada', 'Howard,Japan'],
        ['ID_002','Joel,UK','Tommy,Paris', 'Angelo,Ireland']]
df = pd.DataFrame(data=data , columns=columns)
df

Data frame looks like
        ID      DESIGN_APPROVER PLAN APPROVER   FINAL_APPROVER
0   ID_001  Sheldon,US      Leonard,Canada  Howard,Japan
1   ID_002  Joel,UK         Tommy,Paris     Angelo,Ireland

Also I have a dict which specifies how each of the column has to be splitted
key_list = list(set(df.columns)-{'ID'})
value_list = [['{}_NAME'.format(i),'{}_LOCATION'.format(i)] for i in key_list]
dict(zip(key_list, value_list))
split_dict

split_dict
{'PLAN APPROVER': ['PLAN APPROVER_NAME', 'PLAN APPROVER_LOCATION'],
 'FINAL_APPROVER': ['FINAL_APPROVER_NAME', 'FINAL_APPROVER_LOCATION'],
 'DESIGN_APPROVER': ['DESIGN_APPROVER_NAME','DESIGN_APPROVER_LOCATION']}

My Requirement: How to iterate through the dictionary to split the key column into value columns based on ',' delimiter. I tried the below code
    for k,v in split_dict:
        df[v] = df[k].str.split(',', expand=True)

but getting
ValueError: too many values to unpack (expected 2)

A: Use a simple loop and set a max number of split that matches the length of the list (-1):
out = []
for k,v in split_dict.items():
    # for each key, pop (=remove and returns) the column
    # use it as input to str.split to split in n chunks on comma
    # the the maximum number of split to x-1 where x is the number
    # of items in the list
    df[v] = df.pop(k).str.split(',', n=len(v)-1)

output:
       ID PLAN APPROVER_NAME PLAN APPROVER_LOCATION FINAL_APPROVER_NAME FINAL_APPROVER_LOCATION DESIGN_APPROVER_NAME DESIGN_APPROVER_LOCATION
0  ID_001            Leonard                  Tommy              Howard                  Angelo              Sheldon                     Joel
1  ID_002             Canada                  Paris               Japan                 Ireland                   US                       UK

NB. if you want to keep the original column, use slicing instead of pop.:
out = []
for k,v in split_dict.items():
    df[v] = df[k].str.split(',', n=len(v)-1)


text:
Q: How to setup up Labview/myRIO to communicate via UART I'm trying to write to, and read a 3-Space Sensor Nano from a NI myRIO/Labview via UART (or I2C, or SPI - just messing around with them). I have about 0 experience with sending commands via bytes.
I've read through the documentation and understand that I need to initialize the process with the first byte and then send some commands. Then, hopefully, the sensor spits back what I want.
This is the documentation for the sensor. Page 24-25 is what I believe I should be sending.
This is the block diagram of what I've tried. Honestly, I have no clue what I'm doing and couldn't find any good examples online.
If someone could point me in the right direction, or to some resources where I can learn more, I would greatly appreciate it.

A: You're on the right track with your sensor. You can send it ASCII commands like the examples on page 25:
:0\n

This would request the orientation to your sensor.
For the LabVIEW part you can start with this example.
I strongly advise you to make sure you have the right connections and the signal levels on your RIO agree with those your sensor need. If you have a RS232 RIO unit (NI-9870), note that you will need to add a MAX232 level shifter (see page 20 on your sensor manual).


text:
Q: Draw a rotated box in openCV in python I would like to draw a rotated rectangle I've got the top left point and bottom right point, width and height of box. As well as the angle. But I can't seem work out how you draw the rotated rectangle using OpenCV in Python. Please note that I do not want to rotate the image.
Thanks

A: There are many ways to draw a rectangle in OpenCV.
From the OpenCV documentatation: Drawing Functions

rectangle
Draws a simple, thick, or filled up-right rectangle.

So this function doesn't help as you want to draw it rotated.
A rectangle is nothing but a special 4-sided polygon. So simply use the function for drawing polygons instead.

polylines
Draws several polygonal curves.
Python:
cv2.polylines(img, pts, isClosed, color[, thickness[, lineType[, shift]]]) → img

and insert the 4 vertices of your rotated rectangle
or draw the 4 sides separately using

line
Draws a line segment connecting two points.

or

drawContours
Draws contours outlines or filled contours.

The points can be obtained using simple math or for example using OpenCV's  RotatedRect https://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#rotatedrect

A:    class Point:

        def __init__(self, x, y):
            self.x = int(x)
            self.y = int(y)

    class Rectangle:

        def __init__(self, x, y, w, h, angle):

            # Center Point
            self.x = x
            self.y = y
            # Height and Width
            self.w = w
            self.h = h
            self.angle = angle

        def rotate_rectangle(self, theta):
            pt0, pt1, pt2, pt3 = self.get_vertices_points()

            # Point 0
            rotated_x = math.cos(theta) * (pt0.x - self.x) - math.sin(theta) * (pt0.y - self.y) + self.x
            rotated_y = math.sin(theta) * (pt0.x - self.x) + math.cos(theta) * (pt0.y - self.y) + self.y
            point_0 = Point(rotated_x, rotated_y)

            # Point 1
            rotated_x = math.cos(theta) * (pt1.x - self.x) - math.sin(theta) * (pt1.y - self.y) + self.x
            rotated_y = math.sin(theta) * (pt1.x - self.x) + math.cos(theta) * (pt1.y - self.y) + self.y
            point_1 = Point(rotated_x, rotated_y)

            # Point 2
            rotated_x = math.cos(theta) * (pt2.x - self.x) - math.sin(theta) * (pt2.y - self.y) + self.x
            rotated_y = math.sin(theta) * (pt2.x - self.x) + math.cos(theta) * (pt2.y - self.y) + self.y
            point_2 = Point(rotated_x, rotated_y)

            # Point 3
            rotated_x = math.cos(theta) * (pt3.x - self.x) - math.sin(theta) * (pt3.y - self.y) + self.x
            rotated_y = math.sin(theta) * (pt3.x - self.x) + math.cos(theta) * (pt3.y - self.y) + self.y
            point_3 = Point(rotated_x, rotated_y)

            return point_0, point_1, point_2, point_3

Returns four new points that have been translated by theta
https://github.com/rij12/YOPO/blob/yopo/darkflow/net/yopo/calulating_IOU.py


text:
Q: custom method to concat string vs not using that method I have a code like this:
private static final String BR_TAG = "
";

private ResourceBundle rb;

public String create(){
   String result = addLine("some text");
   result = addLine("some text");
   result = addLine("some text");
   ....
}

public String addLine(String text){
    return rb.getString(text) + BR_TAG;
}

This is my current code, but is it optimal? Maybe I shouldn't use separate method to add line to my result? I could to this like this without method addLine:
public String create(){
   String result = rb.getString("some text") + BR_TAG;
   result = rb.getString("some text") + BR_TAG;
   result = rb.getString("some text") + BR_TAG;
   ....
}

Or I can think about third option with passing StringBuilder to my method:
public String create(){
   StringBuilder sb = new StringBuilder();
   addLine("some text", sb);
   addLine("some text", sb);
   ....
}

public void addLine(String text, StringBuilder sb){
    sb.append(rb.getString(text)).append(BR_TAG);
}

What do you think which option is the best?

A: Why not use another method?
IMO, neither is the best, in terms of the beauty of the code. But in terms of performance, the third is better because a StringBuilder takes less time than the + when used a lot of times.
To make your code look prettier, Maybe make use of the Builder Pattern?
public class LineBuilder {
    private StringBuilder builder;
    private static final String BR_TAG = "
";

    public LineBuilder() {
        builder = new StringBuilder();
    }

    public LineBuilder addLine(String text) {
        builder.append(text).append(BR_TAG);
        return this;
    }

    public String build() {
        return builder.toString();
    }
}

You can also add other methods like addHeader or addStrong that adds in
 and  tags.
And you can use it like this:
String result = new LineBuilder()
    .addLine("Hello")
    .addLine("World")
    .addLine("Bye!")
    .build();

That just looks better!


text:
Q: PHP and MySQL not communicating I have come to the conclusion that my PHP installation and my MySQL installation are not getting along; I'm working on making my first web page that uses MySQL for content, but after two days, man pages, online documentation, and dozens of tutorials, I just can't get the PHP/MySQL part to work.  I have an established home web server (I am the only admin/user) that runs Apache and hosts my web pages.  I have MySQL installed, and was able to create and query a database through Terminal.  I have PHP installed, and can use echo to print text to the document.  When I work with MySQL however, everything changes…
I have a page that contains initialization stuff in .  contains a few paragraphs of hardcoded HTML and then PHP code to access MySQL.  When I first loaded the page, all that resulted was a blank page.  I commented out the PHP section and reloaded to confirm that the plain HTML still worked, which it did.  Therefore, some part of PHP was keeping any of the page from ever loading.
To begin troubleshooting my code, I left all of the PHP code commented except the following code for the server connection, which is adapted from several different tutorials:
<?
echo("
PHP is working
");
$ses = mysql_connect("localhost","username","password");
if(!$ses){
 echo("
Connection to content server failed.
");
 exit();
}
echo("
Database Connected
");
?>

When the page is loaded, the beginning HTML loads in addition to a paragraph reading "PHP is working" but neither the failure or success message appear.  I removed the If structure from the code - so that only two echos and the mysql_connect remained – and got the same result.
It seems that the mysql_connect feature is causing the server to stop loading the code when it is run, but I'm out of ideas for how to fix it.  For the record: I've modified the php.ini file to include the "connection = msql.so" line, and I'm using MySQL 5.5, Apache 2.2.22, PHP 5.3.10, Ubuntu 12.04.  Also, both my router and modem have been configured to forward port 3306 to the server – though I don't see how that should be necessary – and my MySQL username and password have been triple checked and are identical to the ones that I use successfully in Terminal.
What am I missing?

A: Everything looks OK so I think your installation is not complete. For mysql and php to communicate, you need to install the php5-mysql  package :
sudo apt-get install php5-mysql

A: Install php5-mysql package and use mysqli_connect instead of of mysql_connect

A: sudo apt-get install php5-mysql

Find Tomcat-version from /etc/init.d/. There should be a file with the name tomcat7, hence 7 is the version
sudo service tomcat7 stop
sudo service tomcat7 start

Sometimes the machine reboot helps in sorting other issues.
After reboot, don't forget to run:
sudo service tomcat7 start


text:
Q: createIndex elasticsearch high level rest client for JAVA makes settings incorrectly I am using this code from the elasticsearch documentation to create an index. I should be able to paste the index configuration object from Postman in my Java code.
request.source("{\n" +
        "    \"settings\" : {\n" +
        "        \"number_of_shards\" : 1,\n" +
        "        \"number_of_replicas\" : 0\n" +
        "    },\n" +
        "    \"mappings\" : {\n" +
        "        \"properties\" : {\n" +
        "            \"message\" : { \"type\" : \"text\" }\n" +
        "        }\n" +
        "    },\n" +
        "    \"aliases\" : {\n" +
        "        \"twitter_alias\" : {}\n" +
        "    }\n" +
        "}", XContentType.JSON);

When I execute GET /index_name I see an index with a weird structure containing two mappings sections. Why is this? I would expect a single mapping and a single settings section.
{
    "contacts_4_3t88f9nabk": {
        "aliases": {},
        "mappings": {
            "properties": {
                "aliases": {
                    "properties": {
                        "twitter_alias": {
                            "type": "object"
                        }
                    }
                },
                "mappings": {
                    "properties": {
                        "properties": {
                            "properties": {
                                "message": {
                                    "properties": {
                                        "type": {
                                            "type": "text",
                                            "fields": {
                                                "keyword": {
                                                    "type": "keyword",
                                                    "ignore_above": 256
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                "settings": {
                    "properties": {
                        "number_of_replicas": {
                            "type": "long"
                        },
                        "number_of_shards": {
                            "type": "long"
                        }
                    }
                }
            }
        },
        "settings": {
            "index": {
                "creation_date": "1589442095340",
                "number_of_shards": "1",
                "number_of_replicas": "1",
                "uuid": "othIq5Q2Sgy4eZ3xkxkneg",
                "version": {
                    "created": "7060199"
                },
                "provided_name": "contacts_4_3t88f9nabk"
            }
        }
    }
}

A: I needed to use the CreateIndexRequest object rather than IndexRequest.

A: You can try below code block to create Index in both(synchronous and async) ways through Java high level rest client:
//Synchronous call
  public String createIndex(String indexName) throws IOException {
    CreateIndexRequest request = buildIndexRequest(indexName);
    CreateIndexResponse indexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    return indexResponse.index();
  }

  //Asynchronous call
  public void createIndexAsync(String indexName) {
    CreateIndexRequest request = buildIndexRequest(indexName);

    ActionListener listener = new ActionListener<IndexResponse>() {
      @Override
      public void onResponse(IndexResponse indexResponse) {
        log.info("Index: {} has been created successfully", indexResponse.getIndex());
      }

      @Override
      public void onFailure(Exception e) {
        log.error("Exception occurred while creating the index: {}", indexName, e);
      }
    };

    restHighLevelClient.indices().createAsync(request, RequestOptions.DEFAULT, listener);
  }

  private CreateIndexRequest buildIndexRequest(String indexName) {
    CreateIndexRequest request = new CreateIndexRequest(indexName);

    //We can specify shards and replicas like below
    request.settings(Settings.builder()
        .put("index.number_of_shards", 1)
        .put("index.number_of_replicas", 2)
    );

    Map<String, Object> mapping = new HashMap<>();
    mapping.put("properties", buildProperties());
    request.mapping(mapping);
    return request;
  }

  //We can define field mapping as below
  private Map<String, Object> buildProperties() {
    Map<String, Object> textType = new HashMap<>();
    textType.put("type", "text");

    Map<String, Object> longType = new HashMap<>();
    longType.put("type", "long");

    Map<String, Object> dateType = new HashMap<>();
    dateType.put("type", "date");

    Map<String, Object> properties = new HashMap<>();
    properties.put("documentId", textType);
    properties.put("documentNumber", longType);
    properties.put("documentCreated", dateType);
    return properties;
  }


text:
Q: Where should I put general app config in a Gatsby project? I'm new to Gatsby, but familiar with CRA. I'm using the default Gatsby setup generated by running gatsby new <project_name> from Gatsby CLI.
I have some general config that I want run in my whole project, regardless of current page - for example:
import { enableMapSet, enableES5 } from "immer";

enableMapSet();
enableES5();

In CRA projects I put this stuff inside App.tsx, but can't figure out what the right place is in a Gatsby project.

A: In Gatsby, you don't have a single configuration file per se. There are several APIs exposed by Gatsby that allows you to configure one specific part of your site.
To run a set of functions regardless of the page you can use a gatsby-browser.js (placed in the root of the project).
Basically, Gatsby exposes a bunch of APIs that lets you respond to actions within the browser, and wrap your site in additional components. The Gatsby Browser API gives you many options for interacting with the client-side of Gatsby. One of them, onClientEntry fits your requirements. From its documentation:

onClientEntry
(_: emptyArg, pluginOptions: pluginOptions) => undefined
Called when the Gatsby browser runtime first starts.

Applied to your code, your gatsby-browser.js should look like:
import { enableMapSet, enableES5 } from "immer";
import React from 'react';

export const onClientEntry = () =>{
  enableMapSet();
  enableES5();
};

The snippet above will trigger enableMapSet() and enableES5() on every page.


text:
Q: SQL Server Compiling and Calculating Data from Multiple Tables I'm trying to find the hour of day in which a subscriber in my database opens the most emails.
I have a table with a bunch of subscriber IDs, I have another table with email opening records mapped to a table that stores sent emails which then maps to specific subscriber IDs.
So my basic desire is to get a table output with each row being a specific subscriber (subscriber ID) and the hour that they opened the most emails in. So I need to first go through each subscriber ID, then I guess create a temp table with each row being a different hour associated with the number of emails they opened in that hour. Then I need to do a select Max to get the max row from that temp table, then I need to place that into my output table, and repeat for the next subscriber.
All I care about is the hour of day. I don't care about month, or year or time. I just want to know what hour of day people mostly open emails.
I've been trying and trying, using CTEs and while loops but to no avail. Any help would be greatly appreciated.
Here's the (minimized) structure:
Table: Subscribers
| subscriber_id | last_name | first_name |
|   9999999999  |   Smith   |   John     |
Table: SentEmail
| message_id | subscriber_id |
| 9028340    | 9999999999    |
Table: OpenEmails
| open_id | message_id | dtopened                  |
| 9923489 | 9028340    | '2011-11-22 15:53:02.157' |
My goal, an output table like this (last column is unnecessary) with each subscriber_id being unique in the list:
| subscriber_id | OpenHour | NumOpens |
| 999999999     | 10       |   32     |

A: You'll have to figure out how to tweak it with the correct columns and what not since the schema was not provided...
With    orderedHourly As
(
        Select  SubscriberID,
                Convert(Date,OpenDateTime) OpenDate,
                Hour(OpenDateTime) OpenHour,
                Row_Number() Over (Partition By SubscriberID, Convert(Date,OpenDateTime) Order By Count(1) Desc) As HourPriority
        From    subscriber s
        Join    email e
                On  s.subscriberID = e.subscriberID
        Group   By SubscriberID, Convert(Date,OpenDateTime), Hour(OpenDateTime)
)
Select  SubScriberID, OpenDate, OpenHour
From    orderHourly
Where   HourPriority = 1

A: I made some assumptions since there wasn't a structure included.
Here is the structure I used.
CREATE TABLE Subscriber (
    Id int not null identity(1,1),
    SubscriberId varchar(50)
    )
CREATE TABLE EmailOpened (
    OpenDate DateTime,
    EmailId int
    )
CREATE TABLE Emails (
    EmailId int not null identity(1,1),
    SubscriberId varchar(50),
    EmailText varchar(max)
)
GO

Here is the query I ended up with.
WITH OpenedByHour AS (
    SELECT
        SubscriberId,
        DATEPART(YEAR, OpenDate) AS OpenYear,
        DATEPART(DAYOFYEAR, OpenDate) AS OpenDOY,
        DATEPART(HOUR, OpenDate) AS OpenHour,
        COUNT(1) AS OpenCount
    FROM Emails
    JOIN EmailOpened
        ON Emails.EmailId = EmailOpened.EmailId
    GROUP BY
        SubscriberId,
        DATEPART(YEAR, OpenDate),
        DATEPART(DAYOFYEAR, OpenDate),
        DATEPART(HOUR, OpenDate)
    ),
    MaxOpenedByHour AS (
    SELECT
        SubscriberId,
        OpenYear,
        OpenDOY,
        OpenHour,
        OpenCount,
        Row_Number() Over (Partition By SubscriberId
                Order By OpenCount Desc) AS MaxRow
    FROM OpenedByHour
    )
SELECT SubscriberId,
    OpenYear,
    OpenDOY,
    OpenHour,
    OpenCount
FROM MaxOpenedByHour
WHERE MaxRow = 1


text:
Q: How do I get notified of a BuildDestroyedEvent Background:
I have a on premise TFS 2015 Update 1 server. In the new TFS build style builds drops done via a network share are not deleted when the build is deleted from expiring retention policies. Our setup can not use server based drops and we must use network share drops.
As a work around I am attempting to write a service that will be notified when a build expires and is deleted and it can then delete the associated network share for me.
Issue:
I discovered the .NET TFS client libraries, in the Microsoft.TeamFoundationServer.Client NuGet package there is a Microsoft.TeamFoundation.Build.WebApi.Events.BuildDestroyedEvent class which looks exactly like what I need. However I can not figure out how to "subscribe" to that event.
I found a good tutorial using the Microsoft.TeamFoundationServer.ExtendedClient API which shows a subscription to a WorkItemChangedEvent with a web callback. However when I tried to a BuildDestroyedEvent I get a error.
const string collectionUri = "https://tfs.example.com:8081/tfs/MyCollection";
static void Main(string[] args)
{
    using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(collectionUri)))
    {
        tpc.Authenticate();
        tpc.EnsureAuthenticated();

        var eventService = tpc.GetService<IEventService>();

        DeliveryPreference del = new DeliveryPreference();
        del.Address = "http://srchamberlain.example.com/TestWebApp/api/destroyEventSink";
        del.Schedule = DeliverySchedule.Immediate;
        del.Type = DeliveryType.Soap;

        var id = eventService.SubscribeEvent("BuildDestroyedEvent", "", del);
        Console.WriteLine(id);
    }

    Console.ReadLine();
}

The error I get on the SubscribeEvent line is

Microsoft.TeamFoundation.Framework.Client.TeamFoundationServiceException was unhandled
  ErrorCode=0
  EventId=3000
  HResult=-2146232832
  IsRemoteException=true
  LogException=false
  Message=Event type BuildDestroyedEvent does not exist.
  ReportException=false
  Source=Microsoft.TeamFoundation.Client
  StackTrace:
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.HandleReply(TfsClientOperation operation, TfsMessage message, Object[]& outputs)
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters, TimeSpan timeout, Object[]& outputs)
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters, Object[]& outputs)
       at Microsoft.TeamFoundation.Client.Channels.TfsHttpClientBase.Invoke(TfsClientOperation operation, Object[] parameters)
       at Microsoft.TeamFoundation.Framework.Client.EventWebService.SubscribeEvent(String userId, String eventType, String filterExpression, DeliveryPreference preferences, String projectName)
       at Microsoft.TeamFoundation.Framework.Client.TeamFoundationEventService.SubscribeEvent(String eventType, String filterExpression, DeliveryPreference preferences)
       at SandboxConsole.Program.Main(String[] args) in D:\Code\SandboxConsole\SandboxConsole\Program.cs:line 33
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
       Actor=""
       HResult=-2146233087
       Lang=en
       Message=Event type BuildDestroyedEvent does not exist.
       Node=""
       Role=""
       InnerException:

Question:
What is the correct way get a notification of the Microsoft.TeamFoundation.Build.WebApi.Events.BuildDestroyedEvent firing?

A: *

*collectionUri for VSTS is always https://xxx.visualstudio.com/DefaultCollection, other format can't be recognized.

*the tutorials are all for TFS on-premise, not VSTS. As Event Subscriptions is a server side plugin, but VSTS is hosted, it's unable to run Subscription on server side. .Net Event Subscriptions is not supported in VSTS.

*VSTS now supports to create a service hooks subscription, but supported events doesn't include BuildDestroyedEvent.
Supported events:

*

*build completed

*code pushed (for Git team projects)

*pull request create or updated (for Git team projects)

*code checked in (TFVC team projects)

*work item created, updated, deleted, restored or commented on

*message posted to a team room

So, you may take Harshil Lodhi's advice as a workaround.


text:
Q: What causes 'Both DataSource and DataSourceID are defined on 'DataListCity'. Remove one definition' error? I am getting this error

"Both DataSource and DataSourceID are defined on 'DataListCity'.  Remove one definition."

This is the code from my Masterpage that is causing the error
<asp:DataList ID="DataListCity" runat="server" Width="100%"
    onitemcommand="DataListCity_ItemCommand" CellPadding="4"
    ForeColor="#333333" DataSourceID="SqlDataSource1">

    <ItemTemplate>
        CityId:
        <asp:Label ID="CityIdLabel" runat="server" Text='<%# Eval("CityId") %/>

        CityName:
        <asp:Label ID="CityNameLabel" runat="server" Text='<%# Eval("CityName")%>' />

    </ItemTemplate>
</asp:DataList>

<asp:SqlDataSource
    ConnectionString="<%$ ConnectionStrings:HotelConnString %>"
    ID="SqlDataSource1" runat="server"
    SelectCommand="SELECT [CityId], [CityName], [Description] FROM [Categories]">
</asp:SqlDataSource>

A: Remove your binding code from cs if you have written in code behind because you can bind only by code behind or from design not both at same time
Remove these lines from code behind
DataListCity.DataSource=somesource;
DataListCity.DataBind();


text:
Q: How can I write IIS Rewrite multiple subdomains to multiple local port rule? I want to set reverse proxy rules in IIS for list below.
app1.application.com > localhost:26000
app2.application.com > localhost:26001
app3.application.com > localhost:26002

I added bindings in single IIS site then defined single rule for port 26000. All of them redirect to app on port 27000.
Here is the rule I added;
<rule name="ReverseProxyInboundRule1" stopProcessing="true">
    <match url="(.*)" />
    <action type="Rewrite" url="http://localhost:26000/{R:1}" />
</rule>

How can I add other rules?
Thanks

A: Like this.  Note the 4th rule how I'm doing a temporary redirect to an internet URL.  That's an easy way for "testing" your scripts as its a little more foolproof to do Redirect and internal rewrites.  Typically I get everything working with Redirects (again, use Temporary) and then switch it over to the internal Rewrites.
Finally, you might consider adding a catch-all rewrite after your 3 to redirect either to an error page or to a "default" app.  Since these rules are processed in order (and Stop Processing is set) you can just add that rule without the HTTP_HOST condition at the end.
            <rule name="ReverseProxyInboundRule1" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://localhost:26000/{R:1}" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^(app1\.application\.com)$" />
                </conditions>
            </rule>
            <rule name="ReverseProxyInboundRule2" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://localhost:26001/{R:1}" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^(app2\.application\.com)$" />
                </conditions>
            </rule>
            <rule name="ReverseProxyInboundRule3" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://localhost:26002/{R:1}" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^(app3\.application\.com)$" />
                </conditions>
            </rule>
            <rule name="ReverseProxyInboundRule4" enabled="false" stopProcessing="true">
                <match url="(.*)" />
                <action type="Redirect" url="http://www.google.com" redirectType="Temporary" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^(app4\.application\.com)$" />
                </conditions>
            </rule>


text:
Q: How do I compute equinox/solstice moments? What algorithms or formulas are available for computing the equinoxes and solstices?  I found one of these a few years ago and implemented it, but the precision was not great: the time of day seemed to be assumed at 00:00, 06:00, 12:00, and 18:00 UTC depending on which equinox or solstice was computed.  Wikipedia gives these computed out to the minute, so something more exact must be possible.  Libraries for my favorite programming language also come out to those hardcoded times, so I assume they are using the same or a similar algorithm as the one I implemented.
I also once tried using a library that gave me the solar longitude and implementing a search routine to zero in on the exact moments of 0, 90, 180, and 270 degrees; this worked down to the second but did not agree with the times in Wikipedia, so I assume there was something wrong with this approach.  I am, however, pleasantly surprised to discover that Maimonides (medieval Jewish scholar) proposed an algorithm using the exact same idea a millenium ago.

A: A great source for the (complex!) underlying formulas and algorithms is Astronomical Algorithms by Jean Meeus.
Using the PyMeeus implementation of those algorithms, and the code below, you can get the following values for the 2018 winter solstice (where "winter" refers to the northern hemisphere).
winter solstice for 2018 in Terrestrial Time is at:
 (2018, 12, 21, 22, 23, 52.493725419044495)

winter solstice for 2018 in UTC, if last leap second was (2016, 12):
 (2018, 12, 21, 22, 22, 43.30972542127711)

winter solstice for 2018 in local time, if last leap second was (2016, 12)
 and local time offset is -7.00 hours:
 (2018, 12, 21, 15, 22, 43.30973883232218)

i.e. 2018-12-21T15:22:43.309725-07:00

Of course, the answer is not accurate down to microseconds, but I also wanted to show how to do high-precision conversions with arrow.
Code:
from pymeeus.Sun import Sun
from pymeeus.Epoch import Epoch

year = 2018  # datetime.datetime.now().year
target="winter"

# Get terrestrial time of given solstice for given year
solstice_epoch = Sun.get_equinox_solstice(year, target=target)

print("%s solstice for %d in Terrestrial Time is at:\n %s" %
      (target, year, solstice_epoch.get_full_date()))

print("%s solstice for %d in UTC, if last leap second was %s:\n %s" %
 (target, year, Epoch.get_last_leap_second()[:2], solstice_epoch.get_full_date(utc=True)))

solstice_local = (solstice_epoch + Epoch.utc2local()/(24*60*60))
print("%s solstice for %d in local time, if last leap second was %s\n"
 " and local time offset is %.2f hours:\n %s" %
 (target, year, Epoch.get_last_leap_second()[:2],
  Epoch.utc2local() / 3600., solstice_local.get_full_date(utc=True)))

Using the very cool more ISO and TZ aware module Arrow: better dates and times for Python, that can be printed more nicely:
import arrow
import math

slutc = solstice_epoch.get_full_date(utc=True)
frac, whole = math.modf(slutc[5])

print("i.e. %s" % arrow.get(*slutc[:5], int(whole), round(frac * 1e6)).to('local'))

A: I'm not sure if this is an accurate enough solution for you, but I found a NASA website that has some code snippets for calculating the vernal equinox as well as some other astronomical-type information.  I've also found some references to a book called Astronomical Algorithms which may have the answers you need if the info somehow isn't available online.

A: I know you're looking for something that'll paste into an answer here, but I have to mention SPICE, a toolkit produced by NAIF at JPL, funded by NASA. It might be overkill for Farmer's Almanac stuff, but you mentioned interest in precision and this toolkit is routinely used in planetary science.

A: I have implemented Jean Meeus' (the author of the Astronomical Algorithms referenced above) equinox and solstice algorithm in C and Java, if you're interested.


text:
Q: How can I bind to properties of the ViewModel and properties of collection items in the ViewModel? I'll try and explain this as best as I can...
I'm just trying to make sense of views, view models and presenters so I created a little program to illustrate some of the ins and outs. My small application basically stores albums. The albums are listed in a combo box and I have fields for artist, genre and year, which are all text boxes. Up until now, no problems... I created a binding source and bound it to the view model (which has properties for title, artist, genre and year) and it works as expected. I can cycle through the combo box and the various text boxes will change depending on the combo box selection.
I then decided I wanted to add a list of songs for each album, so I added a new songs property to the view model and added a data grid view to the view. This is where I became quite confused. If I bind the binding source I used for everything else to the data grid view, it obviously just wants to render the immediate fields of the view model (basically repeating what I'm displaying in the text boxes, only in a grid format).
Assuming I described the problem adequately enough, what can I do to display the album fields in the text boxes and the songs in the data grid view? I think I've come to the conclusion that I simply need a second binding source, but I'd like to avoid it if possible. I've attempted obvious things like directing the DataMember property of the data grid view to "Songs" (the property name of the songs collection in the view model) without any luck.
Could anyone point me in the right direction?

A: I have always accomplished this using a second BindingSource that has the first BindingSource set as the DataSource.

A: So, the ViewModel loads and readies the Models that represent Albums, and the View watches the ViewModel and presents to the users the Albums in a way they can understand.
First, let's look at the Model.  You have an Album, which has one or more Songs.
public sealed class Album
{
  public string Name {get;set;}
  public string Artist {get;set;}
  public IEnumerable<Song> Songs {get;set;}
}

public sealed class Song
{
  public string Name {get;set;}
  public TimeSpan Length {get;set;}
}

The ViewModel loads up a public collection of all the Albums
public sealed class ViewModel : INotifyPropertyChanged
{
  public ObservableCollection<Album> Albums {get;set;}
  public Album SelectedAlbum {get;set;} // implement INPC for this property
}

The ViewModel is the DataContext for the View.  Controls bind to Albums and SelectedAlbum.  Note, if the ViewModel doesn't have to act on the SelectedAlbum, we could handle the currently selected Album all in the View.  This is just an example.
<ComboBox
    ItemsSource="{Binding Albums}"
    SelectedItem="{Binding SelectedAlbum}" />

Your controls bind relative to SelectedAlbum in order to display information about it
<TextBlock Text="{Binding SelectedAlbum.Name}" />

Your DataGrid binds to the Songs property of the SelectedAlbum
<DataGrid ItemsSource="{Binding SelectedAlbum.Songs}" />

And everything went better than expected.


text:
Q: How to make one router which works with more then one route So I was trying to make one function which to do crud operation for all routes but found out once i call one route with that function it doesnt work with any other routes and will only get post put or delete item that are in the first route in my code.
My base router

function baseRouter(Model, outputName) {
  router
    .route("/")
    .get((req, res, next) => {
      getAllData(res, Model, outputName + "s");
    })
    .post((req, res, next) => {
      let data = new Model(req.body);
      addData(res, data, outputName);
    });

  router
    .route("/:id")
    .get((req, res, next) => {
      getDataById(req, res, Model, outputName);
    })
    .put((req, res, next) => {
      let data = req.body;
      updateDataById(req, res, Model, data, outputName);
    })
    .delete((req, res, next) => {
      deleteDataById(req, res, Model, outputName);
    });

  return router;
}

module.exports = baseRouter;

The code from which i am calling every routes

const router = require("express").Router();
//all models
const UserModel = require("../models/user.model");
const ContactModel = require("../models/contact.model");
const LinksModel = require("../models/links.model");
const EducationModel = require("../models/education.model");
const SkillModel = require("../models/skills.model");
const ProjectModel = require("../models/projects.model");

//router
const baseRouter = require("./baseRoute");

// all routes crud operation
router.use("/contact", baseRouter(ContactModel, "Contact"));
router.use("/link", baseRouter(LinksModel, "Link"));
router.use("/education", baseRouter(EducationModel, "Education"));
router.use("/skill", baseRouter(SkillModel, "Skill"));
router.use("/project", baseRouter(ProjectModel, "Project"));

module.exports = router;

I hope i explained my question properly.

A: try passing the router instance and name string to your
function baseRouter(router, name, Model, outputName) {...}

add it to the routes path in that function
.route(`${name}/`)

and
.route(`${name}/:id`)

and call it in your router index as
baseRouter(router, "contact", ContactModel, "Contact"));

you don't have to return it in the function because you're defining the routes for the router instance directly and might be able to use the "contact" once and capitalize it where you need it
you instantiate your router in the router index and return it to your app index if you want after you've passed all your defined routes the same way


text:
Q: pg_restore does not restore blobs I have a database with many large objects. A table have a column OID that refers to these large objects. I dump the database daily, including all large objects, with command:
pg_dump --format=c --file=/var/backups/pgsql/db-neos.pgdump \
  --compress=6 --blobs neos

and then I restore it, on a different machine, with command:
createdb neos
pg_restore -d neos /mnt/db-neos.pgdump

but, while all tables are correctly created, large objects aren't.
Instead, an error message is displayed by pg_restore:
pg_restore: [compress_io] decompressione dei dati fallita: (null)
(english: could not uncompress data)

A: I've faced the same issue some months ago, and I have managed to solve it with a bash script. This is the piece of code that take care to backup large objects, and save it to a local folder (/path/to/destination/lo/folder/) with filename = oid (the filename is important in order to restore lo with same oid) :
echo -e "going to export largeobjects belonging to community $i..." && sleep 2
psql -U <username> -X -c "SELECT file_oid FROM <my_table>" \
    --single-transaction \
    --set AUTOCOMMIT=off \
    --set ON_ERROR_STOP=on \
    --no-align \
    -t \
    --field-separator ' ' \
    --quiet \
    -d <my_source_db> \
| while read file_oid ; do
    echo "Exporting largeobject OID: $file_oid"
    ${PSQL} -d <my_source_db> -c "SELECT lo_export($file_oid, '/path/to/destination/lo/folder/$file_oid');"
done

Then to restore them I've written this other piece of code:
echo "going to import largeobjects belonging to community $i..." && sleep 2
LOBJECTS=/path/to/destination/lo/folder/*
for f in $LOBJECTS
do
    echo "Processing $f file..."
    filename=$(basename "$f")
    oid=${filename}

    psql -U <username> -d <my_source_db> -c"
    -- check if largeobject is already present, if it is delete it
    SELECT lo_unlink(${oid});"

    psql -U <username> -d <my_source_db> -c"
    -- import largeobjects
    SELECT lo_import('$f', ${oid});
    "
done

Out there it may exist a simpler solution, but at the time I've not been able to find it, this is why used this approach. I hope you will be more lucky and find a cleaner solution. I'll follow this post in case I can learn something useful too : )

A: I found the problem: the dump file was corrupt, so while importing large objects, pg_restore failed with message:
pg_restore: ripristino del large object con OID 19659
pg_restore: ripristino del large object con OID 19660
pg_restore: [compress_io] decompressione dei dati fallita: (null)

and it stopped after reaching the end of the file.