text:
Q: Reading in pydub AudioSegment from url. BytesIO returning "OSError [Errno 2] No such file or directory" on heroku only; fine on localhost EDIT 1 for anyone with the same error: installing ffmpeg did indeed solve that BytesIO error
EDIT 1 for anyone still willing to help: my problem is now that when I AudioSegment.export("filename.mp3", format="mp3"), the file is made, but has size 0 bytes -- details below (as "EDIT 1")

EDIT 2: All problems now solved.

*

*Files can be read in as AudioSegment using BytesIO

*I found buildpacks to ensure ffmpeg was installed correctly on my app, with lame support for exporting proper mp3 files

Answer below

Original question
I have pydub working nicely locally to crop a particular mp3 file based on parameters in the url.
(?start_time=3.8&end_time=5.1)
When I run foreman start it all looks good on localhost. The html renders nicely.
The key lines from the views.py include reading in a file from a url using
url = "https://s3.amazonaws.com/shareducate02/The_giving_tree__by_Alex_Blumberg__sponsored_by_mailchimp-short.mp3"
mp3 = urllib.urlopen(url).read() # inspired by http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter11_image/06_speech.ipynb
original=AudioSegment.from_mp3(BytesIO(mp3))  # AudioSegment.from_mp3 is a pydub command, see http://pydub.com
section = original[start_time_ms:end_time_ms]

That all works great... until I push to heroku (django app) and run it online.
then when I load the same page now on the herokuapp.com, I get this error
OSError at /path/to/page
[Errno 2] No such file or directory
Request Method: GET
Request URL:    http://my.website.com/path/to/page?start_time=3.8&end_time=5
Django Version: 1.6.5
Exception Type: OSError
Exception Value:
[Errno 2] No such file or directory
Exception Location: /app/.heroku/python/lib/python2.7/subprocess.py in _execute_child, line 1327
Python Executable:  /app/.heroku/python/bin/python
Python Version: 2.7.8
Python Path:
['/app',
 '/app/.heroku/python/bin',
 '/app/.heroku/python/lib/python2.7/site-packages/setuptools-5.4.1-py2.7.egg',
 '/app/.heroku/python/lib/python2.7/site-packages/distribute-0.6.36-py2.7.egg',
 '/app/.heroku/python/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg',
 '/app',
 '/app/.heroku/python/lib/python27.zip',
 '/app/.heroku/python/lib/python2.7',
 '/app/.heroku/python/lib/python2.7/plat-linux2',
 '/app/.heroku/python/lib/python2.7/lib-tk',
 '/app/.heroku/python/lib/python2.7/lib-old',
 '/app/.heroku/python/lib/python2.7/lib-dynload',
 '/app/.heroku/python/lib/python2.7/site-packages',
 '/app/.heroku/python/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info']

Traceback:
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/evernote/views.py" in finalize
  105.       original=AudioSegment.from_mp3(BytesIO(mp3))
File "/app/.heroku/python/lib/python2.7/site-packages/pydub/audio_segment.py" in from_mp3
  318.         return cls.from_file(file, 'mp3')
File "/app/.heroku/python/lib/python2.7/site-packages/pydub/audio_segment.py" in from_file
  302.         retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/app/.heroku/python/lib/python2.7/subprocess.py" in call
  522.     return Popen(*popenargs, **kwargs).wait()
File "/app/.heroku/python/lib/python2.7/subprocess.py" in __init__
  710.                                 errread, errwrite)
File "/app/.heroku/python/lib/python2.7/subprocess.py" in _execute_child
  1327.                 raise child_exception

I have commented out some of the original to convince myself that sure enough the single line original=AudioSegment.from_mp3(BytesIO(mp3)) is where the problem kicks in... but this is not a problem locally
The full function in views.py starts like this:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect #, Http404, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
import pydub
# Maybe only need:
from pydub import AudioSegment # == see below
from time import gmtime, strftime

import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key

# http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter11_image/06_speech.ipynb
import urllib
from io import BytesIO
# import numpy as np
# import scipy.signal as sg
# import pydub # mentioned above already
# import matplotlib.pyplot as plt
# from IPython.display import Audio, display
# import matplotlib as mpl
# %matplotlib inline

import os
# from settings import AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_BUCKET_NAME
AWS_ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY') # there must be a better way?
AWS_SECRET_KEY = os.environ.get('AWS_SECRET_KEY')
AWS_BUCKET_NAME = os.environ.get('S3_BUCKET_NAME')

# http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python

boto_conn = S3Connection(AWS_ACCESS_KEY, AWS_SECRET_KEY)
bucket = boto_conn.get_bucket(AWS_BUCKET_NAME)
s3_url_format = 'https://s3.amazonaws.com/shareducate02/{end_path}'

and specifically the view in views.py that's called when I visit the page:
def finalize(request):

    start_time = request.GET.get('start_time')

    end_time = request.GET.get('end_time')

    original_file = "https://s3.amazonaws.com/shareducate02/The_giving_tree__by_Alex_Blumberg__sponsored_by_mailchimp-short.mp3"

    if start_time:

      # original=AudioSegment.from_mp3(original_file)  #...that didn't work
      # but this works below:

      # next three uncommented lines from http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter11_image/06_speech.ipynb
      # python 2.x
      url = original_file
      # req = urllib.Request(url, headers={'User-Agent': ''}) # Note: I commented out this because I got error that "Request" did not exist
      mp3 = urllib.urlopen(url).read()
      # That's for my 2.7

      # If I ever upgrade to python 3.x, would need to change it to:
      # req = urllib.request.Request(url, headers={'User-Agent': ''})
      # mp3 = urllib.request.urlopen(req).read()
      # as per instructions on http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter11_image/06_speech.ipynb

      original=AudioSegment.from_mp3(BytesIO(mp3))
      # original=AudioSegment.from_mp3("static/givingtree.mp3") # alternative that works locally (on laptop) but no use for heroku

      start_time_ms = int(float(start_time) * 1000)
      if end_time:
        end_time_ms = int(float(end_time) * 1000)
      else:
        end_time_ms = int(float(original.duration_seconds) * 1000)
      duration_ms = end_time_ms - start_time_ms
      # duration = end_time - start_time
      duration = duration_ms/1000

   #   section = original[start_time_ms:end_time_ms]
   #   section_with_fading = section.fade_in(100).fade_out(100)

      clip = "demo-"
      number = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
      clip += number
      clip += ".mp3"

      # DON'T BOTHER writing locally:
      # clip_with_path = "evernote/static/"+clip
      # section_with_fading.export(clip_with_path, format = "mp3")

   #   tempclip = section_with_fading.export(format = "mp3")

      # commented out while de-bugging, but was working earlier if run on localhost
      # c = boto.connect_s3()
      # b = c.get_bucket(S3_BUCKET_NAME)  # as defined above
      # k = Key(b)
      # k.key=clip
      # # k.set_contents_from_filename(clip_with_path)
      # k.set_contents_from_file(tempclip)
      # k.set_acl('public-read')
      clip_made = True
    else:
      duration = 0.0
      clip_made = False
      clip = ""
    context = {'original_file':original_file, 'new_file':clip, 'start_time': start_time, 'end_time':end_time, 'duration':duration, 'clip_made':clip_made}
    return render(request, 'finalize.html' , context)

Any suggestions?
Potentially related:
I have ffmpeg installed locally
But have been unable to install it onto heroku, due to not understanding buildpacks.  I tried just a moment ago (http://stackoverflow.com/questions/14407388/how-to-install-ffmpeg-for-a-django-app-on-heroku and https://github.com/shunjikonishi/heroku-buildpack-ffmpeg) but so far ffmpeg is not working on heroku (ffmpeg is not recognised when I do "heroku run ffmpeg --version")
...do you think this is the reason?
An answer like any of these would be much appreciated as I'm going round in circles here:

*

*"I think ffmpeg is indeed your problem. Try harder to sort that out, to get it installed on heroku"

*"Actually, I think this is why BytesIO is not working for you: ..."

*"Your approach is terrible anyway... if you want to read in an audio file to process using pydub, you should just do this instead: ..." (since I'm just hacking my way through pydub for my first time... my approach may be poor)

EDIT 1
ffmpeg is now installed (e.g., I can output wav files)
However, I can't create mp3 files, still... or more correctly, I can, but the filesize is zero
(venv-app)moriartymacbookair13:getstartapp macuser$ heroku config:add BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git
Setting config vars and restarting awe01... done, v93
BUILDPACK_URL: https://github.com/ddollar/heroku-buildpack-multi.git
(venv-app)moriartymacbookair13:getstartapp macuser$ vim .buildpacks
(venv-app)moriartymacbookair13:getstartapp macuser$ cat .buildpacks
https://github.com/shunjikonishi/heroku-buildpack-ffmpeg.git
https://github.com/heroku/heroku-buildpack-python.git
(venv-app)moriartymacbookair13:getstartapp macuser$ git add --all
(venv-app)moriartymacbookair13:getstartapp macuser$ git commit -m "need multi, not just ffmpeg, so adding back in multi + shun + heroku, with trailing .git in .buildpacks file"
[master cd99fef] need multi, not just ffmpeg, so adding back in multi + shun + heroku, with trailing .git in .buildpacks file
 1 file changed, 2 insertions(+), 2 deletions(-)
(venv-app)moriartymacbookair13:getstartapp macuser$ git push heroku master
Fetching repository, done.
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 372 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)

-----> Fetching custom git buildpack... done
-----> Multipack app detected
=====> Downloading Buildpack: https://github.com/shunjikonishi/heroku-buildpack-ffmpeg.git
=====> Detected Framework: ffmpeg
-----> Install ffmpeg
       DOWNLOAD_URL =  http://flect.github.io/heroku-binaries/libs/ffmpeg.tar.gz
       exporting PATH and LIBRARY_PATH
=====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-python.git
=====> Detected Framework: Python
-----> Installing dependencies with pip
       Cleaning up...

-----> Preparing static assets
       Collectstatic configuration error. To debug, run:
       $ heroku run python ./example/manage.py collectstatic --noinput

Using release configuration from last framework (Python).
-----> Discovering process types
       Procfile declares types -> web

-----> Compressing... done, 198.1MB
-----> Launching... done, v94
       http://[redacted].herokuapp.com/ deployed to Heroku

To git@heroku.com:awe01.git
   78d6b68..cd99fef  master -> master
(venv-app)moriartymacbookair13:getstartapp macuser$ heroku run ffmpeg
Running `ffmpeg` attached to terminal... up, run.6408
ffmpeg version git-2013-06-02-5711e4f Copyright (c) 2000-2013 the FFmpeg developers
  built on Jun  2 2013 07:38:40 with gcc 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1)
  configuration: --enable-shared --disable-asm --prefix=/app/vendor/ffmpeg
  libavutil      52. 34.100 / 52. 34.100
  libavcodec     55. 13.100 / 55. 13.100
  libavformat    55.  8.102 / 55.  8.102
  libavdevice    55.  2.100 / 55.  2.100
  libavfilter     3. 74.101 /  3. 74.101
  libswscale      2.  3.100 /  2.  3.100
  libswresample   0. 17.102 /  0. 17.102
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

