text:
Q: Embedd pig in python . AttributeError: SimplePigStats object has no attribute 'isSuccessfull' Came across a python error while running pig embedded in Python script. Solved the problem but want to know if anyone else came across this error.
Scenario: a) Python script with pig goes like this.
pigRun = Pig.compileFromFile(self.settingsReader.getScriptsDir() + "/" + script.name)
params = { 'datefrom': '2012-08-04 00:00:00', 'dateto': '2012-12-05 00:00:00',
       'parallelism':self.settingsReader.getParallelism(),
       'input' : script.input, 'output':script.output}
        bound = pigRun.bind(params)
        stats=bound.runSingle()
        if not stats.isSuccessfull():
          raise 'failed'

b) Pig version is 0.10. Python 2.7, Jython 2.5
Getting error on the lines
if not stats.isSuccessfull():
          raise 'failed'

c) Error is as follows
AttributeError: 'org.apache.pig.tools.pigstats.SimplePigStats' object has no attribute 'isSuccessfull'
After looking at the source for Apache PIG 0.10, SimplePigStats seems to have isSuccessfull() implemented in it. But the runtime error says it is not.
Temporary Solution: Changed the failure check code as follows
bound = pigRun.bind(params)
stats= bound.runSingle()
     if stats.getReturnCode() != 0:
        raise 'failed'

This seems to work fine.


text:
Q: Tail file graphically with PyQt I'm trying to do what sounds fairly simple but I keep running in to all sorts of problems.
I'm trying to create a GUI that can tail several files at the same time using PyQt.
I saw this answer on how to tail a file in pure Python
How can I tail a log file in Python?
I have tried using this code inside of a QThread.
The issues I'm having here are that the tail process never stops by itself; it needs to be killed.
It should be killed when the GUI is closed.
The other issues I'm getting with this specific solution below is
QThread: Destroyed while thread is still running

and
QWaitCondition::wakeAll(): mutex lock failure:

and
QThread: Destroyed while thread is still running
Traceback (most recent call last):
  File "./tailer.py", line 27, in run
    self.emit(SIGNAL('newline'), line.rstrip())
RuntimeError: underlying C/C++ object has been deleted

Other implementations I've tried have had the tail process complaining about a broken pipe but those stopped appearing once I did stderr=PIPE as well.
I'm worried now that I could be missing errors since I never read from stderr (since it would block and there shouldn't be any output).
To get the errors fire this up trying to tail 3 different file.
I wrote another script that loops and writes to those 3 files doing a sleep of 0.1 seconds.
I close the GUI and start it up over and over again.  Sometimes I get errors sometimes I don't.
Please tell me what I'm doing wrong here.
#!/usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import os
from subprocess import Popen, PIPE

class Tailer(QThread):

    def __init__(self, fname, parent=None):
        super(Tailer, self).__init__(parent)
        self.fname = fname
        self.connect(self, SIGNAL('finished()'), self.cleanup)

    def cleanup(self):
        print 'CLEANING UP'
        self.p.kill()
        print 'killed'

    def run(self):
        command = ["tail", "-f", self.fname]
        print command
        self.p = Popen(command, stdout=PIPE, stderr=PIPE)
        while True:
            line = self.p.stdout.readline()
            self.emit(SIGNAL('newline'), line.rstrip())
            if not line:
                print 'BREAKING'
                break

    def foo(self):
        self.p.kill()

class TailWidget(QWidget):
    def __init__(self, fnames, parent=None):
        super(TailWidget, self).__init__(parent)
        layout = QGridLayout()
        self.threads = {}
        self.browsers = {}
        for i, fname in enumerate(fnames):
            if not os.path.exists(fname):
                print fname, "doesn't exist; creating"
                p = Popen(['touch', fname], stdout=PIPE, stderr=PIPE)
                out, err = p.communicate()
                ret = p.wait()
                assert ret == 0
            t = Tailer(fname, self)
            self.threads[fname] = t
            b = QTextBrowser()
            self.browsers[fname] = b
            layout.addWidget(QLabel('Tail on %s' % fname), 0, i)
            layout.addWidget(b, 1, i)
            self.connect(t, SIGNAL("newline"), b.append)
            t.start()
        self.setLayout(layout)

    def closeEvent(self, event):
        for fname, t in self.threads.items():
            t.foo()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    tw = TailWidget(sys.argv[1:])
    tw.show()
    sys.exit(app.exec_())

A: The problem is that the main thread isn't waiting on the background threads.
You tell them to stop here:
def closeEvent(self, event):
    for fname, t in self.threads.items():
        t.foo()

So, this kills all of the subprocesses, which will make all of the background threads quit eventually. But it won't make them stop immediately. That won't happen until the next time each one gets to its readline.
After killing the subprocesses, you return, letting Qt immediately close your window and destroy your widget. Any background threads that try to send a signal to that widget will then fail.
Imagine that thread 1 has done a readline, and is in the middle of its rstrip when thread 0 tries to close down. So, thread 0 kills thread 1's subprocess, then deletes the main widget. Thread 1 finishes its rstrip and calls emit, and it's now sending to a deleted widget.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stop drag event inside jDesktopPane I want to block dragging jInternalForm inside Desktop Pane.
I've tried steps followed here :
Preventing JInternalFrame from being moved out of a JDesktopPane
But it didn't work for me. Can someone suggest a working override method for this.

A: Here is a somewhat simpler example of a custom DesktopManager to keep the internal frame within the bounds of the desktop:
public class BoundsDesktopManager extends DefaultDesktopManager
{
    /*
    **  This is called anytime a frame is moved.
    **  This implementation keeps the frame from leaving the desktop.
    */
    @Override
    public void dragFrame(JComponent component, int x, int y)
    {
        // Deal only with internal frames

        if (component instanceof JInternalFrame)
        {
            JInternalFrame frame = (JInternalFrame)component;
            JDesktopPane desktop = frame.getDesktopPane();
            Dimension d = desktop.getSize();

            // Too far left or right?

            if (x < 0)
            {
                x = 0;
            }
            else if (x + frame.getWidth() > d.width)
            {
                x = d.width - frame.getWidth();
            }

            //  Too high or low?

            if (y < 0)
            {
                y = 0;
            }
            else if (y + frame.getHeight() > d.height)
            {
                y = d.height - frame.getHeight();
            }
        }

        // Pass along the (possibly cropped) values to the normal drag handler.

        super.dragFrame(component, x, y);
    }
}


text:
Q: How to get the current installation within the cloud function This was asked here but without a clear answer on how to get the current installation from the cloud.
In my cloud function, I need to bind the current user with the current installation, I can send the current user within the request object to the cloud function, but I cannot find any way to get the current installation within the cloud code. I know this is pretty easy in iOS SDK but since I am using javascript, I need a way to access the current installation from the cloud code. How is that be doable?

A: You can get the installationId from your current session.
Parse.Session.current()
  .then(function(session) {
    // Get the installation ID
    installationId = session.get('installationId');
  });

A: edit: JavaScript doesn't have installations, so what installation are you trying to alter?
The answer is going to be the same here..  The "installation" isn't sent with every request like the user is, so you need to assign that relationship elsewhere.  Either you send in the current installation object id with your function request, or you save a pointer (either way) to pair the user and the installation together and then query for the related object in cloud code.

A: You can get the current installation from which the request is made like this:
// Get current installation
const currentInstallationId = request.installationId;


text:
Q: Graphite - use multiple series with DivideSeries I'm trying to use Graphite to compute a CTR for all my resources, so I tried recording my data like this:

*

*ctr.resource_id.clicks

*ctr.resource_id.reach

So first, I made my query :
&target= averageSeries(divideSeries(ctr.176983011340976128.clicks,ctr.176983011340976128.reach),divideSeries(ctr.190348137012011008.clicks,ctr.190348137012011008.reach))

My problem here is that I don't want to send all my resource ids to graphite, so I tried :
&target= averageSeries(divideSeries(ctr.*.clicks,ctr.*.reach))

But yeah, as the documentation says "ValueError: divideSeries second argument must reference exactly 1 series".
I tried an alternative architecture :

*

*ctr.clicks.resource_id

*ctr.reach.resource_id

But same problem…
I'm new with Graphite, so if anyone has a solution, it will be amazing!
Edit:
Just saw the function groupByNode, trying to use it…

A: Sounds like you need to aggregate your data into a series beforehand so you can pass it to divideSeries.
Aggregator-rules.conf reference in the Configuring Carbon docs: http://graphite.readthedocs.org/en/latest/config-carbon.html
So you'd need 2 rules like this to sum up the click data per min:
ctr.resource_all.clicks (60) = sum ctr.*.clicks
ctr.resource_all.reach (60) = sum ctr.*.reach
You'll also have to run the carbon-aggregator.py daemon
/opt/graphite/bin/carbon-aggregator.py start
The default port for the aggregator daemon is 2023, so that's where you should send your traffic instead of the 2003 port you've been using.


text:
Q: Templating `bucket_key` in S3KeySensor in Apache Airflow Airflow version: 1.9.0
Within an airflow dag file, I have a PythonOperator task, named run_query, that sets the following xcom variable within its python_callable function:
kwargs['ti'].xcom_push(key='query_result_loc', value=query_result_loc)
Latter in that same dag, I have a S3KeySensor task that uses the above location for its bucket_key param:
S3KeySensor(task_id = 'check_file_in_s3',
                 bucket_key = '{{  ti.xcom_pull(task_ids="run_query",key="query_result_loc")  }}' ,
                 bucket_name = None,
                 wildcard_match = False,
                 poke_interval=60,
                 timeout=1200,
                 dag = dag
                 )

Now, when I run the dag (either in test mode or trigger_dag mode), S3KeySensor complains of a missing bucket_name, which comes from this code in S3KeySensor definition:
    class S3KeySensor(BaseSensorOperator):
    """
    Waits for a key (a file-like instance on S3) to be present in a S3 bucket.
    S3 being a key/value it does not support folders. The path is just a key
    a resource.

    :param bucket_key: The key being waited on. Supports full s3:// style url
        or relative path from root level.
    :type bucket_key: str
    :param bucket_name: Name of the S3 bucket
    :type bucket_name: str
    :param wildcard_match: whether the bucket_key should be interpreted as a
        Unix wildcard pattern
    :type wildcard_match: bool
    :param aws_conn_id: a reference to the s3 connection
    :type aws_conn_id: str
    """
    template_fields = ('bucket_key', 'bucket_name')

    @apply_defaults
    def __init__(
                self, bucket_key,
                bucket_name=None,
                wildcard_match=False,
                aws_conn_id='aws_default',
                *args, **kwargs):
            super(S3KeySensor, self).__init__(*args, **kwargs)
            # Parse
            if bucket_name is None:
                parsed_url = urlparse(bucket_key)
                if parsed_url.netloc == '':
                    raise AirflowException('Please provide a bucket_name')
                else:
                    bucket_name = parsed_url.netloc
                    if parsed_url.path[0] == '/':
                        bucket_key = parsed_url.path[1:]
                    else:
                        bucket_key = parsed_url.path
            self.bucket_name = bucket_name
            self.bucket_key = bucket_key