Use -h to get full help or, even better, run 'man ffmpeg'
(venv-app)moriartymacbookair13:getstartapp macuser$ heroku run bash
Running `bash` attached to terminal... up, run.9660
~ $ python
Python 2.7.8 (default, Jul  9 2014, 20:47:08)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydub
>>> from pydub import AudioSegment
>>> exit()
~ $ which ffmpeg
/app/vendor/ffmpeg/bin/ffmpeg
~ $ python

Python 2.7.8 (default, Jul  9 2014, 20:47:08)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydub
>>> from pydub import AudioSegment
>>> AudioSegment.silent(5000).export("/tmp/asdf.mp3", "mp3")
<open file '/tmp/asdf.mp3', mode 'wb+' at 0x7f9a37d44780>
>>> exit ()
~ $ cd /tmp/
/tmp $ ls
asdf.mp3
/tmp $ open asdf.mp3
bash: open: command not found
/tmp $ ls -lah
total 8.0K
drwx------  2 u36483 36483 4.0K 2014-10-22 04:14 .
drwxr-xr-x 14 root   root  4.0K 2014-09-26 07:08 ..
-rw-------  1 u36483 36483    0 2014-10-22 04:14 asdf.mp3

Note the file size of 0 above for the mp3 file... when I do the same thing on my macbook, the file size is never zero
Back to the heroku shell:
/tmp $ python
Python 2.7.8 (default, Jul  9 2014, 20:47:08)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydub
>>> from pydub import AudioSegment
>>> pydub.AudioSegment.ffmpeg = "/app/vendor/ffmpeg/bin/ffmpeg"
>>> AudioSegment.silence(1200).export("/tmp/herokuSilence.mp3", format="mp3")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'AudioSegment' has no attribute 'silence'
>>> AudioSegment.silent(1200).export("/tmp/herokuSilence.mp3", format="mp3")
<open file '/tmp/herokuSilence.mp3', mode 'wb+' at 0x7fcc2017c780>
>>> exit()
/tmp $ ls
asdf.mp3  herokuSilence.mp3
/tmp $ ls -lah
total 8.0K
drwx------  2 u36483 36483 4.0K 2014-10-22 04:29 .
drwxr-xr-x 14 root   root  4.0K 2014-09-26 07:08 ..
-rw-------  1 u36483 36483    0 2014-10-22 04:14 asdf.mp3
-rw-------  1 u36483 36483    0 2014-10-22 04:29 herokuSilence.mp3

I realised the first time that I had forgotten the pydub.AudioSegment.ffmpeg = "/app/vendor/ffmpeg/bin/ffmpeg" command, but as you can see above, the file is still zero size
Out of desperation, I even tried adding the ".heroku" into the path to be as verbatim as your example, but that didn't fix it:
/tmp $ python
Python 2.7.8 (default, Jul  9 2014, 20:47:08)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydub
>>> from pydub import AudioSegment
>>> pydub.AudioSegment.ffmpeg = "/app/.heroku/vendor/ffmpeg/bin/ffmpeg"
>>> AudioSegment.silent(1200).export("/tmp/herokuSilence03.mp3", format="mp3")
<open file '/tmp/herokuSilence03.mp3', mode 'wb+' at 0x7fc92aca7780>
>>> exit()
/tmp $ ls -lah
total 8.0K
drwx------  2 u36483 36483 4.0K 2014-10-22 04:31 .
drwxr-xr-x 14 root   root  4.0K 2014-09-26 07:08 ..
-rw-------  1 u36483 36483    0 2014-10-22 04:14 asdf.mp3
-rw-------  1 u36483 36483    0 2014-10-22 04:31 herokuSilence03.mp3
-rw-------  1 u36483 36483    0 2014-10-22 04:29 herokuSilence.mp3

Finally, I tried exporting a .wav file to check pydub was at least working correctly
/tmp $ python
Python 2.7.8 (default, Jul  9 2014, 20:47:08)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydub
>>> from pydub import AudioSegment
>>> pydub.AudioSegment.ffmpeg = "/app/vendor/ffmpeg/bin/ffmpeg"
>>> AudioSegment.silent(1300).export("/tmp/heroku_wav_silence01.wav", format="wav")
<open file '/tmp/heroku_wav_silence01.wav', mode 'wb+' at 0x7fa33cbf3780>
>>> exit()
/tmp $ ls
asdf.mp3  herokuSilence03.mp3  herokuSilence.mp3  heroku_wav_silence01.wav
/tmp $ ls -lah
total 40K
drwx------  2 u36483 36483 4.0K 2014-10-22 04:42 .
drwxr-xr-x 14 root   root  4.0K 2014-09-26 07:08 ..
-rw-------  1 u36483 36483    0 2014-10-22 04:14 asdf.mp3
-rw-------  1 u36483 36483    0 2014-10-22 04:31 herokuSilence03.mp3
-rw-------  1 u36483 36483    0 2014-10-22 04:29 herokuSilence.mp3
-rw-------  1 u36483 36483  29K 2014-10-22 04:42 heroku_wav_silence01.wav
/tmp $

At least that filesize for .wav is non-zero, so pydub is working
My current theory is that either I'm still not using ffmpeg correctly, or it's insufficient... maybe I need an mp3 additional install on top of basic ffmpeg.
Several sites mention "libavcodec-extra-53" but I'm not sure how to install that on heroku, or to check if I have it? https://github.com/jiaaro/pydub/issues/36
Similarly tutorials on libmp3lame seem to be geared towards laptop installation rather than installation on heroku, so I'm at a loss http://superuser.com/questions/196857/how-to-install-libmp3lame-for-ffmpeg
In case relevant, I also have youtube-dl in my requirements.txt... this also works locally on my macbook, but fails when I run it in the heroku shell:
~/ytdl $ youtube-dl --restrict-filenames -x --audio-format mp3 n2anDgdUHic
[youtube] Setting language
[youtube] Confirming age
[youtube] n2anDgdUHic: Downloading webpage
[youtube] n2anDgdUHic: Downloading video info webpage
[youtube] n2anDgdUHic: Extracting video information
[download] Destination: Boyce_Avenue_feat._Megan_Nicole_-_Skyscraper_Patrick_Ebert_Edit-n2anDgdUHic.m4a
[download] 100% of 5.92MiB in 00:00
[ffmpeg] Destination: Boyce_Avenue_feat._Megan_Nicole_-_Skyscraper_Patrick_Ebert_Edit-n2anDgdUHic.mp3
ERROR: audio conversion failed: Unknown encoder 'libmp3lame'
~/ytdl $

The informative link is that it too specificies an mp3 failure, so perhaps they two issues are related.

EDIT 2
See answer, all problems solved

A: All problems sorted, thanks
I can now read in AudioSegments from url using BytesIO.
I can now export either mp3 or wav after processing.
ffmpeg issue was solved using the packs recommended here:
http://blog.pogoapp.com/youtube-mp3-with-node-js-and-ffmpeg/ (replacing "nodejs" with my language, "python")
The ffmpeg pack recommended there (https://github.com/jayzes/heroku-buildpack-ffmpeg) already includes the lame support I needed
For some reason, https://github.com/integricho/heroku-buildpack-python-ffmpeg didn't quite do the job for me
I also had to add "ffprobe" into requirements.txt to allow youtube-dl to run properly (I mention that here since it was also previously complaining about lame missing... adding ffprobe was the second step to getting this to work)
Full writeup to my answer is here:https://github.com/rg3/youtube-dl/issues/302#issuecomment-60146845

A: Pydub uses ffmpeg to encode/decode all formats other than wav. So the first issue is getting ffmpeg installed on heroku.
You may find that using heroku run bash you can cd around and find the ffmpeg binary (try in /app/.heroku/vendor).
If that is the case you can explicitly specify where pydub should look like so:
import pydub

pydub.AudioSegment.converter = "/app/.heroku/vendor/ffmpeg/bin/ffmpeg" # or wherever you find it

edit
I was able to get the following to work:
create a requirements.txt in the root directory of an empty git repo.
requirements.txt:
pydub

add this and push to heroku.
the run:
heroku config:add BUILDPACK_URL=https://github.com/integricho/heroku-buildpack-python-ffmpeg.git

then:
heroku run bash

and in the shell
$ which ffmpeg
/app/.heroku/vendor/ffmpeg/bin/ffmpeg

$ python
>>> from pydub import AudioSegment
>>> AudioSegment.silent(5000).export("/tmp/asdf.mp3", "mp3")
<open file '/tmp/asdf.mp3', mode 'wb+' at 0x7ffa8aac0390>

after that ffmpeg is found at: /app/.heroku/vendor/ffmpeg/bin/ffmpeg


text:
Q: Using if statement in lists python shopping = [
    'Garlic',
    'Califlower',
    'Peppper',
    'Slat',
    'Oil',
    'Beer',
    'Toilet Paper',
    'Pizza'
]

for item in shopping:
    print(item)
    if item != 'Mashrum':
        print('we missed Mashrum!')

I want to get one print statement if this condition is false, instead of getting every time when it's looping?

A: You can do
shopping = [ 'Garlic', 'Califlower', 'Peppper', 'Slat', 'Oil', 'Beer', 'Toilet Paper', 'Pizza' ]
if 'Mashrum' not in shopping:
    print('we missed Mashrum!')

That will print you the print statement if 'Mashrum' not in the shopping list.

A: you can use any:
x = any('Mashrum' == item for item in shopping)
if not x:
    print("Mashrum was missed")

redpajama_set_name: RedPajamaStackExchange


text:
Q: why i am receiving this error ? django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" I have created already postgresql database in my local and i already imported it in my settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mytransactiondb',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

when i creating my database in pgadmin 4 i didnt encounter any password. then why i receiving this error?
django.db.utils.OperationalError: FATAL:  password authentication failed for user "postgres"

here is my pgadmin 4

A: One is connecting to the database 'postgres' and one to 'mytransactiondb'.  It is possible you have different authentication methods in your pg_hba.conf for those.  It is also possible you had previously told pgAdmin4 to remember your password.


text:
Q: LEFT SELF JOIN in Rails - Thread Based Private Messaging I am trying to implement one to one thread based private messaging in Rails.
Following is my Message model:
Table name: messages

id                :integer         not null, primary key
sender_id         :integer
recipient_id      :integer
sender_deleted    :boolean         default(FALSE)
recipient_deleted :boolean         default(FALSE)
subject           :string(255)
body              :text
read_at           :datetime
created_at        :datetime
updated_at        :datetime
messagethread_id  :integer

I create a new thread for a new conversation between any two users.
I am using following query to find the latest undeleted message of each thread for a given user (example: with id = 1):
SELECT *
FROM messages LEFT JOIN
          (SELECT *
               FROM messages m3
               WHERE (m3.sender_id = 1 AND m3.sender_deleted = FALSE)
                     OR (m3.recipient_id = 1 and m3.recipient_deleted = FALSE)) AS m2
          ON (messages.updated_at, messages.id) < ( m2.updated_at, m2.id)
                  AND m2.messagethread_id = messages.messagethread_id
WHERE ((messages.sender_id = 1 AND messages.sender_deleted = FALSE) OR (messages.recipient_id = 1 AND messages.recipient_deleted = FALSE)) AND m2.updated_at IS NULL

I would like to implement this in my rails model/controller and display the results on corresponding view.
Can someone please guide on how to get these results in an array of Messages? Thanks in advance!


text:
Q: Mapping JSON String as Postgresql's JSON type with hibernate How should I tell Hibernate to map a String containing a JSON value to PostgreSQL as PostgreSQL's JSON Type ? Assume I have an attribute like this:
private String foo_json_value;

I have used Gson to convert Foo object to a JSON String and now I want to store this attribute in PostgreSQL. I have learned that PostgreSQL has a JSON data type, so I want to use this datatype instead of string (varchar). What JPA annotation or mapping strategy should I use to be able to store this String as JSON directly?


text:
Q: How do I make my Ninject module DRY? I have the the following code in my Ninject modules repeated several times over. What methods and techniques can I use to reduce this repeated code?
public override void Load()
{
    Bind<IDataReader<IList<Price>>>()
        .To<PricesDataReader>().Named("ValDatePrices");
    Bind<IDataConnection<IList<PricesCsvRecord>>>()
        .To<PricesXLConnection>().WhenParentNamed("ValDatePrices")
        .Named("ValDatePricesXLConnection");
    Bind<IDirectoryBuilder>()
        .ToMethod(DefaultValDatePricesDirectory)
        .WhenParentNamed("ValDatePricesXLConnection");

    Bind<IDataReader<IList<Price>>>()
        .To<PricesDataReader>().Named("EDDatePrices");
    Bind<IDataConnection<IList<PricesCsvRecord>>>()
        .To<PricesXLConnection>().WhenParentNamed("EDDatePrices")
        .Named("EDDatePricesXLConnection");
    Bind<IDirectoryBuilder>()
        .ToMethod(DefaultEDDatePricesDirectory)
        .WhenParentNamed("EDDatePricesXLConnection");
}

The main differences occur when requesting an IDirectoryBuilder whose main function is to determine the location of a file based on configuration settings through the use of an IDirectory implementation.
In the example above, I return a DefaultDirectoryBuilder, however I have several other implementations of these (see the EdNrrDirectoryBuilder method) below.
public IDirectoryBuilder DefaultValDatePricesDirectory(IContext arg)
{
    return new DefaultDirectoryBuilder(
         ConfigurationManager.AppSettings["VALDATE_PRICES_DIR"],
         ConfigurationManager.AppSettings["VALDATE_PRICES_FILENAME"]);
}

public IDirectoryBuilder DefaultEDDatePricesDirectory(IContext arg)
{
    return new DefaultDirectoryBuilder(
         ConfigurationManager.AppSettings["EDDATE_PRICES_DIR"],
         ConfigurationManager.AppSettings["EDDATE_PRICES_FILENAME"]);
}

public IDirectoryBuilder EdNrrDirectoryBuilder(IContext arg)
{
    return new ExternalDirectoryBuilder(
         ValuationDate,
         ConfigurationManager.AppSettings["NRRDATE_DIR"],
         ConfigurationManager.AppSettings["NRRDATE_PRICES_FILENAME"]);
}

My issue is that I need values from my configuration files. Right now, all configuration related requests are limited in my Ninject modules.
If I use a Ninject Factory approach to create IDirectoryBuilders, the way I see it is that I will need to have ConfigurationManager  related calls scattered throughout my codebase.
If I use a Ninject Provider approach, I will need providers for all implementations of IDirectoryBuilders, and also updated my constructors and implementations of IDataConnection . My code now also looks like (not very DRY and similar to my current approach).
Bind<IDirectoryBuilder>().ToProvider<DefaultDirectoryBuilderProvider>()
    .WhenParentNamed("EDDatePricesXLConnection")
    .WithConstructorArgument("baseDir", "someConfigValue")
    .WithConstructorArgument("fileName", "someOtherConfigValue");

My code has a very consistent dependency chain at the moment (using NamedArguments): ICalculator->IDataReader->IDataConnection->IDirectoryBuilder - this leads me to believe that there must be some way  to create this chain repeatedly without having to repeat the setup code - which I can not seem  to figure out. There is the added limitation, in that I often require two instances of the same dependency chain - the only difference being different configuration values.

A: There's no reason to rely on any Ninject specific techniques (though in some cases, a Provider may be appropriate (example of a provider here).
The simple answer is that you create extension methods for what the preceding component of the binding expression returns (similar question).

On re-reading your question, I'd suggest looking at Ninject.Extensions.Conventions which hass lots of Bind extension methods that will allow you to do bullk Bindings in the manner you suggest. If it doesn't I'd recommend commenting and identifying the bits you feel it doesn't address.

A: Based on Ruben's comment, this is my current solution. The one thin I did was use the concept of conventions, thus retrieving my Config settings became easier. This filtered through most of the other code that used Ninject Named parameters.
public void Load(){
    BindDependencies<IDataReader<IList<Price>>, PricesDataReader
      , IDataConnection<IList<PricesCsvRecord>>, PricesXLConnection
      , DefaultDirectoryBuilder>
      ("ValDatePrices");

    BindDependencies<IDataReader<IList<Price>>, PricesDataReader
      , IDataConnection<IList<PricesCsvRecord>>, PricesXLConnection
      , DefaultDirectoryBuilder>
      ("EDDatePrices");
       // etc etc
}

 public void BindDependencies<
     TReaderBase, TReaderImpl,
     TDataConnectionBase, TDataConnectionImpl,
     TDirectoryBuilderFactoryImpl>
     (string baseName)
         where TReaderImpl : TReaderBase
         where TDataConnectionImpl : TDataConnectionBase
 {
     DirectoryBuilderInfo dirInfor = GetSettings(baseName);

     Bind<TReaderBase>()
           .To(typeof(TReaderImpl))
           .Named(baseName);
     Bind<TDataConnectionBase>().To(typeof(TDataConnectionImpl))
            .WhenParentNamed(baseName)
            .Named(baseName + "XLConnection");
     Func<IDirectoryBuilder> directoryBuilder = CreateDirectoryBuilderFunc<TDirectoryBuilderFactoryImpl>(dirInfor);

     Bind<IDirectoryBuilder>()
            .ToMethod(d => directoryBuilder())
            .WhenParentNamed(baseName + "XLConnection");
    }

private Func<IDirectoryBuilder> CreateDirectoryBuilderFunc<TDirectoryBuilderFactoryImpl>(DirectoryBuilderInfo dirInfor)
{
    Func<IDirectoryBuilder> directoryBuilder =
         () => CreateDefaultDirectoryBuilder(dirInfor.BaseDirectory, dirInfor.FileName);

    if (typeof(TDirectoryBuilderFactoryImpl) == typeof(RiskDirectoryBuilderFactory))
    {
        directoryBuilder =
         () => CreateRiskDirectoryBuilder(ValuationDate, dirInfor.BaseDirectory, dirInfor.FileName);
    }
    return directoryBuilder;
}

private DirectoryBuilderInfo GetSettings(string baseName)
{
    var settingsName = baseName.ToUpperInvariant();
    return new DirectoryBuilderInfo()
    {
        BaseDirectory = ConfigurationManager.AppSettings[settingsName + "_DIR"],
        FileName = ConfigurationManager.AppSettings[settingsName + "_FILENAME"]
     };
 }


text:
Q: Rails - HAML "surround" for !IE I am doing a rails app and I found bit issue following what @matt suggested in his answer, I am finding below issues:
HAML
!!!
= surround ''.html_safe, ''.html_safe do
  %html.no-js{:lang => 'en'}
  %head
  %body

Here is how the browser render the HTML (without ending  tag at very end and adds it at declaring line itself)
<!DOCTYPE html>

..
..

So, here is the code that's working fine for me, but is there a way to make above code work ?
!!!
:plain

%html.no-js{:lang => 'en'}
  / <![endif]

A: Not sure if it's causing the problem, but head and body should be inside the html tag.
!!!
= surround ''.html_safe, ''.html_safe do
  %html.no-js{:lang => 'en'}
    %head
    %body

Could be confusing the surround method by having multiple tags appended instead of nested...  Worth a try!


text:
Q: How to fix "Illegal datatype context" (use -XDatatypeContexts)? I am a new learner of Haskell, my code is as follows:
data Num a=>Units a = Units a (SymbolicManip a )

      deriving (Eq)

I am not sure how to fix it?
Anyone can help me?

A: Typeclass contexts in datatypes are now regarded as a not so useful feature. The problem is that the following does not compile:
foo :: Units a -> a
foo (Units x _) = x+x

This intuitively should compile, since the Units a argument can only be constructed for a type a satisfying Num a. So, on destruction (pattern matching) one should be able to access the Num a instance. However this is not the case, and a Num a must be counterintuitively provided on destruction as well:
foo :: Num a => Units a -> a
foo (Units x _) = x+x

The standard suggestion is therefore to remove the constraint Num a from the Units a datatype declaration, and add it instead to every function involving Units a.
Another option is to enable GADTs and change the datatype to:
data Units a where
   Units :: Num a => a -> SymbolicManip a -> Units a

This does the "right" thing: a Num a instance is required to construct a value, and is instead provided on destruction. In this way, the first foo declaration above will be well-typed.

I almost forgot the "quick & dirty" option, which is to enable the obsolescent datatype context feature: this is done by adding at the beginning of your file the line
{-# LANGUAGE DatatypeContexts #-}

Still, I would rather modify the code than to enable this language extension.


text:
Q: Find files less than 1 week old with match TODO in files My unsuccessful proposal
find ./ -newerct '1 week ago' -print | grep TODO

No output although should be.
Files are text files like
Lorem
% TODO check this out
Lorem ipsun

How can you find less than 1 week old files matching TODO?
Output should be the line after TODO.
Perl solution is also welcome, since I am practising it too.

A: Change this:
find ./ -newerct '1 week ago' -print | grep TODO

to this:
find ./ -newerct '1 week ago' -exec grep TODO {} +

or this:
find ./ -newerct '1 week ago' -print | xargs grep TODO

Explanation
Your grep doesn't interpret the output of find as a list of files to search through, but rather as its input. That is, grep tries to match TODO in the names of files rather than their contents.
From the grep(1) man page:

grep  searches the named input FILEs (or standard input if no files are
         named, or if a single hyphen-minus (-) is given as file name)

To match the line after TODO:
find ./ -newerct '1 week ago' -exec grep -A1 TODO {} + | grep -v TODO

This assumes you have GNU grep.

A: Try this
find . -type f -ctime -7 -print | grep -R "TODO" /etc/

-type f  -type f to list only files
-ctime -7 is for files with a created time less than 7 days old

A: You can use that:
find ./ -type f -newerct '1 week ago' -exec sh -c "grep -H -A1 TODO {} | tail -1" \;

Explanation:

*

*-type f: includes only files in the search pattern

*-exec sh -c "...": executes ... for all found files

*grep -H -A1 TODO {} | tail -1: -H prints the filename, -A1 prints the line after the match, and tail -1 deletes the first line (the line with TODO) out of the output.


text:
Q: Issue with using Ably in Doze mode I use Ably API as a way to communicate between two Android devices (mobile phones). The first one is a "Master" which sending a request to the second ("slave"). the main part of "Slave" is background service which is awaiting for the command from the master. As soon as a request from the master arrives, the slave gets its geo-location and sends it back to the master. The trouble is that while the slave is in the doze mode Ably doesn't work ('onMessage' method doesn't work) until I wake the phone up. At the same time, if I use sms reciever (onRecieve method of  mainBroadcastReceiver) with the service of "slave" it works fine even when the phone is "asleep".
Is there any ideas how to resolve that issue? Here is the code of my Service.
package ru.volganap.nikolay.kids_monitor_ably;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.util.Log;
import android.app.Service;
import android.os.IBinder;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import androidx.core.app.NotificationCompat;

import io.ably.lib.realtime.AblyRealtime;
import io.ably.lib.realtime.Channel;
import io.ably.lib.realtime.CompletionListener;
import io.ably.lib.types.AblyException;
import io.ably.lib.types.ErrorInfo;
import io.ably.lib.types.Message;

public class KidService extends Service implements KM_Constants {*emphasized text*
    private SharedPreferences sharedPrefs;
    BroadcastReceiver mainBroadcastReceiver;
    private String parent_sender;
    FindGeoPos fg;
    private NotificationManager notificationManager;

private static final int NOTIFY_ID = 101;
private static final String NOTIFY_CHANNEL_ID = "CHANNEL_ID";
public static final int DEFAULT_NOTIFICATION_ID = 101;
private Channel channel;

public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "Service: onCreate");
    //EventBus eventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();
    sharedPrefs = getSharedPreferences(PREF_ACTIVITY, MODE_PRIVATE);
    notificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
    try {   //Init ABLY
        AblyRealtime ablyRealtime = new AblyRealtime(ABLY_API_KEY);
        channel = ablyRealtime.channels.get(ABLY_ROOM);
        channel.subscribe(PARENT_PHONE, new Channel.MessageListener() {
            @Override
            public void onMessage(Message messages) {
                Log.d(LOG_TAG, "Service - Ably message received: " + messages.data);
                if (messages.name.equals(PARENT_PHONE) && messages.data.equals(getResources().getString(R.string.parent_sms))) {
                    getPosition();
                }
            }
        });
    } catch (AblyException e) {
        e.printStackTrace();
    }
}