Looks like the template is not getting rendered at this stage.
If I comment out that if block, it works fine. Is this a bug or a wrong usage of template fields?
Update, based on @kaxil's comment:

*

*With no bucket_name provided and with the 'if' block left uncommented, airflow fails to even detect the dag. On the UI, I instead see this error: Broken DAG: [/XXXX/YYYY/project_airflow.py] Please provide provide a bucket_name

*With no bucket_name provided, but with the following modification to the 'if' block (cf. removed the if parsed_url.netloc == '' check), it works fine:
if bucket_name is None:
    parsed_url = urlparse(bucket_key)
    bucket_name = parsed_url.netloc
    if parsed_url.path[0] == '/':
        bucket_key = parsed_url.path[1:]
    else:
        bucket_key = parsed_url.path

*With a bucket_name provided, it works fine with a rendered value for bucket_key and bucket_name under Rendered Template tab.

A: You've probably worked this out by now but it's because you're not providing an array to task_ids. The format should be task_ids=["run_query"]. Changing it to this resolved the problem for me.

A: As you correctly noticed with updated quote, bucket key validation happens before jinja templating.
The only solution I found to this is to not use functionality where you only provide bucket key. If you want to use templating, provide both bucket name and bucket key. In that case, validation won't happen and fields will be templated.


text:
Q: same locations memory but the result false (python) i just get confuse about the identity operator in python , how to use it and how the identity operator works , i'll give you the example :
var_1 = 10
print (id(var_1) is id(var_1))

the result is "False" , i don't know why be like that , some one can explain in simple way ? and explain the id() function works .
thank's

A: your use of id() is redundant, the is operator takes the two objects and compares their addresses , when you do id(var_1)  you're creating a nameless variable that has the value of the id of var_1 then you create another nameless variable, it will have the same value but it won't be the same id you can check this by printing id(id(var_1) and seeing it's different every time:
var_1 = 10
print id(id(var_1))
#18438008
print id(id(var_1))
#18438032
print id(id(var_1))
#18438056

if you want to see if an object is the same you need to either do id(var_1) == id(var_2) or as recommended: var_1 is var_2


text:
Q: Не происходит инъекция в конструктор WebApiController Дали задание заинджектать в конструктор контроллера класс Repository реализующий интерфейс Repository. Нашёл пример пример вот такой конфигурации
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(API.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(API.App_Start.NinjectWebCommon), "Stop")]

namespace API.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    using DataAccess;

    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);

        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);//Добавил строчку вот тут

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<Repository>().ToConstructor(i => new Repository(i.Inject<QueueDB>()));
            kernel.Bind<IRepository>().To<Repository>();
        }
    }
}

Вот он сам контроллер. В конструкторе передаю интерфейс IRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DataAccess;

namespace API.Controllers
{
    [Authorize]
    public class ValuesController : ApiController
    {
        IRepository _repository;
        public ValuesController(IRepository repository)
        {
            _repository = repository;
        }
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

При этом реализация интерфейса, класс Repository принимает в качестве аргумента конструктора интерфейс IContext (Который мы тоже заинджектали) у который реализует класс QueueDB.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Threading.Tasks;
using Entity;

namespace DataAccess
{
    public class Repository : IRepository
    {
        private IContext _context;
        public Repository(IContext context)
        {
            if (context == null)
                throw new NullReferenceException("Context is null");

            this._context = context;
        }
        public void AddQueue(Queue queue)
        {
            _context.Queues.Add(queue);
            _context.SaveChanges();
        }

        public void AddUser(User user)
        {
            _context.Users.Add(user);
            _context.SaveChanges();
        }

        public void AddUserInQueue(User user, Queue queue)
        {
            UserState state = new UserState
            {
                Queue = queue,
                User = user
            };
            _context.States.Add(state);
            _context.SaveChanges();
        }

        public void DeleteQueue(Queue queue)
        {
            _context.Delete(queue);
            _context.SaveChanges();
        }

        public void DeleteUser(User user)
        {
            _context.Delete(user);
            _context.SaveChanges();
        }

        public void DeleteUserFromQueue(User user, Queue queue)
        {
            UserState state = user.States.FirstOrDefault(s => s.Queue.Id.Equals(queue.Id));//Яне буду использовать include, буду надется на lazy loading

            if (state == null)
                throw new NullReferenceException(string.Format("User (systemName: {0}) not a member Queue (id: {1})", user.SystemName, queue.Id));
            else
            {
                _context.Delete(state);
                _context.SaveChanges();
            }
        }

        public void Dispose()
        {
            _context.Dispose();
        }

        public void EditQueue(Queue edit)
        {
            _context.Update(edit);
        }

        public void EditUser(User edit)
        {
            _context.Update(edit);
            _context.SaveChanges();
        }

        public ICollection<Queue> GetAllQueue()
        {
            return _context.Queues.ToList();
        }

        public ICollection<User> GetAllUser()
        {
            return _context.Users.ToList();
        }

        public Queue GetQueueById(Guid id)
        {
            Queue queue = _context.Queues.FirstOrDefault(q => q.Id.Equals(id));

            if (queue == null)
                throw new NullReferenceException(string.Format("Queue (id: {0}) not fount", id));
            else
                return queue;
        }

        public User GetUserBySystemName(string systemName)
        {
            User user = _context.Users.FirstOrDefault(u => u.SystemName.Equals(systemName));

            if (user == null)
                throw new NullReferenceException(string.Format("User (systemName: {0}) not fount", systemName));
            else
                return user;
        }

        public bool HasUser(string systemName)
        {
            return _context.Users.FirstOrDefault(u => u.SystemName.Equals(systemName)) != null;
        }
    }
}

Но при обращении к контроллеру ValuesController появляется ошибка:
<Error>
<Message>Произошла ошибка.</Message>
<ExceptionMessage>
Произошла ошибка при попытке создать контроллер типа "ValuesController". Убедитесь в том, что контроллер имеет общедоступный конструктор без параметров.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
в System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) в System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) в System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
<InnerException>
<Message>Произошла ошибка.</Message>
<ExceptionMessage>
Тип "API.Controllers.ValuesController" не содержит конструктор по умолчанию
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
в System.Linq.Expressions.Expression.New(Type type) в System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) в System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) в System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</InnerException>
</Error>

Пример я брал вот от сюда


text:
Q: Software Floating Point Library for Arm aarch64 I am working on armv8 Cortex A55 with 5 cores ,in aarch64 mode and compiling with armclang. However my core doesn't have a hardware FPU unit but my program does have floating point operations. I need to use a SW FPU library consistent with the IEEE standard for arm aarch64 since armclang doesnt provide one for aarch64.

*

*Will using  -mfloat-abi=soft be enough to tell the compiler not to use fpu instructions or registers anywhere?

*How is the soft float abi option different from  -mgeneral-regs-only compiler option ?


text:
Q: Facebook page access token is not working I am using Graph API for insights stats for facebook page but data array is blank and not returning any value.
"data": [

   ]

A: This is a reference from Stackoverflow Question
Looks like you're using v2.4 of the Graph API. See

*

*https://developers.facebook.com/docs/apps/changelog#v2_4

Declarative Fields
  To try to improve performance on mobile networks, Nodes and Edges in v2.4 requires that you explicitly request the field(s) you need for your GET requests. For example, GET /v2.4/pageid/insights no longer includes likes and comments by default, but GET /v2.4/pageid/insights?fields=id,name,period,values,title,description will return the data. For more details see the docs on how to request specific fields.


text:
Q: The difference of gevent and multiprocess I am learning how to make my script run faster. I think parallel is a good way. So I try gevent and multiprocessing. But I am confused by it's different result. Let me show two examples I met,
ex 1:
a=np.zeros([3])
def f(i):
    a[i]=1
    print a
def f_para():
    p=multiprocessing.Pool()
    p.map(f, range(3))

def f_asy():
    threads = [gevent.spawn(f, i) for i in xrange(3)]
    gevent.joinall(threads)

f_para()
[ 0.  1.  0.]
[ 0.  0.  1.]
[ 1.  0.  0.]

f_asy()
[ 1.  0.  0.]
[ 1.  1.  0.]
[ 1.  1.  1.]

I find that using multiprocessing, the global object a never change in fat, and after running f_para(), a is still the original array. While running f_asy(), it's different, a changed.
ex 2:
def f2(i):
    subprocess.call(['./a.out', str(i)])
    time.sleep(0.2)

def f2_loop():
    for i in xrange(20):
        f2(i)

def f2_para():
    p=multiprocessing.Pool()
    p.map(f2, range(20))

def f2_asy():
    threads = [gevent.spawn(f2, i) for i in xrange(20)]
    gevent.joinall(threads)

%timeit -n1 f2_loop()
1 loop, best of 3: 4.22 s per loop
%timeit -n1 f2_asy()
1 loop, best of 3: 4.22 s per loop
%timeit -n1 f2_para()
1 loop, best of 3: 657 ms per loop

I find that f2_asy() don't decrease run time. And the output of f2_asy() is one by one, just as f2_loop(), so there is no parallel in f2_asy() I think.
The a.out is a simple c++ code:
 #include <iostream>

 int main(int argc, char* argv[])
 {
   std::cout<<argv[1]<<std::endl;
   return 0;
 }

So my question is that:

*

*why in ex 1, f_para can change the value of global array a ?

*why in ex 2, f2_asy can't do parallel?
Dose any knows the difference between gevent and multiprocessing? I am very grateful if you are willing to explain it.

A: ex1:
when you use multiprocess each process has separate memory(unlike threads)
ex2:
gevent does not create threads, it creates Greenlets(coroutines)!

Greenlets all run inside of the OS process for the main program but are scheduled cooperatively.
Only one greenlet is ever running at any given time.
This differs from any of the real parallelism constructs provided by multiprocessing or threading libraries which do spin processes and POSIX threads which are scheduled by the operating system and are truly parallel.