@SuppressLint("MissingPermission")
public int onStartCommand(Intent intent, int flags, int startId) {
    if (startId > 1) {
        stopSelf(startId);
    }
    Log.d(LOG_TAG, "Service: onStartCommand, starId = " + startId + ", flags = " + flags);
    //Send Foreground Notification
    sendNotification("KMService","");

    if (!EventBus.getDefault().hasSubscriberForEvent(KidService.class)) {
        EventBus.getDefault().register(this);
    }
    //Init SMS Receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_FROM_BR);
    mainBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                parent_sender = intent.getStringExtra("sender");
                Log.d(LOG_TAG, "Service: Get back with Sender-parent");
                getPosition();
            }
        }
    };
    registerReceiver(mainBroadcastReceiver, filter);
    return START_STICKY;
}

public void sendNotification(String Title,String Text) {

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    //notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationIntent.setAction(Intent.ACTION_MAIN);
    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), NOTIFY_CHANNEL_ID)
                    .setOngoing(true)
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(contentIntent)
                    .setContentTitle(Title)
                    .setContentText(Text);
                    //.setPriority(PRIORITY_HIGH);

    createChannelIfNeeded(notificationManager);
    Notification notification = builder.build();
    //notificationManager.notify(NOTIFY_ID, notification);
    startForeground(NOTIFY_ID, notification);
}

public static void createChannelIfNeeded(NotificationManager manager) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFY_CHANNEL_ID, NOTIFY_CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(notificationChannel);
    }
}

// Find the location
protected void getPosition () {
    if (isLocationEnabled()) {
        Log.d(LOG_TAG, "Service: new FindGeoPos call");

        Handler handler = new Handler(Looper.getMainLooper());
        Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                fg = new FindGeoPos(getBaseContext());
            }
        };
        handler.post(myRunnable);
    } else {
        Toast.makeText(getApplicationContext(), "Service: Please turn on your location", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
        Log.d(LOG_TAG, "Service: Please turn on your location");
    }
}

private boolean isLocationEnabled() {
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

@Subscribe//(threadMode = ThreadMode.MAIN)
public void onEvent(EventBus_Kid event){
    Log.d(LOG_TAG, "Service: EventBus is worked, position is:  " + event.location_message);
    fg = null;
    parent_sender = sharedPrefs.getString(PARENT_PHONE, "" );

    try { // ABLY PUBLISH a message
        channel.publish(KID_PHONE,  event.location_message, new CompletionListener() {
            @Override
            public void onSuccess() {
                Log.d(LOG_TAG,"Service - onSuccess - Message sent");
            }

            @Override
            public void onError(ErrorInfo reason) {
                Log.d(LOG_TAG,"Service - onError - Message not sent, error occurred: " + reason.message);
                sendSMSMessage (parent_sender, event.location_message);
            }
        });
    } catch (AblyException e) {
        Log.d(LOG_TAG,"Service - AblyException - Message not sent: " + e.toString());
        sendSMSMessage (parent_sender, event.location_message);
    }
    //OkHttp is starting
    String user = KID_PHONE;
    OkHttpRequest serverReguest = new OkHttpRequest();
    serverReguest.serverGetback(user, event.location_message);
}

protected void sendSMSMessage (String phoneNo, String message) {
    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
        Log.d(LOG_TAG, "Service: SMS sent to number: " + phoneNo + " with message: " + message);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),"SMS faild, please try again later", Toast.LENGTH_LONG).show();
        e.printStackTrace();
        Log.d(LOG_TAG, "Service: SMS failed. SMS Exception: " + e.toString());
    }
}

public void onDestroy() {
    super.onDestroy();
    Log.d(LOG_TAG, "Service: onDestroy");
    unregisterReceiver(mainBroadcastReceiver);
    EventBus.getDefault().unregister(this);
    channel.unsubscribe();
    notificationManager.cancel(DEFAULT_NOTIFICATION_ID);
    stopSelf();
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return null;
    //throw new UnsupportedOperationException("Service: Not yet implemented");
}

}

A: Ably Engineer here.
The issue here is mostly to do with the way android handles services when the app is not in the foreground. Using Ably helps but we cant stop the OS pausing that thread :D.
SMS's are not handled in the same way by the device, the system is not under user-space control. They'll be received no matter what and then your application can handle them.
In this post There is an answer about websockets in a background thread/task. and its more or less the correct way to go about it.
There are a few examples out there about how to do this on android in flutter:
https://medium.com/stuart-engineering/keep-flutter-running-background-on-android-6ffc85be0234


text:
Q: How to fetch Oauth Token for Openshift Server for login I am trying to  fetch the OAuth token from Openshift enterprise  Server . I was looking into may reference and found we have to use the below  endpoint ,
<namespace_route>/oauth/authorize , Like
https://oauth-openshift.apps.domain.com/oauth/authorize?client_id=openshift-browser-client&response_type=token
Do anyone have a correct Java API or REST API example how to achieve the token.
When I tried executing this below Curl command I got this error
curl -u user:pass -H "X-CSRF-Token: 100" 'https://oauth-openshift.apps.domain.com/oauth/authorize?client_id=openshift-browser-client&idp=Azure_AD&response_type=token'
Error
Error: lookup of user for "system:c3ZlbGx1dmE" failed: useridentitymapping.user.openshift.io "system:c3ZlbGx1dmE" not found
Can you help me by sharing  the reference how to achieve this Token using JAVA?


text:
Q: Backbone model parsing in collection.fetch and collection.create In my Backbone powered app, I am utilizing REST functions. On the back-end, its PHP. I am using a particular response structure for any REST calls made to the server. The response type is like this:
$response = array(
    "success" => // true/false,
    "data" => // can be an array or a value
    "message" => // a string
)

I have a model called team_member and a collection called team_members. When the team_members.fetch() is called, the server responds (in a successful case) like this:
$response = array(
    "success" => // true
    "data" => array(
          array (some member data),
          array (some member data),
          array (some member data)
     ),
    "message" => "Found 3 members"
)

The problem is that that when a single model is fetched, I still want to respond like the above style and not just send the array of member data. But when I do this, it doesn't work well because in collection.fetch() the array is different.
What is the best way to resolve this issue keeping in mind that I want the back-end response style to be consistent, whether its a single model or a collection. I hope I explained well. Thanks.

A: Okay I solved this. I can call collection.fetch({ parse: false }). This does call the parse method on the collection but suppresses the parse on each model. Hence, I was able to use the model.parse() function when I create/update a particular model.


text:
Q: OmniAuth and Oauth2 gem to auth with one site and access another I have two apps which share the same secret and I authenticate using one of them, like so:
  def oauth_client
    @oauth_client ||= OAuth2::Client.new(ENV["OAUTH_ID"], ENV["OAUTH_SECRET"], site: 'http://accounts.ourco.com')
  end

  def access_token
    if session[:access_token]
      @access_token ||= OAuth2::AccessToken.new(oauth_client, session[:access_token])
    end
  end

is there a way to use the same oauth_client to access the "http://data.ourco.com" server for example?
I can then do the rest with having to cross authenticate the sessions in the background between data and accounts servers.


text:
Q: R: Writing loops to replace NULL with Dates The Here is an example of my table:
custID | StartDate | EndDate   | ReasonForEnd  | TransactionType | TransactionDate
    1a |  NULL     | 2/12/2014 | AccountClosed |  AccountOpened  |  1/15/2004
    1a |  NULL     | 2/12/2014 | AccountClosed |  Purchase       |  3/16/2004
    .......
    2b | 7/7/2011  | 6/14/2013 | AccountClosed | AccountOpened   |  8/1/2010

The problem has to do with the StartDate field. For each custId, if the entry is NULL then I want to replace with the TransactionDate where TransactionType = AccountOpened. If StartDate is after the TransactionDate where TransactionType = AccountOpened, then replace with this date.
The actual data is over 250,000 rows. I really need some help figuring out how to write this in R.

A: You could try the following, however I didn't test it yet. I assume your data.frame is called df:
require(dplyr)

df %>%
    mutate_each(funs(as.Date(as.character(., format="%m/%d/%Y"))),
                StartDate, EndDate, TransactionDate) %>%
    group_by(custID) %>%
    mutate(StartDate = ifelse(is.na(StartDate) | StartDate > TransactionDate[TransactionType == "AccountOpened"],
                          TransactionDate[TransactionType == "AccountOpened"], StartDate))

This code first converts several columns to Date format (in this step, NULL entries will be converted to NA), groups by custID and then checks if StartDate is either NA or greater than TransactionDate where TransactionType == "AccountOpened" and if TRUE, replaces StartDate with TransactionDate where TransactionType == "AccountOpened".


text:
Q: NSToolbar with custom views Hi so I've got a problem that i can't really figure out what the cause is. I made an app so far that has a NSToolbar that has custom views in it so that you can switch between views on the toolbar (just like safari's preference window toolbar views). I was using CCodings tutorial on youtube but i have the problem of the views moving by themselves, for example i click on view 1 and when i click on view 2 view one changes and the view moves up so that you can only see half of when i put on the view, I'm using Xcode 6 and OS X 10.10 so i don't know if that would be one cause but i thank you in advance if you can help me, heres the MainWindowController.m file:
Also the views should be setup correctly
-(NSRect)newFrameForNewContentView:(NSView*)view {
    NSWindow *window = [self window];
    NSRect newFrameRect = [window frameRectForContentRect:[view frame]];
    NSRect oldFrameRect = [window frame];
    NSSize newSize = newFrameRect.size;
    NSSize oldSize = oldFrameRect.size;

    NSRect frame = [window frame];
    frame.size = newSize;
    frame.origin.y -= (newSize.height - oldSize.height);

    return frame;

}

-(NSView *)viewForTag:(int)tag {

    NSView *view = nil;
    switch (tag) {
    case 0:
    view = smallView;
    break;
    case 1:
    view = mediumView;
    break;
    case 2: default:
    view = largeView;
    break;

    }

    return view;

}

- (BOOL)validateToolbarItem:(NSToolbarItem *)item {

    if ([item tag] == currentViewTag) return NO;
    else return YES;
}

-(void)awakeFromNib {

    [[self window] setContentSize:[smallView frame].size];
    [[[self window] contentView] addSubview:smallView];
    [[[self window] contentView] setWantsLayer:YES];

}

-(IBAction)switchView:(id)sender {
    int tag = [sender tag];
    NSView *view = [self viewForTag:tag];
    NSView *previousView = [self viewForTag:currentViewTag];
    currentViewTag = tag;

    NSRect newFrame = [self newFrameForNewContentView:view];

    [NSAnimationContext beginGrouping];

    if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask)
    [[NSAnimationContext currentContext] setDuration:1.0];

    [[[[self window] contentView] animator] replaceSubview:previousView with:view];
    [[[self window] animator] setFrame:newFrame display:YES];

    [NSAnimationContext endGrouping];

}

A: Seems that you also need to change NSWidnow frame apart from contenView.
Also as for me for switching views by click events its better to use NSTabView.


text:
Q: Data reading and writing in a RFID chip through iphone application I am trying to make an app Which can transfer some points to an RFID chip. RFID chip will store the data. Then an other iPhone with my app will receive the stored points wirelessly.
Is it possible to write some data in some RFID chip like (Mifare S50 chip) through my ios application and then read it back from a other iphone using my application? Please guide me with some reference or link.

A: If you only have an iPhone (without any RFID/NFC reader adapter), the answer is no. Current iPhones (we will see what features the iPhone 6 will bring us in that direction ...) do not have the necessary hardware to interact with MIFARE Classic chips (which -- in your case -- would be a 13.56 MHz iductive-coupling proximity reader with MIFARE Classic crypto support).
If your iPhone already has an NFC (or RFID) reader adapter, the answer depends on what specific adapter you use.

EDIT: As of today, this answer partially(!) applies to iPhone 6 (also see this question). The iPhone 6 has the necessary hardware to access such cards (i.e. an NFC controller chip from NXP), however there is no API that provides access to NFC reader/writer functionality. Moreover, there is doubts that the antenna boosting circuitry permits using the iPhone in reader/writer mode.


text:
Q: Arkhangel'skii's definition of cardinal function I was searching an article written by A. V. Arkhangel'skii called A theorem on Cardinality. I found it but there is a little problem: the article is in Russian. I can't read Russian and I need the definitions in the article. Particularly, the definition of the cardinal function $\text{qL}$. Here is the definition

I really aprecciate any help you can provide me.