text:
Q: How to Center Align template element in PdfPCell I am building a vertical list of months with a horizontal list of days in each month. To each day I am adding a sized and colored rectangle; the size and color is dependant on a value from a db query.
I am using PdfPTable, PdfPCell and cbCreateTemplate provided in this answer
Everything else works fine (the size of the rectangle, the color of the rectangle), apart from the position of the rectangle: it is always positioned at 0,0 even though I (think) I have set the V & H positioning. An excerpt of the code is below; please advise.
int Severity = args.getPLR().get(i).getItems().get(j).getItems().get(itemIndex).getSeverity();
Severity = Severity + 5; //plump up, so that max (10) should fill the cell
PdfPCell cell = new PdfPCell();
cell.setPadding(0);
template = cb.createTemplate(Severity, Severity);
template.setLineWidth(0.5f);
template.rectangle(0, 0, Severity, Severity);
//we should switch the color
//based on the Severity
switch ((Severity-5)) {
    case 0:
        template.setColorFill(Color.GREEN);
        break;
    case 1:
        template.setColorFill(Color.GREEN);
        break;
    case 2:
        template.setColorFill(Color.YELLOW);
        break;
    case 3:
        template.setColorFill(Color.YELLOW);
        break;
    case 4:
        template.setColorFill(Color.YELLOW);
        break;
    case 5:
        template.setColorFill(Color.ORANGE);
        break;
    case 6:
        template.setColorFill(Color.ORANGE);
        break;
    case 7:
        template.setColorFill(Color.ORANGE);
        break;
    case 8:
        template.setColorFill(Color.RED);
        break;
    case 9:
        template.setColorFill(Color.RED);
        break;
    case 10:
        template.setColorFill(Color.RED);
        break;
}
template.fill();
img = Image.getInstance(template);
chunk = new Chunk(img, 0f, 0f);
cell.addElement(chunk);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
painTable.addCell(cell);

This is a graphic of what is shown:

It should be Center / Center. Where have I gone wrong?
This is the updated code part using the accepted solution:
img = Image.getInstance(template);
chunk = new Chunk(img, 0f, 0f);
Phrase severityChunk = new Phrase(chunk);
PdfPCell cell = new PdfPCell(severityChunk);
cell.setPadding(0);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
painTable.addCell(cell);

A: You're mixing text mode and composite mode.
Alignment properties set on the level of the PdfPCell work in text mode only. As soon as you switch to composite mode (you do so by using the addElement() method), iText ignores the alignment defined for the cell in favor of the aligment defined for the contents of the cell.
In text mode all the content has the same alignment. In composite mode, you can have different elements with different alignments.
You have different options: you can put the Chunk in a Paragraph and define the alignment for the paragraph instead of for the cell. You can create the cell in text mode using a Phrase that contains the Chunk. It may even be possible to create a cell with an Image without using a Chunk, etc...
This is all explained in the "iText in Action" book I wrote.

A: cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER) align the text of the cell in the center. You can see an example.
PdfPTable tablaTotal = new PdfPTable(2);
PdfPCell cell1 = new PdfPCell(new Phrase("TOTAL"));
cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
cell1.setPadding(5);
tablaTotal.addCell(cell1);
PdfPCell cell2 = new PdfPCell(new Phrase(contrato.getPrecioInmueble() + " €"));
cell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
cell2.setPadding(5);
tablaTotal.addCell(cell2);

We create tablaTotal with two columns, cell1 with the text Total, we align the text of the cell1 and add and padding to the cell1. We do the same to cell2 and we add the two cell to tablaTotal.


text:
Q: GIT: Workflow to sync work from two desktop and laptop and a central repo (server shared folder) I created a central repository (protocol:file) and I want to use that to keep in sync the work I do on my work laptop and my work desktop.
I am able to push and fetch files from the repo but I am not clear on how to merge things.
As far as I understand, after the files are in the central repo each computer will have a local master/head and a remote master/head.
The local master/head is considered a branch of the remote so every time when I commit and push a new branch shows up in the central repo. Here is the link that shows how I created the above described structures Working with GIT4Windows, shared folder and two computers-is this workflow correct?
I thought I was done and I planned to starting the work later (today is "later") and today I realized that I overlooked some aspects.
Consider this situation:
-a new module/feature was created on the laptop
-a new module/feature was created on the desktop
-each computer pushes its changes to the central repo
-now each computer can check out the other computer's new module and merge it in the local master and the two computers are in sync but the central repo has just two branches (the laptop one and the desktop one).
What happens if a third party wants to access the central repo? It will be confusing, when the repo is cloned the user gets an origin/master and two branches, one for the desktop one for the laptop.
What is the work flow to merge the two branches in the central repo? Is this the proper way to work with this setup?

A: There seem to be some slight misconceptions, so lets try to clear them up:

As far as I understand, after the files are in the central repo each computer will have a local master/head and a remote master/head.

Both repositories should have a master branch, correct. head has nothing to do with all of this, I think you're misusing this term.

The local master/head is considered a branch of the remote so every time when I commit and push a new branch shows up in the central repo.

Local master is a local branch. It is tracking the remote master, yes, but they are two different branches. Tracking means this branch will pull from X and push to X, however they are still two branches which can evolve independently. I'm particularly confused by your statement a new branch shows up in the central repo because when you push from master to master then no new branch shows up, master already existed. A few new commits show up on master though.

Consider this situation:
  -a new module/feature was created on the laptop
  -a new module/feature was created on the desktop
  -each computer pushes its changes to the central repo
  -now each computer can check out the other computer's new module and merge it in the local master and the two computers are in sync but the
  central repo has just two branches (the laptop one and the desktop
  one).
What happens if a third party wants to access the central repo? It
  will be confusing, when the repo is cloned the user gets an
  origin/master and two branches, one for the desktop one for the
  laptop.