A: I could guess from my minimal Russian but this paper confirms it, it's the quasi-Lindelöf number of $X$: the minimal infinite cardinality $\tau$ such that for all closed subsets $C$ of $X$ and all open covers $\mathcal{U}$ of $C$ (so that $C \subseteq \bigcup \mathcal{U}$) there is a subfamily $\mathcal{U}' \subseteq \mathcal{U}$ such that $|\mathcal{U}'| \le \tau$ and $C \subseteq \overline{\bigcup \mathcal{U}'}$.
(note that Arhangel'skij uses $[]$ for closure looking at the formula in the paper).


text:
Q: variable undefined in inner query in laravel 5.4 I'm new in laravel, and I have a problem in the controller..
I need to retrieve one row from a table that specified my condition, then I need to join the result with two tables.
I try to write this code, but I have this error [ Undefined variable: coursenum ]
public function stafflogin (Request $request) {$jobid=$request->input('jobID');
$coursenum=$request->input('referenceNumber');
$semester=$request->input('semester');
$checklogin=DB::table('members')->select('jobID')->where(['jobID'=>$jobid])->get();

this is the query:
if(count($checklogin)>0){ $users=DB::table('members_courses_assign')->join('members','members.externalPersonKey','=','members_courses_assign.externalPersonKey')
   ->whereIn('referenceNumber', function($query)
   {
       $query->select(DB::raw(1))
             ->from('courses')
             ->where(['referenceNumber'=>$coursenum,'termkey'=>$semester])->get();
   })
  ->where(['jobID'=>$jobid]) ->get();

A: please try something like this :
->whereIn('referenceNumber', function($query) use ($coursenum, $semestre)
{
        // put yout code here
})


text:
Q: Controlling CodeModel's code output formatting: putting lines between namespace declarations I'm making some experiments with Visual Studio's CodeModel. I tried creating a file with two namespaces in there through VS's Code Model:
CodeModel codeModel = projItem.ContainingProject.CodeModel;
codeModel.AddNamespace("Namespaces.FirstNamespace", "namespacestest.cs");
codeModel.AddNamespace("Namespaces.SecondNamespace", "namespacestest.cs");

the output of such code is:
//file namespacestest.cs
namespace Namespaces.FirstNamespace {
}
namespace Namespaces.SecondNamespace {
}

Which is almost what I'm looking for. The only catch here is that I'd like to control the spacing: having at least one line between the first and the second namespace. Does by chance anyone know of a way of achieving this?
This is what I want:
//file namespacestest.cs
namespace Namespaces.FirstNamespace {
}

namespace Namespaces.SecondNamespace {
}

Thanks

A: The statement codeModel.AddNamespace will return you an object of CodeNamespace.
you can find the EditPoint of the namespace using the your first namespace and then insert a line like this.
CodeNamespace yournamespace = codeModel.AddNamespace(....);
EditPoint2 endEditPoint = yournamespace.GetEndPoint(vsCMPart.vsCMPartWhole).CreateEditPoint();
endEditPoint.InsertNewLine(1);

I am not sure whether this will put the line at the place you want but the idea is to get the EditPoint and then use it to insert the line.


text:
Q: Tag GTM in body My tag GTM in the body is not properly installed because outside the body section. I'm very new in coding, so I'm sorry for this question but how to insert the code noscript correctly in body section ?
Thanks a lot
Here the code :
    <body<?php body_class( mk_get_body_class( global_get_post_id() ) ); ?> <?php echo get_schema_markup( 'body' ); ?> data-adminbar="<?php echo is_admin_bar_showing(); ?>">

    <?php
        // Hook when you need to add content right after body opening tag. to be used in child themes or customisations.
        do_action( 'theme_after_body_tag_start' );
    ?>

            <div id="mk-theme-container" <?php echo is_header_transparent( 'class="trans-header"' ); ?>>

                <?php
                mk_get_header_view( 'styles', 'header-' . get_header_style() );

A: That appears to only contain the fallback GTM code for users without JavaScript. You should have an additional JavaScript snipped to place on your page that's completely missing from the above example?
See their documentation here for reference (you're missing section #1):
https://developers.google.com/tag-manager/quickstart


text:
Q: VBA - Sending Emails Through Outlook Based on Cell Data I've been failing miserably trying to write code for this, so I'd be happy if someone could help me create a macro in excel. I'm looking to send a bunch of users access credentials through outlook based off data I add to excel. Specifically, I have two worksheets:
1) Email Information (all static)
This contains:

*

*Email Subject in cell C5

*Email Body in Cell C6 (Essentially this says Hello, your user credentials are below)

*Additional Email Body in Cell C7 (This portion would say something along the lines of "please let us know if you have any questions") Both cells C6 and C7 can of course be updated to include any language

2) User Information (number of users can vary)
This contains:

*

*Column A - First Name

*Column B - Last Name

*Column C - Full Name (Not really needed)

*Column D - Email Address

*Column E - Password

Ideally, the macro would be able to look at the user information and create a new, separate email from outlook for every email address from column D with the following format:

*

*Email To: email addresses in cell D2 until last email (User Information worksheet)

*Email Subject: Cell C5 in Email information worksheet

*"Hi" Firstname value from column A in User Information worksheet

*Email Body Part 1 from cell C6 in Email Information worksheet

*Username: which is the email address from column D (same as email recipient)

*Password: from column E in User Information worksheet

*Email Body PArt 2 from cell C7 in Email Information worksheet

Hope someone has the time to help me out.
Thanks in advance!!
EDIT
Thanks for the help, Barry. Here is my code as I'm trying to reference two different worksheets. Can you let me know what I'm doing wrong?
Sub GenerateEmail()
Dim sEmailBodyp1 As String
Dim sEmailBodyp2 As String
Dim sEmailSubject As String
Dim sEmailTo As String
Dim sFirstName As String
Dim sPassword As String
Dim OutApp As Object
Dim OutMail As Object
Dim EmailSheet As Worksheet
Dim UserSheet As Worksheet
Dim UsedRange As Range

Set EmailSheet = Sheets("Email Information")
Set UserSheet = Sheets("User Information")
Set sEmailSubject = EmailSheet.Cells("C5")
Set sEmailBodyp1 = EmailSheet.Cells("C6")
Set sEmailBodyp2 = EmailSheet.Cells("C7")
Set UsedRange = UserSheet.UsedRange

For Each Row In UsedRange.Rows
    sFirstName = Row.Columns(1)
    sEmailTo = Row.Columns(4)
    sPassword = Row.Columns(5)
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .To = sEmailTo
        .Subject = sEmailSubject
        .Body = "Hi " + sFirstName + "," + vbCrLf + vbCrLf + sEmailBodyp1 + vbCrLf + vbCrLf + "Username: " + sEmailTo + vbCrLf + "Password: " + sPassword + vbCrLf + vbCrLf + sEmailBodyp2
        .Display
    End With

    Set OutMail = Nothing
Next

Set OutApp = Nothing

End Sub

A: Based on discussions this is my edit for this solution.
Excel Macro
Public Sub GenerateEmail()
Dim sEmailBodyp1 As String
Dim sEmailBodyp2 As String
Dim sEmailSubject As String
Dim sEmailTo As String
Dim sFirstName As String
Dim sPassword As String
Dim OutApp As Object
Dim OutMail As Object
Dim EmailSheet As Worksheet
Dim UserSheet As Worksheet
Dim UsedRange As Range

Set EmailSheet = Sheets("Email Information")
Set UserSheet = Sheets("User Information")

sEmailSubject = EmailSheet.Range("C5").Value
sEmailBodyp1 = EmailSheet.Range("C6").Value
sEmailBodyp2 = EmailSheet.Range("C7").Value

Set UsedRange = UserSheet.UsedRange

For Each Row In UsedRange.Rows.Offset(1, 0).Resize(UsedRange.Rows.Count - 1, UsedRange.Columns.Count)

        sFirstName = Row.Columns(1)
        sEmailTo = Row.Columns(4)
        sPassword = Row.Columns(5)
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)

        With OutMail
            .To = sEmailTo
            .Subject = sEmailSubject
            .Body = "Hi " + sFirstName + "," + vbCrLf + vbCrLf + sEmailBodyp1 + vbCrLf + vbCrLf + "Username: " + sEmailTo + vbCrLf + "Password: " + sPassword + vbCrLf + vbCrLf + sEmailBodyp2
            .Display
        End With

        Set OutMail = Nothing

Next

Set OutApp = Nothing
End Sub


text:
Q: ColdFusion/SQL : ELEMENT XXX IS NOT DEFINED IN FORM I have a form on my cfm page, that is to insert a new row into an SQL datasource.  The cfm page hosts the form - and when submitted the -action.cfm page inserts the data and relocates the user to a page listing the new information.  The problem I am getting is when I submit the form I am getting:: Element NEWUSERID is undefined in FORM.
the form on the insertScores.cfm page:
<form method="post" action="insertScores-action.cfm">

    User ID
    <input name="newUserID" type = "text" size = "50">

    First Name
    <input name="newFirstName" type="text" size="50">

    Last Name
    <input name="newLastName" type="text" size="50">

    Email
    <input name="newEmailAdd" type="text" size="50">

    Score
    <input name="newScore" type="text" size="50">

    Pass Date
    <input name="newPassDate" type="text" size="50" value="dd/mm/yyyy">

    Level
    <input name="newLevel" type="text" size="50">

    <input type="submit" value="Insert Scores">

The insertScores-action.cfm page
<cfquery name="insertScores" datasource="staffwrite">
INSERT INTO protinfo_scores (
  userID
  , first_name
  , last_name
  , email
  , curr_score
  , curr_score_date
  , level
  )
VALUES (
    '#form.newUserID#'
  , '#form.newFirstName#'
  , '#form.newLastName#'
  , '#form.newEmailAdd#'
  , '#form.newScore#'
  , '#form.newPassDate#'
  , '#form.newLevel#'
  )
</cfquery>

<cfquery name = "queryScore" datasource="staff">
  SELECT userid, level
  FROM protinfo_scores
  WHERE userid LIKE '#form.newUserid#'
  AND level = '#form.newLevel#'
</cfquery>

<cflocation URL="newScore.cfm?userid=#url.userid#&level=#url.level#">

newScore.cfm

Your ammendments have been made.

<cfquery name = "queryScore" datasource="staff">
  SELECT first_name, last_name, email, curr_score, curr_score_date, userid, level
  FROM protinfo_scores
  WHERE userid LIKE '#URL.userid#'
  AND level = #URL.level#
</cfquery>

<cfoutput query="queryScore">

    Name
    #queryScore.first_name# #queryScore.last_name#

    Email
    #queryScore.email#

    Username
    #queryScore.userid#

    Level
    #queryScore.level#

    Current Score
    #queryScore.curr_score#

    Date Passed
    #queryScore.curr_Score_date#

</cfoutput>

A:
and when submitted the -action.cfm page inserts the data and relocates
  the user to a page listing the new information

I can't tell from the wording if this is the desired effect or the actual effect.  If it is the actual effect, your error is occurring on newScore.cfm which would make sense because the data in the form scope does not persist after the cflocation and you're trying to use form.newUserID after the output table..
If this is the desired effect and NOT the actual effect...

*

*As Dan said, you're looking at two different files.  You show code from insertScores-application.cfm but your action is pointing to insertScores-action.cfm.

*The code in your question is not exact copy/paste or even all of your code (you're missing a </form> tag to say the least).  In this case I'd suggest showing us the actual code AND the error message. Many times I see element XXX is undefined in FROM (notice it says FROM and not FORM, something easy to miss when you're staring at the same thing for hours).  The error message will tell you what line number the error is on.  Is the line number actually among the code you posted?

A: I changed my <form></form> to a <cfform></cfform> and all now appears to work swimmingly.  I was under the impression this would not make any difference but clearly it does.


text:
Q: Read from an external bluetooth keyboard without UITextField I need to read text from an external bluetooth keyboard (an Inateck barcode scanner) on iOS. I'm searching for a solution without using an hidden UITextField like a listener ?

A: I had the same problem with an external keyboard (although read text from BUSICOM Desktop 1D/2D/QR Code Reader through a cable instead of Bluetooth).
My solution is to implement UIKeyInput for the UIViewController.
Swift 5.1:
// MARK: - UIKeyInput
let keyboardHiderView = UIView()
extension QRScannerViewController: UIKeyInput {
    override var canBecomeFirstResponder: Bool { true }
    var hasText: Bool { false }

    override var inputView: UIView? {
        return keyboardHiderView
    }

    func insertText(_ text: String) {
        // Character by character input in here
    }

    func deleteBackward() {}
}

Hoping to help someone.

A: Unfortunately there is no lower-level API to intercept keystrokes on iOS.  If your barcode scanner emulates a keyboard (HID Profile) then your only option is to pair it as a keyboard and direct input into a UITextField.  This text field can be hidden as you point out.


text:
Q: Make screenshot of url When user posts some url, I need to make screenshot of the url content. What .NET library can I use for that?

A: awesomium  is made for this

A: How about using the Selenium WebDriver? It works from .NET and is quite easy:
var browser = new InternetExplorerDriver();
browser.Navigate().GoToUrl("http://example.com");
browser.GetScreenshot().SaveAsFile(filename, ImageFormat.Png);
browser.Quit();

A: You can use System.Windows.Forms.WebBrowser for this purposes.
You create WebBrowser instance. Then navigate to url and in OnDocumentComplete you can call DrawToBitmap method.
Hope this helps you.

A: Just to mention another option, you could use thumbnail services like:
http://www.thumbalizr.com/
http://webshotspro.com
Thumalizr's sreenshot of this page looks decent and didn't take too long to generate:


text:
Q: React Native app opens and closes quickly after installation on ios simulator I've been developing an App using React Native and when I switched to a Mac environment to set up the configurations for ios, after all the setup has been done, the app opens very quickly and closes after the installation, showing that powered by react native screen. I noticed that in my packager screen, the line from the bundle which shows a progress of how much has been loaded does not appear, as if it has never been loaded. Same thing happens if I try to run the code from Xcode.
Here is the screen I'm talking about, for a test project I started for comparisson purposes:

And here is the same screen for my App, without the progress indicator being displayed:

I tried following some solutions provided by the comunity for similar issues but none of them worked. Note that no error message is displayed in my terminal window, as if the build and installation has been succesfull.
Can someone help me with this one? I've been strugling with this App for quite some time, as react native always seems to crash and display error messages for me. Any help would be much appreciated :)
Edit: forgot to mention that I'm trying to run the app on the simulator since I don't have an actual device.

A: Some solutions ...

*

*If you are in latest react version then try to downgrade it.

*Re-start your application and try to run again.

*Delete node modules folder and run using npm install.

*Try to open project using XCODE and build through it.
Most probably the problem is with your react version. Try to downgrade to stable react version and try

A: Exactly this problem happened to me yesterday when I too installed react-native-firebase. I ran react-native run-ios and the app closed as soon as it opened without any specific errors.
I decided to run the app from Xcode, so I opened the Xcode project. To be more precise I opened the <Project>.xcworkspace because I installed CocoaPods. And there inside the logs I when trying to run the app I found the error. It said that the GoogleService-Info.plist was not found. And as I was looking through the Xcode workspace I did not see the file there, although it existed under /ios/<Project>/ in my IDE (VSCode). So maybe just a syncing problem.
So basically I added the file in Xcode as well, re-run and app was running fine.
Of course, I have no idea if I can find some sort of credible sources about this, but this exact issue happened to me under the exact same circumstances as yours.

A: Check the log for errors, run react-native log-ios on the terminal and monitor it for errors.
or you can enable Debug JS Remotely option from the simulator by pressing command+D and check the console for errors.

A: Try to use adb logcat *:E, this will be helpful when you trying to find issues not related js.

A: I depends on the version of your react-native, if you are using its latest version , 0.56.0 (for now) it has a known issue, which you can see here, and it is suppose to be fixed in next version 0.57.0
https://github.com/facebook/react-native/issues/19953
although the issue raised for android version, but it has similar issue in ios
(the latest comment, provides more info about the error)
for now the possible fix is to downgrade to 0.55.4 or 0.55.0
if this couldn't solve your issue, Please provide more  information about your app with adding package.json and build.gradle info to the question

A: Add firebase crashlytics or open again and again that app, so it navigates to the log screen to find the issue. Mainly it caused by the misconfigured pod settings. So please check your Podfile. because all the other errors are comes in app's internal error console. I'm attaching the Non error formed Podfile for your reference. It's only the example
Podfile
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
platform :ios, '12.0'

target 'iospodapp' do
  config = use_native_modules!
  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-LocationAlways', :path => "#{permissions_path}/LocationAlways.podspec"
  pod 'Permission-LocationWhenInUse', :path => "#{permissions_path}/LocationWhenInUse.podspec"
  pod 'Permission-MediaLibrary', :path => "#{permissions_path}/MediaLibrary.podspec"
  pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications.podspec"
  pod 'Permission-PhotoLibrary', :path => "#{permissions_path}/PhotoLibrary.podspec"

  pod 'YogaKit'
  pod 'Firebase/Performance'
  pod 'Firebase/Messaging'
  pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'
  pod 'react-native-orientation', :path => '../node_modules/react-native-orientation'
  pod 'RNFS', :path => '../node_modules/react-native-fs'

  target 'iospodappTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.

  use_flipper!()

  post_install do |installer|
    flipper_post_install(installer)
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'
       end
    end
  end
end

Note:

*

*If you're using the firebase, don't forget to add the GoogleService-Info.plist into your ios directory through xcode.

*If you're using firebase analytics that also makes the crash. because it needs too more configurations to avoid the crash. so check your build without firebase analytics first. If everything is fine, you can add the analytics later

A: If it occurs without any major changes
close Terminal, Emulator and any other application related.
clean the project
clean cache
npm start -- --reset-cache

clean and Install pod file
Cd IOS && podinstall

Rebuild the project.

A: I'm experiencing the same issue since yesterday, the app Im working on is old we are using "react": "16.8.3", "react-native": "^0.59.10", although the app used to work for me properly before, I cloned a fresh copy of the app from the github repo and it worked for the first time, then I again issued the same command npx react-native run-android and after installing the app should open while opening it starts to crash with no error, I see similar metro bundler screen as has been shared in the question. I tried to run the android folder via android studio I could see one issue which Im not able to resolve since yesterday

/node_modules/@react-native-community/netinfo/android/gradle.properties
(Operation not permitted)

which Im not able to figure out how to solve.


text:
Q: Deploying SQL DB To Azure Timeout Enabling Indexes We have a project we are hosting in Azure, we have our SQL servers stored in an elastic pool. The database we have is generated from Code First migrations from the .NET framework; and we load the data into the database with some SQL import scripts.
The issue comes into deploying the database to the Azure. We have tried using SQL Server Management Studio on a dev machine and on the sql server. We have attempted to push the database to Azure using the Deploy Database to Microsoft SQL Azure, and attempted to connect directly to the Azure and Import Data Tier Application using a BACPAC. SQL server 2014 12.0.4439.1 is our server version.
During the deployment process everything seems to go very quickly and the schema is created, data is loaded into the tables, but it hangs on "Enabling Indexes" for most of the process time and at about an hour the entire process times out and fails. I receive 3 errors; the first was error 0; something very cryptic about database files targeting SQL server 2014 having known compatibility with SQL azure v12. Another about a timeout, with a generic message that the process has timed out. The final error is a comment
Could not import package.
Error SQL72016: Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.
Error SQL72045: Script execution error.  The executed script:

Bulk data is loaded

After doing some research I saw a few others complaining that if the basic tier is used that there are not enough DTU's for the process to run within the time limit. We are using the Standard 1 tier for our database and have tried upping it to S2 for the import process as a test. While things seemed to happen faster we had the same issue. Database is 1.6 gigs and does have 2 large tables with ~1 mill rows; though I do not see this as being such a large database that this process should fail.

A: Not a direct solution to the problem, but I have experienced this while testing large database migrations in SSMS. Extending the resources available does seem help, but that means restarting the deployment process.
Rebuilding all the indexes should be the last operation of the migration so to avoid redoing everything you can perform this yourself with something like:
DECLARE C CURSOR FAST_FORWARD FOR
    SELECT so.name, si.name
    FROM sys.indexes si JOIN sys.objects so ON so.object_id = si.object_id
    WHERE is_disabled = 1
    ORDER BY CASE WHEN si.type_desc='CLUSTERED' THEN 0 ELSE 1 END, si.name; -- clustered first as disabled clustered index will stop others rebuilding
DECLARE @tbl NVARCHAR(MAX), @idx NVARCHAR(MAX), @start DATETIME, @sql NVARCHAR(MAX);

OPEN C;
FETCH NEXT FROM C INTO @tbl, @idx;
WHILE @@FETCH_STATUS = 0 BEGIN
    SET @sql = 'ALTER INDEX ['+@idx+'] ON ['+@tbl+'] REBUILD;';
    EXEC (@sql);
    FETCH NEXT FROM C INTO @tbl, @idx;
END
CLOSE C;
DEALLOCATE C;

I found the timeout errors occurred with rebuilds that would on their own take >5 minutes. I've not looked at whether this per operation timeout can be configured in the migration process.
Note that the above assumes all tables are in the dbo schema, if this is not the case add a join to sys.schemas in the cursor definition and use it to prepend the appropriate schema name to the table names.

In the comments Kevin suggests triggers may be disabled at this point, though this was not the case on the occasions I encountered this situation. Just in case, add the following after the current EXEC (@sql); in the above example:
    SET @sql = 'ALTER TABLE ['+@tbl+'] ENABLE TRIGGER ALL;';
    EXEC (@sql);

If the triggers are already active then this is essentially a NoOp so will do no harm. Note that this will not help if the triggers are not yet defined, but they should be by the time the indexes are being rebuilt as that is part of the schema build earlier in the process.

A: SQL DB is designed so that you can scale-up for big operations and scale back down when the workload is quieter?  If you're still receiving errors, why not scale up to an S3 for an hour or two (SQL DB bills in hourly increments) get the import done and scale back down?


text:
Q: How to make a foreign key value NULL in Entity Framework class Table1
{
    int Id;
    int Var1;
    Table2? table2;
}

class Table2
{
    int Id;
    //Other fields
}

Table1 refers to Table2. Since Table2 field is nullable in class Table1, why can't I set it to null the following way?
var zeroVars = table1.where(i => i.Var1 == 0).ToList();

foreach (var t2 in zeroVars)
{
    t2.Var1= -1; // Works
    t2.table2 = null; // Does not change. No error
}

A: The issue is that you haven't eager loaded Table2 for the change tracking to know that you want to remove it. This should work as expected:
var zeroVars = table1
    .Include(i => i.table2)
    .Where(i => i.Var1 == 0)
    .ToList();

foreach(var t2 in zeroVars)
{
    t2.Var1= -1;
    t2.table2 = null;
}

If you don't load the reference then the value is effectively null to begin with, unless it is eager or lazy loaded before attempting to set it.


text:
Q: How to create a loop for the following code? I wrote the following code:
$("#img1").add("#label1").fadeIn();
$("#img1").click(function() {
  $(this).attr("src", "/abc/xyz.png");
  $("#content1").add("#img2").add("#label2").fadeIn(1000);
});

When I click on img2, the image source ishould change and content2 as well as img3 / label3 should be displayed.When I reach img5, just content5 should be displayed and the function should end.
Without a loop the function works fine - but its a lot of code...
I tried to build an Array and loop through it with a for loop, but somehow I always fail.
$("#img1").add("#label1").fadeIn();
var turn = [1, 2, 3, 4]

for (var i = 1; i <= turn; i++) {
  $("#img" + turn).click(function() {
    $(this).attr("src", "/abc/xyz.png");
    $("#content" + turn).add("#img" + (turn + 1)).add("#label" + (turn + 1)).fadeIn(1000);
  });
}

$("#img5").click(function() {
  $(this).attr("src", "/abc/xyz.png.png");
  $("#content5").fadeIn(1000);
});

I would be very happy if you could provide some input for beginners: )
Here is some of the html-code where it should be used:
    .check{
    display: none;
}
.container{
    display:flex;
    flex: space-evenly;
}

.box {
    flex: 0 0 170px;
}
.content{
    flex: 2 1 50px;
    display:none;
    text-align: left;
}
img{
    cursor:pointer;
    float: left;
    display: none;
}
label{
    display: none;
}
.pic{
    cursor: context-menu;
}

    <input type="checkbox" id="Einltg_Var1" class="check">

             Step1

Content1

    <input type="checkbox" id="Einltg_Var2" class="check">

            Step2

Content2.

A: It's a bit unclear what you want 100%. but if you want a click function that works with all, try something like this:
$("img[id^=img]").click(function() {
  var idnumber = +$(this).attr("id").replace("img", "");
  $(this).attr("src", "/abc/xyz.png");
  $("#content" + idnumber).add("#img" + (idnumber + 1)).add("#label" + (idnumber + 1)).fadeIn(1000);
});

Demo

$("img[id^=img]").click(function() {
  var idnumber = +$(this).attr("id").replace("img", "");
  $(this).attr("src", "/abc/xyz.png");
  $("#content" + idnumber).add("#img" + (idnumber + 1)).add("#label" + (idnumber + 1)).fadeIn(1000);
});
.check {
  display: none;
}

.container {
  display: flex;
  flex: space-evenly;
}

.box {
  flex: 0 0 170px;
}

.content {
  flex: 2 1 50px;
  display: none;
  text-align: left;
}

img {
  cursor: pointer;
  float: left;
}

label {
}

.pic {
  cursor: context-menu;
}

    <input type="checkbox" id="Einltg_Var1" class="check">

             Step1

Content1

    <input type="checkbox" id="Einltg_Var2" class="check">

             Step2

Content2

    <input type="checkbox" id="Einltg_Var3" class="check">

             Step3

Content3

A: In a loop, you should replace turn with i, and also turn should be an integer not an array.
Here is the correction.
$("#img1").add("#label1").fadeIn();
var turn = 4;

for (var i = 1; i <= turn; i++) {
  $("#img" + i).click(function() {
    $(this).attr("src", "/abc/xyz.png");
    $("#content" + i).add("#img" + (i + 1)).add("#label" + (i + 1)).fadeIn(1000);
  });
}

$("#img5").click(function() {
  $(this).attr("src", "/abc/xyz.png.png");
  $("#content5").fadeIn(1000);
});


text:
Q: java.lang.IllegalArgumentException: Unrecognized Type: [null] in Jackson Here is my method inside which I have this error
private <T> Mono<CarbonResponse<T>> evaluateVersion(Key key, String facts, boolean showTestResults) {
   return mapper.readValue(result,  new TypeReference<CarbonResponse<T>>() {}); // error here
}

where is result is JSON string.
My CarbonResponse.java
public class CarbonResponse<T> {
    int code;
    String message;
    DataV1<T> data;
}

DataV1.java
public class DataV1<T> {

    @JsonProperty(value = "rule_set_id")
    String ruleSetId;

    @JsonProperty(value = "version_id")
    String ruleSetVersionId;

    T result;

    @JsonProperty(value = "rules_evaluation_response")
    List<T> rulesEvaluationResponse;
}

gradle
 implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.10.3'
 // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
 implementation group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.10.3'

Full Error Strace
java.lang.IllegalArgumentException: Unrecognized Type: [null]
    at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1266)
    at com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(TypeFactory.java:1480)
    at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1250)
    at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:670)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3197)
    at com.pharmeasy.carbon.client.CarbonClient.lambda$evaluateVersion$0(CarbonClient.java:321)
    at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:100)
    at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1705)
    at reactor.core.publisher.MonoZip$ZipCoordinator.signal(MonoZip.java:247)
    at reactor.core.publisher.MonoZip$ZipInner.onNext(MonoZip.java:329)

Can I please know what am I missing here?
I figured this new TypeReference<CarbonResponse<T>>() {} is giving out null when we have T in it but I am not able to figure out the solution.

A: You just can use
Mono<CarbonResponse<Void>>
new TypeReference<CarbonResponse<Void>


text:
Q: Among real numbers, find the real solutions of: $x^2(y^2+z)=zy^2$, $y^2(z^2+x)=xz^2$, $z^2(x^2+y)=yx^2$ Among real numbers, find the real solutions of the system: $x^2(y^2+z)=zy^2$, $y^2(z^2+x)=xz^2$, $z^2(x^2+y)=yx^2$.
I tried solving it as follows:
$x^2y^2+x^2z=zy^2$
$x^2y^2=z(y^2-x^2)$
$z=\frac{x^2y^2}{y^2-x^2}$
$x(z^2-y^2)=y^2z^2$
$x=\frac{y^2z^2}{z^2-y^2}$
$y=\frac{x^2z^2}{x^2-z^2}$
And here is where I got stuck. Could you please help me finish off the question?

A: Substituting $z$ we obtain two equations in $x$ and $y$,
which we can solve. Then we need to consider the case $x^2=y^2$ separately.
In summary, we have only the following solutions (even over the complex numbers):
$$
(x,y,z)=(0,0,z),(0,y,0),(x,0,0).
$$
So two of the variables equal to zero, and the third one arbitrary.
More precisely, the two equations are, assuming $x^2-y^2$ nonzero and substituting $z=x^2y^2(y^2-x^2)$
$$
(x^2y^2 - x^2 - xy^2 + y^2)(x^2 - xy^2 - y^2)xy^2=0,
$$
and
$$
(x^2y^2 + x^2y + x^2 - y^2)(x^2y - x^2 + y^2)x^2y=0.
$$


text:
Q: Java 8 Convert Object to String separated by VALUE I'm trying to conver a java Object to a string separated by "SEPARATOR".
Example
public class Person{

int id;
String name;
String age;
String sex;
}

Main method
Person per = new Person(1, "Kevin", "20", "Male");
String objectAsText = per.ConvertObjectToString(per, "|");

Expected output
1|Kevin|20|Male