You're missing an important step in your workflow, merging. There exist different workflows for git, however they pretty much share one true fact: There is one and only one branch in which all changes are collected, possibly merged from a feature branch. There is noting wrong with working directly on master though. Since - again - your local master and remote master are technically two branches, you can work on your local master directly, and when you're ready to "release" your code, push to remote. You'd possibly need to pull first to get new commits you haven't received yet, but it works.
Now you can of course work in different branches. Some git workflows recommend one branch for each feature (GitHub's pull-requests work using this model), or one branch for each computer or developer. But every once in a while, you need to collect all those changes made in different branches and put them in a single branch, usually master, which means you need to merge your changes to master. When and how is up to you. Usually, one would work on a development branch for a while until a feature is stable and works and then merge. master would, in this case, always contain a stable software and your development branches contain not-yet-finished features.


text:
Q: How to define a color scale conditional format in excel I am trying to set up a color scale conditional format on a column of data in Excel using C#. I have already successfully added other conditional format rules but I do not understand how to set this one up.
Here is a conditional rule which I have added which works:
Excel.Range Rng = workSheet.get_Range("H2", "J" + ExcelRowcount.ToString());                Excel.FormatConditions rule2 = Rng.FormatConditions;

Excel.FormatCondition between = (Excel.FormatCondition)rule2.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlBetween, 0.049999, 0.15, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Excel.Interior interior3 = between.Interior;
interior3.Color = ColorTranslator.ToOle(Color.LavenderBlush);

But now I am trying to make it a color scale rule and I do not understand how to format the long excel function, this is what I have so far
Excel.Range range = workSheet.get_Range("L2", "L" +ExcelRowcount.ToString());
Excel.FormatConditions rule3 = range.FormatConditions;

Excel.FormatCondition colorscale = (Excel.FormatCondition)rule3.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlColorScale, Excel.XlFormatConditionType.xlColorScale, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

The values in the column are the results of some computations and are not known before hand so I need the rule to scale from high to low values.
I have not been able to fine and example of this Excel.XlFormatConditionType used any where so if some one could help me out with this that would be really great!
Thanks!

A: I came across the same issue and for me the following worked for setting the colorscales:
MySheet = MyBook.Sheets.get_Item(1);

Excel.ColorScale cfColorScale = (Excel.ColorScale)(MySheet.get_Range("B15", "K34").FormatConditions.AddColorScale(3));
cfColorScale.ColorScaleCriteria[1].Type = Excel.XlConditionValueTypes.xlConditionValueLowestValue;
cfColorScale.ColorScaleCriteria[1].FormatColor.Color = 0x000000FF;  // Red

cfColorScale.ColorScaleCriteria[2].Type = Excel.XlConditionValueTypes.xlConditionValuePercentile;
cfColorScale.ColorScaleCriteria[2].Value = 50;
cfColorScale.ColorScaleCriteria[2].FormatColor.Color = 0x00FFCC00;  // yellow

cfColorScale.ColorScaleCriteria[3].Type = Excel.XlConditionValueTypes.xlConditionValueHighestValue;
cfColorScale.ColorScaleCriteria[3].FormatColor.Color = 0x0000FF00;  // green

I am myself quite new to C# and still learning... hence I cannot elaborate on the solution as I adapted this from code I found on google-code ->
https://code.google.com/p/innovtech/source/browse/trunk/InnovTech/InnovTech.Localization/ExcelFile.cs?spec=svn94&r=94
Hope it might help?


text:
Q: Recursion returning function without returning in special cases I need to combine a given password by bruteforce. So I decided to use recursion function which returns string
string bruteforce(string password, string forcedPassword)
{
    if (password.length() == forcedPassword.length())
    {
        if (password == forcedPassword)
        {
            return forcedPassword;
        }
        // What can I do here to return nothing and continue from the previous step?
    }

    for (int j = 32; j <= 126; j++)
    {
        forcedPassword += char(j);
        bruteforce(password, forcedPassword);
    }
}

int main()
{
   ...
   cin >> password;
   cout << bruteforce(password, "");
   ...
}

The problem is when I get password.length() == forcedPassword.length() but they are not the same. I need to exit only the last step of the recursion without any returning values. Is there any way to make it?

A: Assuming non empty password (else use optional), you may write:
std::string bruteforce(const std::string& password, const std::string& forcedPassword)
{
    if (password.length() == forcedPassword.length())
    {
        if (password == forcedPassword)
        {
            return forcedPassword;
        }
        return "";
    }

    for (int j = 32; j <= 126; j++)
    {
        auto res = bruteforce(password, forcedPassword + char(j));
        if (!res.empty()) {
            return res;
        }
    }
    return "";
}

A: I don't know if this will help you or not in your specific case:
std::string bruteforce( const std::string& enteredPassword, std::string& forcedPassword ) {

    if ( enteredPassword.length() == forcedPassword.length() ) {
        if ( enteredPassword == forcedPassword ) {
            return forcedPassword;
        }
        return "";
    }

    static int j = 31;
    while ( j <= 126 ) {
        ++j;
        // Display forcedPassword to test it for each recursive iteration
        std::cout << forcedPassword << "\n";
        return bruteforce( enteredPassword, forcedPassword + char( j ) );
    }
    return "";
}

int main() {
    std::string password;
    std::string forcedPassword( "Hello" );
    std::cout << "Enter the password\n";
    std::cin >> password;

    std::cout << bruteforce( password, forcedPassword );

    std::cout << "\Press any key and enter to quit.\n";
    char q;
    std::cin >> q;
    return 0;
}

But this does compile, build and run without errors, and there is no stack overflow here.
I made the enteredPassword a const ref since it will not be modified by this function. For the forcedPassword since you are showing that you are concatenating to this string I choose to make this a non const reference that will be modified. Instead of a for loop from [32,126], I choose to use a while loop using a static int counter. I initially set this value to 31 and check this loop while it is <= 126. Then within the loop I pre-increment the static counter, I then display the forcedPassword value for debugging purposes. Finally I return this recursive function passing in the original non modified enteredPassword along with the forcedPassword while updating it with char(j). For control paths where there are no operations to be made I simply just returned "";

A: Using bool function as suggested in comments you can do
#include <iostream>
using namespace std;

bool bruteforce(const string& password, string& forcedPassword, unsigned int length=0)
{
    if (password.length() == length)
    {
        if (password == forcedPassword)
        {
            return true;
        }
        return false;
    }

    for (int j = 32; j <= 126; ++j)
    {
        forcedPassword[length] = char(j);
        if ((bruteforce(password, forcedPassword, length+1)))
            return true;
    }
}

std::string findpassword(const string& password) {
    std::string forcedPassword = "";
    while (forcedPassword.length() < password.length())
        forcedPassword.push_back('a');
    if (bruteforce(password, forcedPassword))
        return forcedPassword;
    else
        return "failed";
}

int main()
{
   std::string password;
   cin >> password;
   cout << findpassword(password);
}


text:
Q: How to prevent onbeforeunload from being called when clicking submit button How can I prevent onbeforeunload from being called when clicking the submit button?
$(document).ready(function()
 {
  $('input:text,input:checkbox,input:radio,textarea,select').one('change', function()
  {
   //('BODY').attr('onbeforeunload',"return 'Leaving this page will cause any unsaved data to be lost.';");
   if(
   window.onbeforeunload = function() { return 'You have unsaved changes!'; }

  });

 });

A: You can't prevent the calling of unbeforeunload, but using a global flag variable, you can control whether it displays a warning.
in the document, add the script:
warn_on_unload = "You have unsaved changes!"

in the submit event, add:
warn_on_unload = "";

the definition of the event, change to:
window.onbeforeunload = function() { return warn_on_unload; }

through warn_on_unload, you can now switch the warning message on or off at will.

A: Here is the final code:
$(document).ready(function()
{
    var warn_on_unload="";
    $('input:text,input:checkbox,input:radio,textarea,select').one('change', function()
    {
        warn_on_unload = "Leaving this page will cause any unsaved data to be lost.";

        $('#submit').click(function(e) {
            warn_on_unload = "";});

            window.onbeforeunload = function() {
            if(warn_on_unload != ''){
                return warn_on_unload;
            }
        }
    });
});

A: you can use .on() to bind onbeforeunload and then use .off() to unbind it in form submission, short and sweet
$(document).ready(function () {
    $(window).on('beforeunload', function(){
        return "You have unsaved changes!";
    });
    $(document).on("submit", "form", function(event){
        $(window).off('beforeunload');
    });
}

A: Modified it : now ignores form submission
$(document).ready(function () {
var warn_on_unload = "";
$('input:text,textarea').on('change', function () {
    warn_on_unload = "Leaving this page will cause any unsaved data to be lost.";
    $("form").submit(function () {
        warn_on_unload = "";
    });
    window.onbeforeunload = function () {
        if (warn_on_unload != '') {
            return warn_on_unload;
        }
    }
});
});

A: If you just want to disable Onbeforeunload Event on submit button.
So here an example code
document.getElementById('sub').onsubmit = function(e) {
 window.onbeforeunload = null;
 return true;
}

But if you want to monitors forms changes and alerts(confirmation Box) the user before leaving the page, Then I'll suggest you to you Plugin here is one jquery plugin that do exactly what i have written https://github.com/snikch/jquery.dirtyforms
The Plugin Monitior Your forms changes and alert before leaving the Page
The Best Part "It will not dispaly the alert Box when you click on Submit Button" OR You Submit your Form
Example Code:-
<!DOCTYPE html>
 <html>
  <head>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0-beta00006/jquery.dirtyforms.min.js"></script>

  <script type="text/javascript">
    $(function() {
        $('#form_verify').dirtyForms();
    })
  </script>

  <title></title>
 <body>
<form id="form_verify" action="a.php" method="POST">
    Firt Name <input type="text">
    Last Name <input type="file">
    <input type="submit">
</form>


text:
Q: What does $\{0,1\}^J$ mean in math? "When accommodating customer choice behavior, we assume that the arriving customer chooses product j with probability $P_{t,j}(u)$, where $u \in \mathcal{U} \equiv \{0,1\}^J$ corresponds to the characteristic vector of the set of products currently being offered;"
What does $\{0,1\}^J$ mean?

A: It is basically a cartesian product, i.e.,
$u\in\{0,1\}^J$ iff $u=(u_j)_{j=1}^J$ with $u_i\in\{0,1\}$.
For generals sets, $R^D$ is the set of functions $f:D\to R$, which is equivalent to the definition given above.

A: Let $J$ represent the list of products. Let $j\in J$ represent a particular product (e.g. $j=$"iPhone"). Then $u_j=0$ probably means the person did not buy that product and $u_j=1$ probably means they did buy that product.
The space $\mathcal U=\{0,1\}^J$ would be the set of all binary vectors with $|J|$ components where $|J|$ is the total number of different products included in set $J$. It will just be a bunch of $|J|$-tuples with each having the form $(0,1,1,0,0,1,\ldots,0,1,1,0)$ with all possible arrangements of $0$'s and $1$'s included (and $|J|$ total digits in the list). I.e. $u=(1,1,1,\ldots, 1,1,1)$ means they bought every single product and all zeros implies they bought none of the products (presumably that's the interpretation).
It's just
$$\{0,1\}\times\{0,1\}\times\cdots\times\{0,1\}$$
with the appropriate number of repetitions of $\{0,1\}$. This is called a "Cartesian product" usually. where it just means you pick one value from each set in the product and combine them separated by commas encapsulated in parentheses.

A: It's a way to describe a vector of $1$'s and $0$'s. For example, if $J = 3$, you would have $$\mathcal U = \{ (0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1) \}.$$
The interpretation of, let's say, $u = (1,0,1)$ would be that customer chooses products 1 and 3, but not 2.
You might be familiar with notation $\mathbb R^3$, which would be the set of vectors of type $(x,y,z)$, where $x,y,z\in\mathbb R$. This is completely analogous.
As others noted, you could interpret it as the set of functions $u\colon J\to \{0,1\}$, but that's just a different way to describe the same thing, since for some $j\in J$, if $u(j) = 1$, the customer chooses product $j$, and if $u(j) = 0$, the customer doesn't choose the product $j$.


text:
Q: C# syntax help, date formatting and adding " to strings This is my first foray into C# as a SSIS and Informatica developer living only in SQL.  I have a script task that is reading data from a single SQL Server table via Query and simply writing that data to a text file. Everything works except what I think are  two small formatting problems I can't figure out.
The following requirements are in place for this build.  Thanks in advance I'm here to answer any questions!

*

*SQL query is purposefully set as a Select * to pick up any new columns added(already in code)

*First 3 columns excluded from write to file(already in code)

Problems:

*

*"  " wrappers need to be added to all values, column and rows.

*Date in database is true Date but when writing to file it shows Datetime.  Needs to be only date.

Current:

ID
Name
Date
Ratio

12345678
John Wayne
12/31/2018 12:00:00 AM
1/1

Needs to be:

"ID"
"Name"
"Date"
"Ratio"

"12345678"
"John Wayne"
"2018-12-31"
"1/1"

Code:
// Declare Variables
string DestinationFolder = Dts.Variables["User::Target_FilePath"].Value.ToString();
string QueryStage = Dts.Variables["User::Query_Stage"].Value.ToString();
//string TableName = Dts.Variables["User::TableName"].Value.ToString();
string FileName = Dts.Variables["User::OutputFileName"].Value.ToString();
string FileDelimiter = Dts.Variables["User::Target_FileDelim"].Value.ToString();
//string FileExtension = Dts.Variables["User::AC_Prefix"].Value.ToString();

//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_TEST_CONN"].AcquireConnection(Dts.Transaction) as SqlConnection);

// Read data from table or view to data table
string query = QueryStage;

SqlCommand cmd = new SqlCommand(query, myADONETConnection);
//myADONETConnection.Open();

DataTable d_table = new DataTable();
d_table.Load(cmd.ExecuteReader());
myADONETConnection.Close();

string FileFullPath = DestinationFolder + "\\" + FileName + ".txt";

StreamWriter sw = null;
sw = new StreamWriter(FileFullPath, false);

// Write the Header Row to File
int ColumnCount = d_table.Columns.Count;

for (int ic = 4; ic < ColumnCount; ic++)
{
    sw.Write(d_table.Columns[ic]);

    if (ic < ColumnCount - 1)
    {
        sw.Write(FileDelimiter);
    }
}

sw.Write(sw.NewLine);

// Write All Rows to the File
foreach (DataRow dr in d_table.Rows)
{
    for (int ir = 4; ir < ColumnCount; ir++)
    {
        if (!Convert.IsDBNull(dr[ir]))
        {
            sw.Write(dr[ir].ToString());
        }

        if (ir < ColumnCount - 1)
        {
            sw.Write(FileDelimiter);
        }
    }

    sw.Write(sw.NewLine);
}

sw.Close();

Dts.TaskResult = (int)ScriptResults.Success;

A: Blindly running .ToString() on an object, which is done in the line sw.Write(dr[ir].ToString());, is going to use the default settings of converting that data type into a string. If it's a DateTime (the c# data type, not the SQL Date column type), then it will include the time information.
C# converts SQL column types (such as Date) into C# data types (DateTime). You need to detect this, just as you're detecting if a value is DBNull.
if (!Convert.IsDBNull(dr[ir]))
{
    if (dr[ir] is DateTime dt)
    {
        // use DateTime's specific string rendering
        sw.Write(dt.ToString("d"));
    }
    else
    {
        // fall back to standard string rendering
        sw.Write(dr[ir].ToString());
    }
}

You can change out the format ("d" in this case) to be something else if you need a different format. Keep in mind that the Culture of a computer will affect how the string is rendered, unless you explicitly use a named Culture.

The other thing in your problem is adding quotes around printed values. This can be done with string concatination. For example:
string result = "\"" + "my string" + "\"";
// result is "my string", with quotes

Remember to escape the quote mark.


text:
Q: Getting HTTP 500 instead of HTTP 404 with WCF webapi I am having trouble returning the correct HTTP error code for a "not found" in my WCF Web API code. Here is my api method ...
    [WebInvoke(Method = "GET", UriTemplate = "{id}")]
    [RequireAuthorisation]
    public Customer GetCustomer(int id)
    {
        var customer = Repository.Find(id);
        if (customer == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return customer;
    }

I also have a logging handler ...
    protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message)
    {
        if (exception != null)
        {
            var msg = "Request failed.";
            _logger.Error(exception, msg);
        }

        message = new HttpResponseMessage
                      {
                          StatusCode = HttpStatusCode.InternalServerError
                      };

        return true;
    }

What is happening is I am getting the following exception ...
HttpResponseException

"The response message returned by the Response property of this exception should be immediately returned to the client.  No further handling of the request message is required."

... which my logging handler picks up and changes the response status code to a 500.
So, based on reading a few blog posts and answers on SO, I changed to this ...
        if (customer == null)
        {
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
            return null;
        }

... but this now give me a 200. Which is clearly wrong.
So, what is the right way to do this? It seems as if the throwing of the HttpResponseException doesn't work and the code after gets executed.

A: The code snippet for your error handler is always changing the response message to 500 no matter what as you are explicitly setting the status always to 500.
It sounds like what you are trying to do is return a 500 ONLY if it is an application error. If that is the case you should check if the error exception is an HttpResponseException and just return rather than overriding.
As to WebOperationContext, don't use it at all with Web Api as it is basically no-op.
Hope this helps
Glenn


text:
Q: How do I enable the Developer menu in Settings for Apple TV 4th Gen? I've seen a developer menu in the Settings app for iPhone and iPad. Recently I also got it to show up in the Settings app for my Apple TV 4 but I can't seem to remember how now. I ask because I enabled a feature that displays the refresh rate and bitrate for audio and video on the top left corner in yellow letters while beta testing tvOS 10.1 but when tvOS 10.1 GM was released, my Apple TV auto updated before I could turn it off but the yellow letters persists in the top left corner and the developer menu is gone. I added the new 10.1.1 beta profile so I could try to get the developer menu to show in the Settings app but so far it hasn't appeared on it's own. I know I could restore my Apple TV but I don't want to do that because I don't have a way to backup my app data and I know there's a way to enable that menu to show again I just don't know how. If you're familiar with the menu, it also allows you to create a custom "Service Provider" for the TV app and add your own URL for authentication as well. It's a menu item that shows up on the bottom of the Settings app. Does anyone know how to enable this menu?

A: If it is an ATV4, hook to Mac w/USB C, open Xcode & the developer menu will appear under Settinga on Apple TV.  Xcode is the trigger to make this menu visible.  All you have to do is open it.

A: Go to Settings -> Developer options -> Scroll down to Media service testing and Enable Playback HUD


text:
Q: Adding object to NSMutableArray as an object's associative reference I have the following:
static char associated_obj_key;
id anObj;

NSMutableArray *a = [[NSMutableArray alloc] init];
objc_setAssociatedObject(anObj, &associated_obj_key, a, OBJC_ASSOCIATION_RETAIN);
[a release];

And I'd like to know: how to add objects to the NSMutableArray inside an associative reference for the anObj object? Is it such a thing even possible?
Can I even do something like [objc_getAssociatedObject(anObj, &associated_obj_key) addObject:something];?

A: Yes, but you would have to have the same key all over the places. As using an address of some static variable is indeed a recommended way, I suggest factoring out the single method for obtaining a reference of an associated object (creating if necessary). I use the following:
- (NSMutableArray*) getOrCreateArray
{
    static const char key;
    NSMutableArray* arr = objc_getAssociatedObject(self, &key);
    if (!arr)
    {
        arr = [NSMutableArray array];
        objc_setAssociatedObject(self, &key, arr, OBJC_ASSOCIATION_RETAIN);
    }
    return arr;
}

- (void) someMethod
{
    id something = // ....
    [[self getOrCreateArray] addObject: something];
}


text:
Q: Determine whether $f(x)$ and $g(x)$ is decreasing or increasing without derivative Consider $f(x) = \frac{1}{\sqrt{x}} - x + 5$ and $g(x) = \frac{1}{\sqrt{x-1}} - \frac{1}{\sqrt{2-x}}$. We want to know that these functions are increasing or decreasing. I know that we can use determination sign of first derivative for checking it but I want the other ways to solve it. Also , one of the ways for doing it is that suppose $x_1<x_2$ and then prove $f(x_1) < f(x_2)$ or $f(x_1) > f(x_2)$ but I can't implement this method.If someone provide better ways or using this method is helpful.

A: Let us consider $0<x_1<x_2$
Since the square root function is strictly growing, $\sqrt{x_1} < \sqrt{x_2}$ and since the inverse is strictly decreasing, $\frac{1}{\sqrt{x_1}} > \frac{1}{\sqrt{x_2}}$
Obviously, $-x_1 > -x_2$
By summing, we get $f(x_1)>f(x_2)$
I let you do the other one in a similar fashion (this time, take $1<x_1<x_2<2$).
Following comment, hint for $g$
$x \rightarrow \frac{1}{\sqrt{x-1}} $ is strictly decreasing on $]1,2[$
$x \rightarrow \frac{1}{\sqrt{2-x}} $ is strictly increasing on $]1,2[$
You can show these in a similar fashion


text:
Q: Adding Layout to "SlideLayout" I have added SlideLayout this layout to my application.
I Added a layout to a SlideLayout but when I slide and get to that Layout tha activity file associated with it dont get called.
I have searched for this, but as I am a beginner I got greatly confused.
I dont know which code snippet i should attach.
the Slidelayout is this
I want to add a layout to its bottom whose activity file should get run as soon as I fling from bottom.
please help.


text:
Q: Frobenius norm bound Is there any way to bound the Frobenius norm of a product of square matrices $A,B$ and a vector $x$ in the following way:
$$
\|ABx\|≤ \|Ax\|\text{ and }\|B\|.
$$

A: The answer is no. Set
$$
A = \begin{pmatrix} 0 & c \\ 0 & 0 \end{pmatrix}, \quad
B  = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
$$
where $c > 0$ and let $x = (1,0)^T$, then $Ax$ is the zero vector but $\|ABx\| = c$ can be arbitrarily large.

A: If $A$ is invertible, then $$\|ABx\|=\|ABA^{-1}Ax\|\leq\|ABA^{-1}\|\|Ax\|=\kappa(A)\|B\|\|Ax\|,$$
where $\kappa(A)=\|A\|\|A^{-1}\|$ is the condition number of $A$. So yes, $\|ABx\|$ can be bounded by "something" involving $\|Ax\|$ and $\|B\|$ if $A^{-1}$ exists.


text:
Q: MongoDb registering class map I have the following code. I want MiscellaneousData to override an abstract MiscellaneousDataBase. However the IdMemberMap always comes up null.
Using a standalone 'normal' class works.
if (!BsonClassMap.IsClassMapRegistered(typeof(MiscellaneousData)))
{
    BsonClassMap.RegisterClassMap<MiscellaneousData>(cm =>
    {
        cm.AutoMap();
        cm.SetIdMember(cm.GetMemberMap(c => c.Key));
        cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance);
    });
}

Here is the miscellaneous data and its base - reduced down for clarity:
public abstract class MiscellaneousDataBase
{
    [XmlIgnore]
    public abstract string Key { get; set; }
}

public class MiscellaneousData : MiscellaneousDataBase
{
    public override string Key { get; set; }
}

A: When creating class maps you map each member at the level at which it is declared, so you need to map MiscellaneousDataBase and MiscellaneousData separately.
Below is some sample code showing how to map each class separately (I added an X property to the subclass so there would be something to map at that level).
Using these classes:
public abstract class MiscellaneousDataBase
{
    public abstract string Key { get; set; }
}

public class MiscellaneousData : MiscellaneousDataBase
{
    public override string Key { get; set; }
    public int X { get; set; }
}

try mapping them like this:
BsonClassMap.RegisterClassMap<MiscellaneousDataBase>(cm =>
{
    cm.AutoMap();
    cm.SetIdMember(cm.GetMemberMap(c => c.Key));
    cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance);
});

BsonClassMap.RegisterClassMap<MiscellaneousData>(cm =>
{
    cm.AutoMap();
    cm.GetMemberMap(c => c.X).SetElementName("x");
});


text:
Q: Way to join two databases in codeigniter in join query I want to know the syntax to join two databases in join query in CodeIgniter.
I am not getting the way to join two databases.
Please share if anyone has an idea.

A: first of all add 2nd database setting with you project/config/database.php file
$db['default'] = array(
'dsn'   => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db1',
    'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE);

$db['defaultdb'] = array(
'dsn'   => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
    'database' => 'dcz',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE);

then add this code start of your code
    $db1 = $this->load->database('defaultdb',TRUE);

    $queryfromDB1 = $this->db->get('Table_name')->result();

    $queryfromDB2 = $db1->get('Table_name')->result();


text:
Q: d3 v4 line chart data I want to use this line chart example with my new format data.
https://codepen.io/sky790312/pen/EbdRNb
Old data format and x-axis:
  const DATA1 = [9.5, 2, 5, 7, 5, 3, 0];
  const LABELS = [
    'monday',
    'tuesday',
    'wednesday',
    'thursday',
    'friday',
    'saturday',
    'sunday'
  ];

New data format::
  // parse the date / time
  const parseDate = d3.timeParse('%Y%m%d')
  const formatTime = d3.timeFormat('%y/%m/%d')

  const data = [
    {dataX: '20171016', dataY: 54.13},
    {dataX: '20171017', dataY: 50.13},
    {dataX: '20171018', dataY: 70.13},
    {dataX: '20171019', dataY: 53.98}]
  data.map(d => {
    d.dataX = parseDate(d.dataX)
    d.dataY = +d.dataY
  })

But I still facing some problem with the new format.

A: You will need to change the scale from scaleBand to timeScale then changes as per the new data set.

const graphContainer = d3.select(".d3--line");
const svg = d3.select("svg");
const margin = { top: 50, right: 50, bottom: 50, left: 50 };
const duration = 500;
let width, height, innerWidth, innerHeight;
let xScale, yScale;
const parseDate = d3.timeParse("%Y%m%d");
const formatTime = d3.timeFormat("%y/%m/%d");

const data = [
  { dataX: "20171016", dataY: 54.13 },
  { dataX: "20171017", dataY: 50.13 },
  { dataX: "20171018", dataY: 70.13 },
  { dataX: "20171019", dataY: 53.98 }
];
data.map(d => {
  d.dataX = parseDate(d.dataX);
  d.dataY = +d.dataY;
});

(function init() {
  getDimentions();
  getScaleDomains();
  getScaleRanges();
  renderGraph(data);
})();

d3.select(window).on("resize", resize);

function resize() {
  destroyGraph();
  getDimentions();
  getScaleRanges();
  renderGraph(data);
}

function renderGraph(data) {

  const line = d3
    .line()
    .x((d, i) => xScale(d.dataX))
    .y(d => yScale(d.dataY))
    .curve(d3.curveCatmullRom.alpha(0.5));

  const area = d3
    .area()
    .x((d, i) => xScale(d.dataX))
    .y0(innerHeight)
    .y1(d => yScale(d.dataY))
    .curve(d3.curveCatmullRom.alpha(0.5));

  const xAxis = d3.axisBottom(xScale).tickFormat((d, i) => formatTime(d)).ticks(4);

  const yAxis = d3.axisLeft(yScale).ticks(4);

  svg.attr("width", width).attr("height", height);

  const inner = svg.selectAll("g.inner").data([null]);
  inner.exit().remove();
  inner
    .enter()
    .append("g")
    .attr("class", "inner")
    .attr("transform", `translate(${margin.top}, ${margin.right})`);

  const horizontalLineGroup = svg
    .selectAll("g.inner")
    .selectAll(".line-group")
    .data([null]);
  horizontalLineGroup.exit().remove();
  horizontalLineGroup
    .enter()
    .append("g")
    .attr("class", "line-group");

  const horizontalLine = svg
    .selectAll("g.line-group")
    .selectAll(".grid-line")
    .data(yScale.ticks(4));
  horizontalLine.exit().remove();
  horizontalLine
    .enter()
    .append("line")
    .attr("class", "grid-line")
    .attr("x1", 0)
    .attr("x2", innerWidth)
    .attr("y1", d => yScale(d))
    .attr("y2", d => yScale(d));

  const xa = svg
    .selectAll("g.inner")
    .selectAll("g.x.axis")
    .data([null]);
  xa.exit().remove();
  xa
    .enter()
    .append("g")
    .attr("class", "x axis")
    .attr("transform", `translate(0, ${innerHeight})`)
    .call(xAxis);

  const ya = svg
    .selectAll("g.inner")
    .selectAll("g.y.axis")
    .data([null]);
  ya.exit().remove();
  ya
    .enter()
    .append("g")
    .attr("class", "y axis")
    .call(yAxis);

  const pathLine1 = svg
    .selectAll("g.inner")
    .selectAll(".path-line1")
    .data([null]);
  pathLine1.exit().remove();
  pathLine1
    .enter()
    .append("path")
    .attr("class", "path-line path-line1")
    .attr("d", () => line(createZeroDataArray(data)))
    .transition()
    .duration(duration)
    .ease(d3.easePoly.exponent(2))
    .attr("d", line(data));

  const pathArea1 = svg
    .selectAll("g.inner")
    .selectAll(".path-area1")
    .data([null]);
  pathArea1.exit().remove();
  pathArea1
    .enter()
    .append("path")
    .attr("class", "path-area path-area1")
    .attr("d", () => area(createZeroDataArray(data)))
    .transition()
    .duration(duration)
    .ease(d3.easePoly.exponent(2))
    .attr("d", area(data));
}

function destroyGraph() {
  svg.selectAll("*").remove();
}

function getDimentions() {
  width = graphContainer.node().clientWidth;
  height = 500;
  innerWidth = width - margin.left - margin.right;
  innerHeight = height - margin.top - margin.bottom;
}

function getScaleRanges() {
  xScale.range([0, innerWidth]);
  yScale.range([innerHeight, 0]).nice();
}

function getScaleDomains() {
  xScale = d3.scaleTime().domain(d3.extent(data, a => a.dataX));
  yScale = d3.scaleLinear().domain([0, d3.max(data, a=>a.dataY)]);
}

function createZeroDataArray(arr) {
  const newArr = [];
  arr.forEach((item, index) => (newArr[index] = { dataX: new Date(), dataY: 0 }));
  return newArr;
}

console.log("refres   h");
.d3 {
  box-shadow: 0 0 0 1px #eee;
  box-sizing: border-box;
}

path,
line {
  fill: none;
  shape-rendering: crispEdges;
  stroke: #E8E8E8;
}

.path-line {
  shape-rendering: initial;
}
.path-line.path-line1 {
  stroke: #0baadd;
}
.path-line.path-line2 {
  stroke: #47cf73;
}

.path-area {
  stroke: none;
}
.path-area.path-area1 {
  fill: rgba(11, 170, 221, 0.7);
  stroke: rgba(11, 170, 221, 0.7);
}
.path-area.path-area2 {
  fill: rgba(71, 207, 115, 0.55);
  stroke: rgba(71, 207, 115, 0.55);
}

.tick text {
  font-family: sans-serif;
  font-size: 10px;
  fill: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script>

<div class="d3 d3--line">
  <svg class="line-graph"></svg>
</div>

A: you have to use d3.scaleTime as your x axis :
https://bl.ocks.org/d3indepth/8948c9936c71e63ef2647bc4cc2ebf78
then when you bind attribute with data value you have to use:
xScale(d.dataX)

instead of :
xScale(LABELS[i])

same for y values use
d => yScale(d.dataY)

instead of
d => yScale(d)


text:
Q: How can I access the methods of Department class using Student class object Create a class Department with the following private member variables
int did
String dname

Include appropriate getters and setters method in Department class.
Create a class Student with the following private member variables
int sid
String sname
Department department

Include appropriate getters and setters method in Student class.
Create a TestMain class which has main method.
In addition to main method, create a method
       public static Student createStudent() -  All input as shown in the sample input should be got in this method.  Set the values to the Student object and return that object

Note : In main method, invoke the createStudent method and print the details of the object returned by that method.
I have already tried creating a new object using the name of Department but I am not able to access the methods
import java.util.Scanner;

public class TestMain {

    public static Student student;
    public static Department department;

    public static void main(String args[]) {
        createStudent();
        System.out.println("Department id:" + department.getDid());
        System.out.println("Department name:" + department.getDname());
        System.out.println("Student id:" + student.getSid());
        System.out.println("Student name:" + student.getSname());
    }

    public static Student createStudent() {
        Scanner sc = new Scanner(System.in);
        student = new Student();
        department = new Department();
        System.out.println("Enter the Department id:");
        department.setDid(sc.nextInt());
        System.out.println("Enter the Department name:");
        department.setDname(sc.next());
        System.out.println("Enter the Student id:");
        student.setSid(sc.nextInt());
        System.out.println("Enter the Student name:");
        student.setSname(sc.next());
        return student;
    }
}

public class Student {

    private int sid;
    private String sname;
    private Department department;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}

public class Department {

    private int did;
    private String dname;

    public int getDid() {
        return did;
    }

    public void setDid(int did) {
        this.did = did;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }
}

Sample Input 1:
Enter the Department id:
100
Enter the Department name:
Computerscience

Enter the Student id:
123
Enter the Student name:
Sudha

Sample Output 1:
Department id:100
Department name:Computerscience
Student id:123
Student name:sudha

A: you are missing:
student.setDepartment(department);

after that, you can do:
student.getDepartment().getSname();

A: import java.util.*;
public class TestMain
{
    public static Department d1;
    public static Student s1;
    public static Student createStudent()
    {
        Scanner sc=new Scanner(System.in);
        Student s1=new Student();
        Department d1=new Department();
        System.out.println("Enter the Department id:");
        int did=sc.nextInt();
        sc.nextLine();
        System.out.println("Enter the Department name:");
        String dname=sc.nextLine();
        System.out.println("Enter the Student id:");
        int sid=sc.nextInt();
        sc.nextLine();
        System.out.println("Enter the Student name:");
        String sname=sc.nextLine();
        d1.setDid(did);
        d1.setDname(dname);
        s1.setSid(sid);
        s1.setSname(sname);
        s1.setDepartment(d1);
        return s1;
    }
    public static void main(String[] args)
    {
        s1=TestMain.createStudent();
        System.out.println("Department id:"+d1.getDid());
        System.out.println("Department name:"+d1.getDname());
        System.out.println("Student id:"+s1.getSid());
        System.out.println("Student name:"+s1.getSname());
    }
}

A: public static void main(String args[]) throws NumberFormatException, IOException
{
 s1 =  createStudent();
 d1 = s1.getDepartment(); // THIS WAS MISSING IN ANSWER 2
 System.out.println("Department id:"+d1.getDid());
 System.out.println("Department name:"+d1.getDname());
 System.out.println("Student id:"+s1.getSid());
 System.out.println("Student name:"+s1.getSname());

}

A: In this case, there are 2 things that must be done.

*

*While "setting" values for all the ids and names, after the did and dname had been set, in order to access that via student object, you must "set" the did & dname combo to the department object inside student class.
department.setDid(did);
department.setDname(dname);
student.setSid(sid);
student.setSname(sname);
student.setDepartment(department);

*Also, now once this is set with right values, before the Sysout statements in Main, you  have to create an object for the Department class. And the data for this comes by calling the getDepartment() in student class (Remember that this function returns a Department object).
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Student student = createStudent();
    Department department = student.getDepartment();
    System.out.printf("Department id:%d",department.getDid()).println();
    System.out.printf("Department name:%s",department.getDname()).println();
    System.out.printf("Student id:%d",student.getSid()).println();
    System.out.printf("Student name:%s",student.getSname()).println();
}


text:
Q: CloudFoundry UAA Multi instances What's the recommended setup across CloudFoundry foundations for UAA? When clients can get routed between the foundations how are clients ensured they don't get re-authenticate?
More specifically: If an access/id token is generated in one foundation can it be used in the other foundation?

A: If you want to ensure that clients do not have to re-authenticate across multiple UAAs, you will have to ensure that the JWT signing key is the same in each foundation. You probably also want to make sure that the issuer field (properties.uaa.issuer in the BOSH deployment) is the same, though I'm less sure that that's required.


text:
Q: Delete Oldest Snapshot through API | Digital Ocean Hi There,
I'm working on bash script to take snapshots of Digital Ocean volumes and droplets through cURL api. I can get all snapshot list and post new snapshot through the script. However I can delete the snapshot through API by manual selecting the ID, but I want to automatation. For that I have to pick the ID of oldest snapshot from get response of snapshot list. can someone please help me in this regard?
My script:
#! /bin/bash

token= xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
get_list=$(curl -X GET \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $token" \
  "https://api.digitalocean.com/v2/snapshots?page=1&per_page=100&resource_type=volume")

echo $get_list > get_list

d=$(date +'%Y%m%d%H%M')

echo -e "Get List of Snapshots before delete\n" $get_list  "\n\n\n\n"
y=1
for ((x=21;x<=2602;x+=265))
do
id=${get_list:$x:36}
echo $id > id$y
((y += 1))
done
rm -rf id
#curl -X DELETE \
#-H 'Content-Type: application/json' \
#-H "Authorization: Bearer $token" \
#"https://api.digitalocean.com/v2/snapshots/${get_list:274:36}"

#get_list= $(curl -X GET -H "Content-Type: application/json" \
#-H "Authorization: Bearer $token" \
#"https://api.digitalocean.com/v2/droplets?page=1&per_page=100")

#echo -e "Get List of Snapshots after delete\n" $get_list  "\n\n\n\n"

#post_snap=$(curl -X POST \
# -H 'Content-Type: application/json' \
# -H "Authorization: Bearer $token" \
# -d '{"name":"'"$d"'"}' \
# "https://api.digitalocean.com/v2/volumes/6d44e0e2-4fc4-11ed-b137-0a58ac14c316/snapshots")

#get_list=$(curl -X GET \
#  -H 'Content-Type: application/json' \
#  -H "Authorization: Bearer $token" \
#  "https://api.digitalocean.com/v2/snapshots?page=1&per_page=100&resource_type=volume")

#echo -e "Get List of Snapshots after new snap\n" $get_list  "\n\n\n\n"

The list of snapshots from api response is pasted below:
{"snapshots":[{"id":"0e24bf13-515e-11ed-b137-0a58ac14c316","name":"202210211633","regions":["lon1"],"created_at":"2022-10-21T16:33:12Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"2ef69541-5162-11ed-9450-0a58ac14c2c7","name":"202210211702","regions":["lon1"],"created_at":"2022-10-21T17:02:45Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"689047e8-517a-11ed-a0ab-0a58ac14c028","name":"202210211955","regions":["lon1"],"created_at":"2022-10-21T19:56:10Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0,"tags":[]},{"id":"6cc0b0f2-516d-11ed-9fc6-0a58ac14c1c9","name":"2022-10-21_18:23","regions":["lon1"],"created_at":"2022-10-21T18:23:13Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"7e20fcfa-5171-11ed-a0ab-0a58ac14c028","name":"2022-10-21_18:52","regions":["lon1"],"created_at":"2022-10-21T18:52:20Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"96a3a010-515f-11ed-9fc6-0a58ac14c1c9","name":"2022-10-21-16-44","regions":["lon1"],"created_at":"2022-10-21T16:44:10Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"a13c0105-5178-11ed-9f93-0a58ac14c247","name":"2022-10-21-19-43","regions":["lon1"],"created_at":"2022-10-21T19:43:26Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"c4dfd95b-5174-11ed-b137-0a58ac14c316","name":"2022-10-21_19:15","regions":["lon1"],"created_at":"2022-10-21T19:15:47Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"d517a7f2-5169-11ed-a0ab-0a58ac14c028","name":"2022-10-21_17:57","regions":["lon1"],"created_at":"2022-10-21T17:57:30Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]},{"id":"f7180242-515a-11ed-b137-0a58ac14c316","name":"2022-10-21-16-11","regions":["lon1"],"created_at":"2022-10-21T16:11:05Z","resource_id":"6d44e0e2-4fc4-11ed-b137-0a58ac14c316","resource_type":"volume","min_disk_size":1,"size_gigabytes":0.0248,"tags":[]}],"links":{},"meta":{"total":10}}


text:
Q: Jenkins deletes keys in keychain We have a problem with fastlane when running on Jenkins. For some reason the key in the keychain gets removed when running the jenkins script. But if I run the command from command-line it works every time. First time I have provide password to gitrepo, second time it runs fine, but switching to Jenkins you can see the key is removed from keychain and subsequently it won't build (asking for password). See below for error log.
I've looked through all configuration I can find in jenkins but can't find anything that has to do with jenkins and keychain. We have one moduled installed for keychain:
Keychains and Provisioning Profiles Management, but this one is disabled just to see whether that one was the problem or not. But it didn't work after disabling it either. So I don't think it is that.
We're running Jenkins ver. 1.625.3 and fastlane latest version provided from zipfile due to issue with ssh and apple. See versions below. What are we missing?
Our fastlane build output:
16:42:50 [EnvInject] - Loading node environment variables.
16:42:50 Building remotely on myapp-mac-001 in workspace /Users/bob/workspace/myapp-ios
16:42:50 [WS-CLEANUP] Deleting project workspace...
16:42:50 [WS-CLEANUP] Done
16:42:50 Cloning the remote Git repository
16:42:50 Cloning repository ssh://server/git/myapp-ios.git
16:42:50  > /usr/bin/git init /Users/bob/workspace/myapp-ios # timeout=10
16:42:50 Fetching upstream changes from ssh://server/git/myapp-ios.git
16:42:50  > /usr/bin/git --version # timeout=10
16:42:50 using GIT_SSH to set credentials This key can authenticate against source servers
16:42:50  > /usr/bin/git fetch --tags --progress ssh://server/git/myapp-ios.git +refs/heads/*:refs/remotes/origin/*
16:42:52  > /usr/bin/git config remote.origin.url ssh://server/git/myapp-ios.git # timeout=10
16:42:52  > /usr/bin/git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
16:42:52  > /usr/bin/git config remote.origin.url ssh://server/git/myapp-ios.git # timeout=10
16:42:52 Fetching upstream changes from ssh://server/git/myapp-ios.git
16:42:52 using GIT_SSH to set credentials This key can authenticate against source servers
16:42:52  > /usr/bin/git fetch --tags --progress ssh://server/git/myapp-ios.git +refs/heads/feature/*:refs/remotes/origin/feature/*
16:42:53 Seen branch in repository origin/develop
16:42:53 Seen branch in repository origin/feature/fastlane_fix
16:42:53 Seen branch in repository origin/feature/new_structure
16:42:53 Seen branch in repository origin/master
16:42:53 Seen 4 remote branches
16:42:53 Checking out Revision 13a27f98eb9e879ccf31729401160af4217b3520 (origin/feature/new_structure)
16:42:53  > /usr/bin/git config core.sparsecheckout # timeout=10
16:42:53  > /usr/bin/git checkout -f 13a27f98eb9e879ccf31729401160af4217b3520
16:42:53  > /usr/bin/git rev-list 13a27f98eb9e879ccf31729401160af4217b3520 # timeout=10
16:42:53 Set build name.
16:42:53 New build name is '#213-origin/feature/new_structure'
16:42:53 [myapp-ios] $ /bin/sh -xe /var/folders/bw/fw05xx_12gjgrylcs4vcvf4c0000gp/T/hudson1075118741175647034.sh
16:42:53 + whoami
16:42:53 bob
16:42:53 + security list-keychains
16:42:53     "/Users/bob/Library/Keychains/login.keychain-db"
16:42:53     "/Library/Keychains/System.keychain"
16:42:53 + security default-keychain
16:42:53     "/Users/bob/Library/Keychains/login.keychain-db"
16:42:53 + security dump-keychain
16:42:53 + grep match
16:42:53     0x00000007 <blob>="match_ssh://server/git/myapp-configuration.git"
16:42:53     "srvr"<blob>="match_ssh://server/git/myapp-configuration.git"
16:42:53 [myapp-ios] $ /bin/sh -xe /var/folders/bw/fw05xx_12gjgrylcs4vcvf4c0000gp/T/hudson8479113557469598261.sh
16:42:53 + fastlane ios build app_identifier:com.myapp configuration:debug scheme:myapp verbose
16:42:54 [    16:42:50]: Your Fastfile has had smart quotes sanitised. To avoid issues in the future, you should not use TextEdit for editing it. If you are not using TextEdit, you should turn off smart quotes in your editor of choice.
16:42:54 [    16:42:50]: -------------------------------------------------
16:42:54 [    16:42:50]: --- Step: Verifying required fastlane version ---
16:42:54 [    16:42:50]: -------------------------------------------------
16:42:54 [    16:42:50]: Your fastlane version 1.110.0 matches the minimum requirement of 1.102.0  ✅
16:42:54 [    16:42:50]: ------------------------------
16:42:54 [    16:42:50]: --- Step: default_platform ---
16:42:54 [    16:42:50]: ------------------------------
16:42:54 [    16:42:50]: Driving the lane 'ios build'
16:42:54 [    16:42:50]: starting build
16:42:54 [    16:42:50]: -------------------
16:42:54 [    16:42:50]: --- Step: match ---
16:42:54 [    16:42:50]: -------------------
16:42:55 Successfully loaded Appfile at path '/Users/bob/workspace/myapp-ios/fastlane/Appfile'
16:42:55 - app_identifier: 'com.myapp'
16:42:55 - apple_id: 'mymail'
16:42:55 - team_id: 'someid'
16:42:55 -------
16:42:55 INFO [2016-11-21     16:42:51.55]: Successfully loaded '/Users/bob/workspace/myapp-ios/fastlane/Matchfile'
16:42:55
16:42:55 +----------------------+------------------------------------------------------------+
16:42:55 |                    Detected Values from './fastlane/Matchfile'                    |
16:42:55 +----------------------+------------------------------------------------------------+
16:42:55 | git_url              | ssh://server/git/myapp-configuration.git |
16:42:55 | username             | mymail                               |
16:42:55 +----------------------+------------------------------------------------------------+
16:42:55
16:42:55 DEBUG [2016-11-21     16:42:51.55]: Taking value for 'team_id' from environment variable 'FASTLANE_TEAM_ID'
16:42:55
16:42:55 +-----------------------+------------------------------------------------------------+
16:42:55 |                              Summary for match 0.11.0                              |
16:42:55 +-----------------------+------------------------------------------------------------+
16:42:55 | app_identifier        | com.myapp                                    |
16:42:55 | type                  | development                                                |
16:42:55 | readonly              | true                                                       |
16:42:55 | verbose               | true                                                       |
16:42:55 | git_url               | ssh://server/git/myapp-configuration.git |
16:42:55 | username              | mymail                               |
16:42:55 | git_branch            | master                                                     |
16:42:55 | keychain_name         | login.keychain                                             |
16:42:55 | team_id               | someid                                                 |
16:42:55 | force                 | false                                                      |
16:42:55 | skip_confirmation     | false                                                      |
16:42:55 | shallow_clone         | false                                                      |
16:42:55 | force_for_new_devices | false                                                      |
16:42:55 | skip_docs             | false                                                      |
16:42:55 +-----------------------+------------------------------------------------------------+
16:42:55
16:42:55 INFO [2016-11-21     16:42:51.55]: Cloning remote git repo...
16:42:55 INFO [2016-11-21     16:42:51.55]: $ GIT_TERMINAL_PROMPT=0 git clone 'ssh://server/git/myapp-configuration.git' '/var/folders/bw/fw05xx_12gjgrylcs4vcvf4c0000gp/T/d20161121-19169-opcqhe'
16:42:55 INFO [2016-11-21     16:42:51.57]: ▸ Cloning into '/var/folders/bw/fw05xx_12gjgrylcs4vcvf4c0000gp/T/d20161121-19169-opcqhe'...
16:42:55 INFO [2016-11-21     16:42:51.76]: ▸ remote: Counting objects: 1195, done.
16:42:56 INFO [2016-11-21     16:42:52.09]: ▸ remote: Compressing objects: 100% (1131/1131), done.
16:42:56 INFO [2016-11-21     16:42:52.31]: ▸ remote: Total 1195 (delta 116), reused 0 (delta 0)
16:42:56 INFO [2016-11-21     16:42:52.31]: ▸ Receiving objects: 100% (1195/1195), 2.26 MiB | 0 bytes/s, done.
16:42:56 INFO [2016-11-21     16:42:52.32]: ▸ Resolving deltas: 100% (116/116), done.
16:42:56 INFO [2016-11-21     16:42:52.34]: ▸ Checking connectivity... done.
16:42:56 WARN [2016-11-21     16:42:52.41]: Enter the passphrase that should be used to encrypt/decrypt your certificates
16:42:56 WARN [2016-11-21     16:42:52.41]: This passphrase is specific per repository and will be stored in your local keychain
16:42:56 WARN [2016-11-21     16:42:52.41]: Make sure to remember the password, as you'll need it when you run match on a different machine
16:42:56 WARN [2016-11-21     16:42:52.41]: Passphrase for Git Repo:
16:42:56 ERROR [2016-11-21     16:42:52.41]: Couldn't decrypt the repo, please make sure you enter the right password!
16:42:56 keychain: "/Users/bob/Library/Keychains/login.keychain-db"

A: To provide the encryption password on a CI, you can use the MATCH_PASSWORD environment variable.

A: You could try setting ENV['FASTLANE_PASSWORD'] (Apple Developer Portal password - mymail in your example) in your Fastfile which should make it available to your build.
As a side note: I have the Keychains and Provisioning Profiles Management plugin as well, but didn't need it to get match working. Hope this helps.


text:
Q: Start ruby app as service on CentOS 7 I have a ruby script (actually an example script from the Oxidized project), which is written in Ruby and opens a UDP port (514) listening for syslog messages and executing some code in the background.
The system runs on CentOS 7. I want to start this script as "service" automatically when the OS boots. The script however needs to run as a specific user (oxidized) and should be controllable using normal "service ... [start|stop|status|...|" behaviour. What would be the best way to achieve this?

A: Startup services can be managed by 2 different boot systems.
CentOS6 uses System V (Old Boot System)
CentOS7 uses Systemd (New Boot System) (Systemd does support System V scripts.)
Here is a link "How to write startup script for systemd"
https://unix.stackexchange.com/questions/47695/how-to-write-startup-script-for-systemd
Here is a link "How to write a System V init script to start, stop, and restart my own application or service"
https://www.cyberciti.biz/tips/linux-write-sys-v-init-script-to-start-stop-service.html


text:
Q: App icons go missing on MacBook I've been having this problem for a while now and it really starts to bother me. Every once in a while, a lot of my app icons go missing in the dock, launchpad, finder, cmd-tab switcher, just everywhere.
Some pictures:

Obviously this is really annoying.
I already tried a lot of stuff to solve it.

*

*I tried relaunching the Finder

*I tried relaunching the Dock (terminal: killall Dock)

*I tried clearing icon cache

The only way I can (temporarily) solve this by doing the following:

*

*Reboot, now the icons have reloaded in finder and launchpad, dock icons are still missing

*go to Library/preferences/com.apple.dock.plist
& delete the file

*open terminal: killall Dock
This way everything is fixed, but I have to rearrange my dock again since I removed the preferences file. It is only a temporary fix though, the issue keeps coming back and I always have to do this, which is very annoying.
Does anyone know what causes this? How could I solve it permanently? It's really getting frustrating!
Thanks a lot!

A: Rebuilding the macOS internal launch services database might help.
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -r -domain local -domain system -domain user

Once completed, you may need to restart Finder.
Sources:

*

*How to fix Mac desktop icons

*Rebuild LaunchServices to Fix Duplicate Entries in OS X's 'Open With' Menu

*Clean out a messy Open With menu in the Finder

A: resetting the icon cache worked for me.

*

*Launch Terminal

*Enter the following commands, one at a time:

sudo find /private/var/folders/ -name com.apple.dock.iconcache -exec rm {} \;
sudo find /private/var/folders/ -name com.apple.iconservices -exec rm -rf {} \;
sudo rm -rf /Library/Caches/com.apple.iconservices.store
killall Dock

A: How to Rebuild Launchpad Database in OS X Yosemite (10.10) and Later

*

*Go to Library folder, which is hidden. To access it, click anywhere on desktop and make sure you see word 'Finder' in the top menu near Apple logo.

*Press and hold alt/option key and in the top menu bar select Go and finally Library.

*In the Library folder, locate and open the Application Support folder.

*In the Application Support folder, locate and open the Dock folder.

*You'll find a number of files in the Dock folder, including one named desktoppicture.db, and one or more files starting with a dashed set of capital letters and numbers and ending in .db. An example file name is FE0131A-54E1-2A8E-B0A0A77CFCA4.db. Grab all the files in the Dock folder with the dashed set of letters and numbers that end in .db and drag them to the trash or press ⌘/command + delete keys.

*Launch Terminal, located in the /Applications/Utilities folder.

*In the Terminal window, enter the following:
defaults write com.apple.dock ResetLaunchPad -bool true; killall Dock
Launchpad has now been reset. The next time you open Launchpad, the app will rebuild the databases it needs. Launchpad may take a bit longer than usual to launch the first time, and the Launchpad display will now be in its default organization, with Apple apps shown first, and third-party apps next.

A: Use app Launchpad manager app and press Regenereate button on the menu

A: This issue may be caused by League of Legends.
https://boards.na.leagueoflegends.com/en/c/bug-report/rA0p1rYx-client-updating-on-mac-high-sierra-messes-up-other-application-icons
Unfortunately, it seems that no solution have been found yet.

A: Try this command in Terminal; it is working for me:
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user;ok

A: Eventually this is a MacOS software issue. You need to boot the mac into recovery mode and reinstall MacOs to fix the icons. It wont delete any information since its only rebuilding the system files. That should fix the missing icons.

A: To replace the generic dock icons with the actual application icon, here's what I did:

*

*Right click on the generic dock icon

*Choose Remove from Dock

*Open the application from the Applications Folder in Finder

*Drag the application back to the Dock

The new dock icon should be the proper one.


text:
Q: Add listboxitems programmatically C#/XAML windows store apps GoodDay! Im having a problem in my expandable/ collapsible listbox. Here's my code:
bool add = true;
public void AddList() {
    string[] win = { "Windows1", "Windows2" };
        foreach (string value in win)
        {
            ListMain.Items.Add(value);

        }

    }
    public void RemoveList() {
        string[] win = { "Windows1", "Windows2" };
        foreach (string value in win)
        {

            ListMain.Items.Remove(value);

        }
    }
private void ListMain_Tapped_1(object sender, TappedRoutedEventArgs e)
    {
        if (add == true)
        {
            this.AddList();

            add = false;
        }
        else {
            this.RemoveList();
            add = true;
        }

My ListMain is the ListBox, so everytime i tapped it, it will create items inside it namely windows1 and windows2, and when i tapped again my listmain, it will remove the windows1 and window2. My problem here is, when i tapped the windows1 or windows2, it automatically removed itself, it seems it shares the same tapped event with the listmain, how can i change the tapped event of the windows1 and windows2. Thanks for understanding. TYIA!

A: If you want to filter out the Tapped event on the ListBoxItems - add an event handler to Tapped on the ListBoxItems and set e.Handled = true; so it doesn't bubble up to the ListBox. Of course in your case you don't have access to the ListBoxItems so you might need to change your code a bit so that you add ListBoxItems explicitly to the ListBox and not rely on it to create those for you, e.g.
var lbi = new ListBoxItem { Content = value };
lbi.Tapped += this.OnListBoxItemTapped;
ListMain.Items.Add(lbi);

private void OnListBoxItemTapped(object sender, TappedRoutedEventArgs e)
{
    e.Handled = true;
}

Remember to remove the ListBoxItems in the RemoveList call and ubsubscribe from the event handlers:
lbi.Tapped -= this.OnListBoxItemTapped;


text:
Q: PayPal - Simple IPN I've a PayPal button on my site where people can donate money. Is there a simple automated way to send the donator an email that I received the donation?
Are there any workarounds with autoresponder or anything like that?
Thanks
Michael

A: Probably enable IPN in your account and then when donor make a donation, paypal will send a notification using IPN. you should be able to get the donor email using variable payer_email in the notification and then you can send donor an email.


text:
Q: jQuery menu stay open after link click I have a jQuery menu that opens on "click" and closes on "dblclick".
http://jsfiddle.net/snoffoz/4rZa9/1/
My problem is that it (submenu) closes after I click on a link.
Is there a way to make it only open/close when clicking on the main menu points (Menu 1, Menu 2)?
EDIT: My problem will not show up in jsfiddle since the links are not real.
The "ul" "li" is generated by Wordpress.
WP link http://wptemp.site90.net/

A: working demo http://jsfiddle.net/JuvwB/
If I may suggest you should try refactoring your unordered list, you had binding issue because  of the your top ul list li nest whole new ul i.e. horizontal menu.
This code should help you, All i did was return false when user will click on the nested list.
you can also try this: http://api.jquery.com/unbind/
Hope this helps, cheers!
code
jQuery.noConflict();
(function($) {
$(function() {

    // Dropdown Menu

    var timeout    = 100;
    var closetimer = 0;
    var ddmenuitem = 0;

    function jsddm_open() {
        jsddm_canceltimer();
        jsddm_close();
        ddmenuitem = $(this).find('ul').css('visibility', 'visible').parent().addClass('jsddm_hover').end();
    }
    function jsddm_close() {
        if(ddmenuitem) ddmenuitem.css('visibility', 'hidden').parent().removeClass('jsddm_hover');
    }
    function jsddm_timer() {
        closetimer = window.setTimeout(jsddm_close, timeout);
    }
    function jsddm_canceltimer() {
        if(closetimer) {
            window.clearTimeout(closetimer);
            closetimer = null;
        }
    }

    $('ul.jsddm li').bind('click', jsddm_open);

    $('ul.jsddm li').bind('dblclick',  jsddm_timer);
    $('ul.sub-menu li a').bind('dblclick', function(){
        return false;
    });
    //document.onclick = jsddm_close;

    $('.thumb img').after('');
    $('.thumb span').css('opacity','0');
    $('.post_home a:first-child').hover(function(){

    });

});
})(jQuery);