Note that the java object is not a list. And I also want to add a validation so the method ConvertObjectToString can avoid printing object values that are null. ie
Person per = new Person(1, "Kevin", "Male");
String objectAsText = per.ConvertObjectToString(per, "|");

Expected output
1|Kevin|Male

I know that this can be achieved using toString method, but I want to know if there is any other efficient way. Also I don't want to check value by value if null since the java object can be large.

A: If you don't want to check each value, I would recommend java object converting into JSON, like into Map<String,Object> and then use Collectors.joining
String value = map.values()
            .stream().filter(Objects::nonNull)
            .map(Object::toString)
            .collect(Collectors.joining("|"));

You can do it using the reflection package, but make sure your fields are public
 Person per = new Person(1, "Kevin", "20", "Male");

   String value = Arrays.stream(Person.getClass().getFields())
           .map(f-> {
               try {
                   return f.get(per).toString();
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               }
               return null;
           }).filter(Objects::nonNull).collect(Collectors.joining("|"));

    System.out.println(value); //1|Kevin|20|Male


text:
Q: swift: Listen for "struct variable"-change event? I got a small problem :

How is it possible to listen for the change of a struct-instance variable declared in another ("uneditable!!") class?

I added some small code snippets to maybe clarify my thoughts.
instructions:

*

*FixedClass is a uneditable class: I don't want to change / I'm not able to change any code of the "FixedClass"

*EditableClass can be edited - I'm sure you will get it looking at the code (^_^)/

code:
let fixedClass: FixedClass = FixedClass()
class FixedClass {
    struct MyObject {
        var abc = 0
    }
    var instance = MyObject()
    public init() { Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.updateVar), userInfo: nil,  repeats: true) }

    @objc func updateVar() {
        instance.abc+=1
    }
    func getVar() -> Int {
        return instance.abc
    }
}

let editableClass: EditableClass = EditableClass()
class EditableClass {
    public init() { }
    func listenForChange() {
        // listen for change event of FixedClass.getVar()
        print("Variable: \(fixedClass.getVar())")
    }
}

Calling with:    editableClass.listenForChange()

To sum that up I'd like to listen for the change of the FixedClass.getVar() result - preferably avoid using loops or timers. However the most important thing is to get it working at least.
Any help would be very appreciated, thanks!

A: This is going to depend totally on how the 'real' FixedClass is defined.  I.E. is it a subclass of NSObject, is it an ObjectiveC class, how the property you want to observe is defined.
As far as your actual example is concerned you could do it by subclassing like this:
var newFixedClass: NewFixedClass = NewFixedClass()
var editableClass: EditableClass = EditableClass()

protocol NewFixedClassProtocol: class {
    func changed(newFixedClass: NewFixedClass)
}

class NewFixedClass: FixedClass {
    public weak var delegate: NewFixedClassProtocol?

    override var instance: FixedClass.MyObject {
        didSet {
            self.delegate?.changed(newFixedClass: self)
        }
    }
}

class EditableClass: NewFixedClassProtocol {
    public init() {
        newFixedClass.delegate = self
    }

    func changed(newFixedClass: NewFixedClass) {
        print ("Value = \(newFixedClass.instance.abc)")
    }
}

So you basically create a protocol which the class doing the observing supports, create a subclass of the FixedClass which has a delegate of the protocol type and overrides the property of the FixedClass you want to observe with a didSet observer which then calls the delegate method.  At some point you have to assign the class observing as the delegate of the sub class (I did it in the init method as a test).
So doing that I can observe when the structure changes but I haven't touched the FixedClass.
Note however that this method relies heavily on knowing about the original FixedClass so may not work for your 'real world' case.
(Also as an aside I couldn't get it to work with the globally defined instances of the classes and had to set them inside my initial view controller but that could be to do with how I was testing and doesn't alter the method involved)

A: A couple of things:

*

*If the original class was Objective-C or otherwise participated in KVO (e.g. Swift dynamic properties of NSObject subclass, etc.) then you could observe changes. But but that's a fairly narrow use case. But that's a general pattern for making one's properties observable by other objects. For more information, see the Key-Value Observing Programming Guide.

*If you can't edit the class, in some narrow cases you could theoretically subclass it and add whatever observation system you want. That obviously only works if you're manually instantiating FixedClass and it is contingent upon how FixedClass was implemented, but in some narrow cases, you can achieve what you need via subclassing.
You asked:

Would you be so kind an share some code snippets with us?

Sure, consider your FixedClass:
class FixedClass {
    struct MyObject {
        var abc = 0
    }
    var instance = MyObject()
    public init() { Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.updateVar), userInfo: nil,  repeats: true) }

    @objc func updateVar() {
        instance.abc+=1
    }
    func getVar() -> Int {
        return instance.abc
    }
}

You could then define a subclass:
class FixedClassSubclass: FixedClass {
    static let changeNotification = NSNotification.Name(rawValue: Bundle.main.bundleIdentifier! + ".FixedClassSubclassNotification")

    override func updateVar() {
        super.updateVar()
        NotificationCenter.default.post(name: FixedClassSubclass.changeNotification, object: self)
    }
}

Then you could do:
let fixed = FixedClassSubclass()

and
NotificationCenter.default.addObserver(forName: FixedClassSubclass.changeNotification, object: nil, queue: nil) { _ in
    print("changed")
}

You can use whatever notification process you want. NotificationCenter. KVN. Delegate-protocol pattern. Whatever. The details of this will vary entirely based upon the details of FixedClass and you have given us a contrived example that is unlikely to be extensible in many situations.
I must confess to some general misgivings to the idea of trying to hook into the internal implementation details of a non-editable class. We generally strive for loosely coupled objects that only rely on published, supported interfaces. This endeavor violates both of those objectives. But I'll assume you have some good reason to do what you're attempting to do.

A: One way to do this would be to use NotificationCenter to broadcast the change, and have your EditableClass listen for that change and react to it.  Your implementation could look something like this:
class FixedClass { //Class names should start with capital letters
  struct MyObject { //Struct names should also start with capital letters
    var abc = 0
  }
  var instance = myObject()
  public init() { Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.updateVar), userInfo: nil,  repeats: true) }

  @objc func updateVar() {
    instance.abc+=1
    //Broadcast the change, and pass this FixedClass instance
    NotificationCenter.default.post(name: Notification.Name("fixedClassChanged"), object: self)
  }
  func getVar() -> Int {
    return instance.abc
  }
}

Then you could react to this broadcast in your EditableClass like so:
class EditableClass {
  public init() { }
  func listenForChange() {
    //Observe same notification being broadcast by the other class
    NotificationCenter.default.addObserver(self, selector: #selector(processChange(_:)), name: Notification.Name("fixedClassChanged"), object: nil)
  }

  @objc func processChange(_ sender: Notification) {
    //When the notification comes in, check to see if the object passed in was a FixedClass, and if so process whatever needs to be processed
    if let fixed = sender.object as? FixedClass {
        print("Class changed to \(fixed.getVar())")
    }
  }
}


text:
Q: How to set an include system directory in the Eclipse Platform From the 'Ubuntu Software Center', I have installed Eclipse Platform Version: 3.7.2. and 'eclipse-cdt C/C++ Development Tools'.
In the eclipse Samples at Eclipse.org, I see only these for java, not for C/C++ as I need. Therefore I have downloaded  hello-2.7.tar.xz from http://ftp.gnu.org/gnu/hello/, unpacked it into my eclipse directory and made a new C Linux project for it.
Its 'Project... Build all' does not find the file from the line
#include <config.h>
 of the hello.c file as you can see from the listing

**** Build of configuration Debug for project hello-2.7 ****

make all
Building file: ../src/hello.c
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/hello.d" -MT"src/hello.d" -o "src/hello.o" "../src/hello.c"
../src/hello.c:19:20: fatal error: config.h: No such file or directory
compilation terminated.
make: *** [src/hello.o] Error 1

**** Build Finished ****

. Please advise me how to set an include system directory in the Eclipse Platform. (In its help, I have tried searching for it; but it only started an indexing that shows '0% complete' even after several hours. The CPU is
Ubuntu
Release 12.04 (precise) 32—bit
Kernel Linux 3.5.0-39-generic
GNOME 3.4.2
Hardware
Memory: 994.9 MiB
Processor: Intel Pentium(R) 4 CPU 3.00GHz x 2
System Status
Available disk space 39.4 GiB

.) At all, does the line
#include <config.h>
 mean the same in Linux as I am used to from Windows and not a further file from the GNU pages?
   Thanks!


text:
Q: java jama array problem I asked a question before but duffymo said it is not clear so i am going to post it again here.
I am using Jama api for SVD calculation. I know very well about jama and SVD.
Jama does not work if your column are more than rows. I have this situation. What should I do?? any help?
I can't transpose the matrix too as it can produce wrong results.
Thanks.
P.S: I am calculating LSI with the help of jama. I am going like column(docs) and rows ( terms )

A: If I understand correctly you are trying to compute the SVD of a matrix which is not square, and you have the library JAMA which only works on square matrices?  If I have understood you correctly then the answer to your question is obvious: Get a library which does compute SVD for non-square matrices. If I remember correctly Numerical Recipes contains such an algorithm, I expect you can find many other sources with Google.

A: Why not use transpose? If X = USV', then X' = VS'U'. Right?
Transpose your matrix. Get U, S and V. Transpose everything back.

A: Since you're doing LSI, you could use SVDLIBJ, which is the Java equivalent of SVDLIBC, which is one of the most scalable SVD implementations that is freely available.  The S-Space package has a command-line tool for SVDLIBJ set up already.  Also, you can use their Matrix libraries and avoid the command-line if that fits your needs better.

A: I now it is a really late reply . But i thought it is better late than never
But i am aware that jblas performs svd in a effective manner.


text:
Q: Getting error after renewing developer license. Can't connect to WCF service I have a WCF self-hosted service, using NetTcpBinding with callbacks and transport security on Windows Azure, with a production certificate and a domain redirect.
Before renewing my developer license, everything worked. After, I'm getting this exception in the Reference.cs file:

The type 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior,
      Microsoft.VisualStudio.Diagnostics.ServiceModelSink, Version=4.0.0.0,
      Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' registered for extension
      'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior'
      could not be loaded.

My colleague has yet to update her dev license, and everything still works for her.
Any idea why this is happening ?

A: Deleting the project and re-downloading it from source control solved the problem. No idea what happened...


text:
Q: Excel macro store value of vlookup and then add them up So I have the following sheet setup:

Sheet 1
A        B     C
Tomatoes  100   50
Onions    20    0
Garlic    10    0
Chicken   0     100
Cheese    0     20
Where each column after A is a recipe and going down is the amount of grams required in the recipe of the ingredient.
Sheet 2 has cost per 100 grams per ingredient like so:

A         B
Chicken   10
Tomatoes  1.5
Onions    2.25
What I'd like to do, is at the bottom of sheet 1 (ideally) under each column I could have the cost for the recipe.
In my mind it's broken down into 2 steps. Step 1 is do a vlookup from Sheet 1 to replace the grams to cost. Then do a sum of the entire column. I just don't know how to do that either in a macro or formula.

A: Refer the below specified link,
https://www.ablebits.com/office-addins-blog/2014/08/05/excel-vlookup-sum-sumif/#lookup-sum
You can download their worksheet here