text:
Q: How To Add button in a Slide-out Sidebar Menu in ios programmatically I am pretty new in objective c so hopefully this all make sense.. I have declared UIView in .h file
@property (strong, nonatomic) UIView *menuViewone;

In .m file i declared UIView in viewdidload
menuViewone =[[UIView alloc ]initWithFrame:CGRectMake(-400, 0, 200, 568) ];
[menuViewone setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:menuViewone];

and set the view frame in Button method
 - (IBAction)collectionmenutwo:(id)sender {
    if (menuViewone.frame.origin.x >=0 ) {
        [UIView animateKeyframesWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            menuViewone.frame=CGRectMake(-400, 100, 300, 568);
        } completion:^(BOOL finished) {

        }];
    }

    else
    {
        [UIView animateKeyframesWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            menuViewone.frame=CGRectMake(200, 100, 300, 568);
        } completion:^(BOOL finished) {

        }];
    }}

Now i want to declare the buttons in this UIView ...How i can do that programmatically?

A: Just add buttons to the subview of that menuview of yours.
It would look something like this in the viewDidLoad of yours right after you declared your menuview.
UIButton *btn = [[UIButton] alloc] init];
btn.frame = CGRectMake(0,0,100,100);
//set other button properties here.
[menuViewone addSubview:btn];

For more specifics you can check this out:
How do I create a basic UIButton programmatically?


text:
Q: How to find a minimal sum of numbers associated with tuples of points so the points don't repeat? I have a structure of data that's presented like this:
List<Tuple<Tuple<Node, Node>, int>>

Node is just a point with x and y coordinates (integers). A Tuple is the C# Tuple so a pair of values. An int represents the minimal number of movements from source Node to destination Node. So to summarize, it's a List of pairs where first element is the pair consisted of Source and Destination and the second element is the minimal distance between them.
Right now Nodes in the list are repeating, because it contains all possible combinations, for example:
Sources:
0,0
1,1
Destinations:
2,2
3,3
List with distances:
((0,0 to 2,2) -> DISTANCE)
((0,0 to 3,3) -> DISTANCE)
((1,1 to 2,2) -> DISTANCE)
((1,1 to 3,3) -> DISTANCE)

What I'm trying to achieve is to calculate the minimal movements needed to move some things from all sources to available destinations. So in this case it would be sum of 2 distances, chosen in a way that it is minimal possible solution (sources nor distances can not repeat).
I've tried the simplest solution in which I just ordered my list by distances (from lowest to highest) and then I moved N elements to a result list in a way that sources nor destinations didn't repeat. But of course it's not that simple, because there are cases where it's better not to take a minimal distance to some Node because taking higher one may result in getting lower final result.
I hope that my description of the problem is understandable. I don't need an actual code, some help with getting an idea for an algorithm would be great.

A: While question description is rather vague, it seems that you need to determine the shortest paths between graph vertices. There are some algorithms for different kinds of this problem.
For limited number of source vertices it is worth to apply Dijkstra algorithm that searches shortest paths from given vertex to all others in O(V^2) time, so for K sources - O(K*V^2)
If number of sources is comparable with overall vertex count, you can use Floyd-Warshall algorithm giving distances between all pairs of vertices in O(V^3)

A: This sounds like the assignment problem - "finding a maximum weight matching (or minimum weight perfect matching) in a weighted bipartite graph" (from Wikipedia). I believe a classic solution for this is the Hungarian algorithm.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Full HD video converted to FLV, slow playback in browser I rendered a full HD video using Adobe AfterEffects CS5 in mp4 format. It plays just fine. I've got this video app to which I fed the mp4 file. The video app converts the mp4 to flv format and makes the video available via a web page. I've downloaded the resulting flv file to my local PC - it plays just fine in my VLC player. But, the problem is I'm getting awful playback inside my browser.
I've made sure the issue is not bandwidth related.
Both original mp4 file, and ffmpeg-converted FLV file, play perfectly using VLC player.
I've tested the FLV file with two players - Agryia FLV Player Elite and JW Player. Both players play the video awfully - really slow and very choppy.
Here's my ffmpeg -i myflvfile.flv:
`
Seems stream 0 codec frame rate differs from container frame rate: 119.88 (120000/1001) -> 59.92 (719/12)
Input #0, flv, from '94044631305552037.flv':
Metadata:
duration        : 146
width           : 1920
height          : 1080
videodatarate   : 684
framerate       : 60
videocodecid    : 7
audiodatarate   : 62
audiosamplerate : 22050
audiosamplesize : 16
stereo          : true
audiocodecid    : 2
major_brand     : mp42
minor_version   : 0
compatible_brands: mp42mp41
creation_time   : 2012-02-10 00:55:19
encoder         : Lavf52.111.0
filesize        : 61969316
Duration: 00:02:25.77, start: 0.034000, bitrate: 764 kb/s
Stream #0.0: Video: h264 (High), yuv420p, 1920x1080 [PAR 3:4 DAR 4:3], 700 kb/s, 59.92 tbr, 1k tbn, 119.88 tbc
Stream #0.1: Audio: mp3, 22050 Hz, stereo, s16, 64 kb/s`

Can any one point me in the right direction here? Why is playback perfect with VLC player of both the mp4 and the flv file on my local PC, yet in my browser, using two different players, the playback is so bad?
PS Here's my convert command:
ffmpeg -y -i /var/www/sandverlag.com/htdocs/rmtk/videos/originals/94044631305552038.mp4 -vcodec libx264 -ar 22050 -ac 2 -vb 700000 -s 1920x1080 -crf 22 -threads 0 -f flv /var/www/sandverlag.com/htdocs/rmtk/videos/converted/94044631305552038.flv > /dev/null &

A: A couple of thoughts:

*

*What version of Flash are you using?  Only the most recent versions of Flash in mainstream platforms support h264 hardware decoding.  Without the hardware decoding, many CPUs  can easily overtaxed with the h264 decoding.

*Why are you placing h264 video into an FLV container?  Flash supports MP4 containeres, like F4V.  In fact, I believe Adobe specifically recommends not using FLV containers for h264 video.  FLV is dated, move on.

*What hardware are you running?  VLC is highly optimized and seems to play almost anything without effort on even modest hardware.  Flash plugins don't exactly meet that level of playback performance.


text:
Q: Inheritance in iterable implementation of python's multiprocessing.Queue I found the default implementation of python's multiprocessing.Queue lacking, in that it's not iterable like any other collection. So I went about the effort of creating a 'subclass' of it, adding the feature in. As you can see from the code below, it's not a proper subclass, as multiprocess.Queue isn't a direct class itself, but a factory function, and the real underlying class is multiprocess.queues.Queue. I don't have the understanding nor effort to expend necessary to go about mimicking the factory function just so I can inherit from the class properly, so I simply had the new class create it's own instance from the factory and treat it as the superclass. Here is the code;
from multiprocessing import Queue, Value, Lock
import queue

class QueueClosed(Exception):
    pass

class IterableQueue:
    def __init__(self, maxsize=0):
        self.closed = Value('b', False)
        self.close_lock = Lock()
        self.queue = Queue(maxsize)

    def close(self):
        with self.close_lock:
            self.closed.value = True
            self.queue.close()

    def put(self, elem, block=True, timeout=None):
        with self.close_lock:
            if self.closed.value:
                raise QueueClosed()
            else:
                self.queue.put(elem, block, timeout)

    def put_nowait(self, elem):
        self.put(elem, False)

    def get(self, block=True):
        if not block:
            return self.queue.get_nowait()
        elif self.closed.value:
            try:
                return self.queue.get_nowait()
            except queue.Empty:
                return None
        else:
            val = None
            while not self.closed.value:
                try:
                    val = self.queue.get_nowait()
                    break
                except queue.Empty:
                    pass
            return val

    def get_nowait(self):
        return self.queue.get_nowait()

    def join_thread(self):
        return self.queue.join_thread()

    def __iter__(self):
        return self

    def __next__(self):
        val = self.get()
        if val == None:
            raise StopIteration()
        else:
            return val

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

This allows me to instantiate an IterableQueue object just like a normal multiprocessing.Queue, put elements into it like normal, and then inside child consumers, simply loop over it like so;
from iterable_queue import IterableQueue
from multiprocessing import Process, cpu_count
import os

def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

def consumer(queue):
    print(f"[{os.getpid()}] Consuming")
    for i in queue:
        print(f"[{os.getpid()}] < {i}")
        n = fib(i)
        print(f"[{os.getpid()}] {i} > {n}")
    print(f"[{os.getpid()}] Closing")

def producer():
    print("Enqueueing")
    with IterableQueue() as queue:
        procs = [Process(target=consumer, args=(queue,)) for _ in range(cpu_count())]
        [p.start() for p in procs]
        [queue.put(i) for i in range(36)]
    print("Finished")

if __name__ == "__main__":
    producer()

and it works almost seamlessly; the consumers exit the loop once the queue has been closed, but only after exhausting all remaining elements. However, I was unsatisfied with the lack of inherited methods. In an attempt to mimic actual inheritance behavior, I tried adding the following meta function call to the class;
def __getattr__(self, name):
    if name in self.__dict__:
        return self.__dict__[name]
    else:
        return self.queue.__getattr__[name]

However, this fails when instances of the IterableQueue class are manipulated inside child multiprocessing.Process threads, as the class's __dict__ property is not preserved within them. I attempted to remedy this in a hacky manner by replacing the class's default __dict__ with a multiprocessing.Manager().dict(), like so;
def __init__(self, maxsize=0):
    self.closed = Value('b', False)
    self.close_lock = Lock()
    self.queue = Queue(maxsize)
    self.__dict__ = Manager().dict(self.__dict__)

However on doing so, I received an error stating RuntimeError: Synchronized objects should only be shared between processes through inheritance. So my question is, how should I go about inheriting from the Queue class properly such that the subclass has inherited access to all of it's properties? In addition, while the queue is empty but not closed, the consumers all sit in a busy loop instead of a true IO block, taking up valuable cpu resources. If you have any suggestions on concurrency and race condition issues I might run into with this code, or how I might solve the busy loop issue, I'd be willing to take suggestions therein as well.

Based on code provided by MisterMiyagi, I created this general purpose IterableQueue class which can accept arbitrary input, blocks properly, and does not hang on queue close;
from multiprocessing.queues import Queue
from multiprocessing import get_context

class QueueClosed(Exception):
    pass

class IterableQueue(Queue):
    def __init__(self, maxsize=0, *, ctx=None):
        super().__init__(
            maxsize=maxsize,
            ctx=ctx if ctx is not None else get_context()
        )

    def close(self):
        super().put((None, False))
        super().close()

    def __iter__(self):
        return self

    def __next__(self):
        try:
            return self.get()
        except QueueClosed:
            raise StopIteration

    def get(self, *args, **kwargs):
        result, is_open = super().get(*args, **kwargs)
        if not is_open:
            super().put((None, False))
            raise QueueClosed
        return result

    def put(self, val, *args, **kwargs):
        super().put((val, True), *args, **kwargs)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

A: The multiprocess.Queue wrapper only serves to use the default context.
def Queue(self, maxsize=0):
    '''Returns a queue object'''
    from .queues import Queue
    return Queue(maxsize, ctx=self.get_context())

When inheriting, you can replicate this in the __init__ method. This allows you to inherit the entire Queue behaviour. You only need to add the iterator methods:
from multiprocessing.queues import Queue
from multiprocessing import get_context

class IterableQueue(Queue):
    """
    ``multiprocessing.Queue`` that can be iterated to ``get`` values

    :param sentinel: signal that no more items will be received
    """
    def __init__(self, maxsize=0, *, ctx=None, sentinel=None):
        self.sentinel = sentinel
        super().__init__(
            maxsize=maxsize,
            ctx=ctx if ctx is not None else get_context()
        )

    def close(self):
        self.put(self.sentinel)
        # wait until buffer is flushed...
        while self._buffer:
            time.sleep(0.01)
        # before shutting down the sender
        super().close()

    def __iter__(self):
        return self

    def __next__(self):
        result = self.get()
        if result == self.sentinel:
            # re-queue sentinel for other listeners
            self.put(result)
            raise StopIteration
        return result

Note that the sentinel to indicate end-of-queue is compared by equality, because identity is not preserved across processes. The often-used queue.Queue sentinel object() does not work properly with this.


text:
Q: Torque and moment of inertia with bikes Can someboby please explain to me why it is better for a bicycle/ motor cycle to have lower center of mass when it rounds a turn.
What I could gather from the rule  I = mr2
Was that the arm is shorter so less moment of inertia but what does that have you do with doing a better turn

A: It is not helpful to consider the moment of inertia of the bike about its centre of rotation. All you need to consider are the forces on the cyclist/biker. The centripetal force from the friction of the tyre on the road $mv^2/r$, together with the inertia of the cyclist and bicycle form an overturning couple. (These can alternatively be considered as frictional reaction and centrifugal force respectively). This couple is balanced by the one from the weight and the vertical reaction (presuming the cyclist is leaning into the turn).
If the centre of gravity is lower, the overturning moment will be correspondingly less and that is preferable. However, it should be pointed out that, if the angle of lean is the same (and the velocity and radius of turn), the bicycle will be equally well balanced with a high C of G because both couples will increase by the same amount. However, the same cannot be said of a car, where resistance to overturning is maintained by the fixed horizontal distance between its centre of mass and the outer wheels, so there is no question that a low centre of mass is desirable for a car driving on a bend.


text:
Q: FanDuel NBA Lineup Optimizer This code runs without error and for the life of me I can't put my finger on why it doesn't return any output besides a "Usage: " message followed by the path to the CSV file it should be reading/parsing.
Any help is appreciated.
salary_cap = 60000

def get_position_number(name):
    return {
        'Center': 0,
        'Point Guard': 1,
        'Power Forward': 2,
        'Shooting Guard': 3,
        'Small Forward': 4
    }[name]

def main(a, y):
    solver = pywraplp.Solver('CoinsGridCLP',
    pywraplp.Solver.CBC_MIaED_INTEGER_PROGRAMMING)

range_c = range(len(a[0]))
range_pg = range(len(a[1]))
range_pf = range(len(a[2]))
range_sg = range(len(a[3]))
range_sf = range(len(a[4]))

take_c = [solver.IntVar(0, 1, 'take_c[%i]' % j) for j in range_c]
take_pg = [solver.IntVar(0, 1, 'take_pg[%i]' % j) for j in range_pg]
take_pf = [solver.IntVar(0, 1, 'take_pf[%i]' % j) for j in range_pf]
take_sg = [solver.IntVar(0, 1, 'take_sg[%i]' % j) for j in range_sg]
take_sf = [solver.IntVar(0, 1, 'take_sf[%i]' % j) for j in range_sf]

teams_c = []
teams_pg = []
teams_pf = []
teams_sg = []
teams_sf = []

for teamNumber in range(0, 29):
    teams_c.insert(teamNumber, solver.Sum([(a[0][i][3] == teamNumber + 1) * take_c[i] for i in range_c]))
    teams_pg.insert(teamNumber, solver.Sum([(a[1][i][3] == teamNumber + 1) * take_pg[i] for i in range_pg]))
    teams_pf.insert(teamNumber, solver.Sum([(a[2][i][3] == teamNumber + 1) * take_pf[i] for i in range_pf]))
    teams_sg.insert(teamNumber, solver.Sum([(a[3][i][3] == teamNumber + 1) * take_sg[i] for i in range_sg]))
    teams_sf.insert(teamNumber, solver.Sum([(a[4][i][3] == teamNumber + 1) * take_sf[i] for i in range_sf]))

value_c = solver.Sum([a[0][i][1] * take_c[i] for i in range_c])
value_pg = solver.Sum([a[1][i][1] * take_pg[i] for i in range_pg])
value_pf = solver.Sum([a[2][i][1] * take_pf[i] for i in range_pf])
value_sg = solver.Sum([a[3][i][1] * take_sg[i] for i in range_sg])
value_sf = solver.Sum([a[4][i][1] * take_sf[i] for i in range_sf])

salray_c = solver.Sum([a[0][i][2] * take_c[i] for i in range_c])
salray_pg = solver.Sum([a[1][i][2] * take_pg[i] for i in range_pg])
salray_pf = solver.Sum([a[2][i][2] * take_pf[i] for i in range_pf])
salray_sg = solver.Sum([a[3][i][2] * take_sg[i] for i in range_sg])
salray_sf = solver.Sum([a[4][i][2] * take_sf[i] for i in range_sf])

solver.Add(salray_c + salray_pg + salray_pf + salray_sg + salray_sf <= y)

solver.Add(solver.Sum(take_c[i] for i in range_c) == 1)
solver.Add(solver.Sum(take_pg[i] for i in range_pg) == 2)
solver.Add(solver.Sum(take_pf[i] for i in range_pf) == 2)
solver.Add(solver.Sum(take_sg[i] for i in range_sg) == 2)
solver.Add(solver.Sum(take_sf[i] for i in range_sf) == 2)

# Maa 4 a per team
for i in range(0, 29):
    solver.Add(teams_c[i] + teams_pg[i] + teams_pf[i] + teams_sg[i] + teams_sf[i] <= 4)

solver.Maaimize(value_c + value_pg + value_pf + value_sg + value_sf)
solver.Solve()
assert solver.VerifySolution(1e-7, True)
print('Solved in', solver.wall_time(), 'milliseconds!', "\n")
salary = 0

for i in range_c:
    if take_c[i].SolutionValue():
        salary += a[0][i][2]
        print(a[0][i][0], '(C): ${:,d}'.format(a[0][i][2]), '(' + str(a[0][i][1]) + ')')

for i in range_pg:
    if take_pg[i].SolutionValue():
        salary += a[1][i][2]
        print(a[1][i][0], '(PG): ${:,d}'.format(a[1][i][2]), '(' + str(a[1][i][1]) + ')')

for i in range_pf:
    if take_pf[i].SolutionValue():
        salary += a[2][i][2]
        print(a[2][i][0], '(PF): ${:,d}'.format(a[2][i][2]), '(' + str(a[2][i][1]) + ')')

for i in range_sg:
    if take_sg[i].SolutionValue():
        salary += a[3][i][2]
        print(a[3][i][0], '(SG): ${:,d}'.format(a[3][i][2]), '(' + str(a[3][i][1]) + ')')

for i in range_sf:
    if take_sf[i].SolutionValue():
        salary += a[4][i][2]
        print(a[4][i][0], '(SF): ${:,d}'.format(a[4][i][2]), '(' + str(a[4][i][1]) + ')')

print("\n", 'Total: ${:,d}'.format(salary), '(' + str(solver.Objective().Value()) + ')')

if len(sys.argv) < 2:
    print('Usage:', sys.executable, sys.argv[0], 'players.csv')
    sys.exit(1)

team = [[], [], [], [], []]

with open('players.csv') as csvfile:
    reader = csv.DictReader(csvfile)

for row in reader:
    team[get_position_number(row['Subposition'])].append(
        [row['Name'], float(row['Value']), int(row['Salary']), int(row['Team'])]
    )

main(team, salary_cap)

A: What is happening
The following bit of code
if len(sys.argv) < 2:
    print('Usage:', sys.executable, sys.argv[0], 'players.csv')
    sys.exit(1)

checks if the argument vector, a list that contains the name of your script and all parameters given to it via command line, is shorter than two.
As an example, take the following file:
import sys
print(sys.argv, len(sys.argv))

If you run:
$ python your_script.py
$ ['your_script.py'] 1
$ python your_script.py parameter
$ ['your_script.py', 'parameter'] 2

In the first example the argument vector has length one, in the second it has length two.
Back to your script. If the argument vector has less then two entries, i.e. no parameters were given by the user, the program terminates with error code 1 (sys.exit(1), every value != 1 indicates an error).
How to fix it
You need to give your script a .csv file as first command line parameter:
$ python your_script players.csv

Otherwise the script has nothing to work with. Dave Hensley also mentions this in the README of this script in the section Usage.


text:
Q: Ocaml: How to "easy" map a list of records to a list of record.field? Suppose that I have the following record:
type t = {a:int}

In order to select the values of field a from a list I do the following:
let x = [{a=1};{a=2}]
let y = List.map (fun t -> t.a) x

This is a bit "unclean" to me. As a comparison, In Haskell I would do the following:
data T = T { a :: Int}
x = [T {a = 1}, T {a = 2}]
y = map a x

Is there a way to write something similar in Ocaml (maybe using external libraries)?
If not possible can someone explain why this limitation?

A: If you use Jane Street's fieldslib library, available with core, then you can write:
type t = { a:int; b:int } with fields

and that gives you a and b as selector functions of type t -> int
It also gives you a submodule called Fields of so-called first-class fields, which include the selector, the mutator, and, critically for some applications, the string name of the field.  This is very useful for generating good error messages in validations functions, for example.
You also get some higher-order functions on the entire record, most usefully a fold over the record.

A: Unlike Standard ML, Ocaml doesn't have first-class selectors for records.(source)
As for why it cannot be done, that's simply a design choice that was made.

A: Haskell implicitly creates selector functions for field names. OCaml doesn't do this. You could just manually define them whenever you create record types, and it would be equivalent to what the Haskell code does.
type t = {a:int, b:int}
let a x = x.a
let b x = x.b


text:
Q: How to install software on Windows in isolation? I usually try different kind of softwares which are available on net those can be trial versions or sharewares or freewares. But after trying them when I want to uninstall those its becoming really difficult sometimes and I'm not sure they are fully uninstalled from my computer and some times those softwares giving unnecessary burden to system by leaving some data in the registry.
I want to find a solution or a way to virtually install any software on my computer. Is it possible?

A: As you may already be aware, you can create a Virtual Machine in any virtualization software. Ideally, you would want virtualization software that lets you create snapshots before installing the software, and revert to the snapshot to go back to that exact state and remove all traces of the software you installed. VMware, VirtualBox, and other products allow you to create one or more snapshots. For those virtualization products that don't, you can manually backup the VM image or folder, then install your software and optionally restore the backup if you decide you want to rollback.
Another alternative is to use software that sandboxes your application, such as Sandboxie.
Yet another option is to use backup software that lets you snapshot your live OS and later revert your system to that state. Acronis TrueImage advertises a feature called "Try & Decide" which does this.

A: to achieve what you want one usually tries to isolate the application as much as possible from the rest of the system. the easiest way to do this is to give it it's own OS, running on it's own hardware. you can do that with products like VirtualBox, VMWare, QEmu, VirtualPC, VMLite etc.
if you do not provide that kind of full level of isolation you might want to use something called 'application virtualization'. some products falling into this category are:

*

*Cameyo

*Spoon (they provide some images of known apps already)

*Enigma
but, depending on how hard an application wants to sidestep application virtualization, it might work or it might not work. eg, an app checking out the MAC of the NIC to call home and report back that the trial for the machine with the MAC of xyz started now. in these cases only full virtualization helps (because you could "exchange" the NIC the next time, or even keep the date constant etc).

A: Revo Uninstaller Pro has a "Real-Time
Installation Monitor":

Revo Uninstaller Pro has a feature that allows monitoring of
  installation of a program. It detects system changes during that
  installation and the process is done in real time.
<snip> promotional stuff removed </snip>
  monitor installations, so when the program is no longer needed the
  system changes made by the installation of the monitored program could
  be fully reverted as the program has never been installed before!

It's similar to Cameyo and Spoon as akira suggested (I don't know about Enigma). The difference is Cameyo and Spoon are designed towards packaging programs, usually used to make them portable, while Revo Uninstaller is designed to revert changes a program has made during installation.
Aside from that, it has a "Forced Uninstall". From what I understand, it deletes all files and registry entries that contain the program and/or publisher name. I would not recommend using this if possible; it can easily break something (e.g. if you uninstall "Microsoft Office Word 2010", it might decide "Microsoft Visual Studio 2010" entries should be removed, breaking that). Always backup your registry before trying anything like "cleaning" it.


text:
Q: Property missing in cosmos mongodb property after insertion I have a .Net Core 2.1 Web API Which Inserts a Record into MongoDB(Azure CosmosDB Mongo Variant) with multiple properties like Id, Status, DateTime and other Objects.
Later I have added another Property named Title and now when I hit the API it inserts the Record but it this newly added 'Title' Property is not added to the Collection.

*

*While Debugging, I have checked the property is available just before it is inserted.

*I added a property with a new name still it didn't work.

*If I am updating an existing record with the 'Title' property value then the Title property is getting added.

*If I am inserting new record Title property is missing

*If I check from Mongo Compass, Just when I finish API and refresh the collection I find the Record inserted with the Title property populated but once I refresh again then Title property is missing.

I suspect it is because of the DLL reference that is cached somewhere. I have tried removing all the references related to that DLL and refreshed them (even that did not work)
I am using MongoDB Driver 2.8.0


text:
Q: wait for expectation but continue What is the best way to wait for an expectation to happen, but continue otherwise? I have tried:
expectation(for: NSPredicate(format: "exists == true"), evaluatedWith: app.buttons["myButton"], handler: nil)
waitForExpectations(timeout: 5) { (error) -> Void in
            if error == nil {
                // Do other stuff and continue
            }
}
//continue

Unfortunatelly, that doesn't work since the test stops if the expectation isn't met

A: In the case of exists == true, you can use waitForExistence -> which returns a boolean value. Once that boolean value is returned (after your timeout is reached.. or when the element exists) you could use that value to determine whether or not to continue. i.e.
let myButtonExists = app.buttons["myButton"].waitForExistence(timeout: 5)
if myButtonExists {
   //do something
} else {
   //do something else
}

https://developer.apple.com/documentation/xctest/xcuielement/2879412-waitforexistence


text:
Q: Spring boot batch - Running multiple batch jobs from schedule tasks causing concurrency issue I have created three different batch jobs using spring boot + batch. When i try to run these jobs via scheduled tasks. At same time (with few seconds difference). I run into unexpected issues in Filereader as its start reporting parsing exceptions. This works fine if is run these jobs in order or via CommandLineRunner (which run one job at a time). Each reader component is configured at Step scope. Can someone please take a look and suggest a possible fix ? Code below.
Job 1 :

        @Bean(JOB_NAME)
        public Job importMonetryFilesJob(JobCompletionNotificationListener listener) {
            return jobBuilderFactory.get(JOB_NAME).incrementer(new RunIdIncrementer()).listener(listener).flow(step1())
                    .end().build();
        }

        @SuppressWarnings("unchecked")
        @Bean(STEP_1)
        public Step step1() {
            TaskletStep step1 = stepBuilderFactory.get(STEP_1).<RawMonteryFileInput, RawMonteryFileInput>chunk(1)
                    .reader(reader()).processor(processor()).writer(writer()).faultTolerant()
                    .skipPolicy(new JobSkipPolicy()).listener(monetryCustomSkipListener()).build();
            step1.registerStepExecutionListener(batchSweepStepContext());
            return step1;
        }

        @Bean(READER_NAME)
        @StepScope
        public MultiResourceItemReader<RawMonteryFileInput> reader() {

            MultiResourceItemReader<RawMonteryFileInput> multiReader = new MultiResourceItemReader<RawMonteryFileInput>();

            multiReader.setResources(inputFiles);
            multiReader.setDelegate(readerInternal());
            return multiReader;
        }

        @Bean(READER_NAME + "_internal")
        @StepScope
        public FlatFileItemReader<RawMonteryFileInput> readerInternal() {
            CustomFlatFileItemReader<RawMonteryFileInput> reader = new CustomFlatFileItemReader<>();
            reader.setRecordSeparatorPolicy(new MergingItemSeparator());
            reader.setLineMapper(sourceAwareLineMapper());
            reader.setFileLocation(processedFilesLocation);
            return reader;
        }

        @Bean(PROCESSOR_NAME)
        @StepScope
        public ValidatingItemProcessor<RawMonteryFileInput> processor() {
            SpringValidator<RawMonteryFileInput> springValidator = new SpringValidator<RawMonteryFileInput>();
            springValidator.setValidator(validator);
            return new ValidatingItemProcessor<RawMonteryFileInput>(springValidator);
        }

        @Bean(WRITER_NAME)
        @StepScope
        public FlatFileItemWriter<RawMonteryFileInput> writer() {

            FlatFileItemWriter<RawMonteryFileInput> writer = new FlatFileItemWriter<RawMonteryFileInput>();
            writer.setResource(new FileSystemResource(getWriterFileName()));
            writer.setShouldDeleteIfEmpty(true);
            writer.setLineAggregator(new CustomDelimitedLineAggregator<RawMonteryFileInput>() {
                {
                    setDelimiter("|");
                    setFieldExtractor(new CustomBeanWrapperExtractor<RawMonteryFileInput>() {
                        {
                            setNames(MonetryJobConstants.WRITER_HEADER);
                        }
                    });
                }
            });
            return writer;
        }

    Job 2 :

        @Bean(JOB_NAME)
        public Job importAccountBalanceJob(JobCompletionNotificationListener listener) {
            return jobBuilderFactory.get(JOB_NAME).incrementer(new RunIdIncrementer()).listener(listener).flow(step1())
                    .end().build();
        }

        @SuppressWarnings("unchecked")
        @Bean(STEP_1)
        public Step step1() {
            TaskletStep step1 = stepBuilderFactory.get(STEP_1).<AccountBalanceFileInput, AccountBalanceFileInput>chunk(1)
                    .reader(reader()).processor(processor()).writer(writer()).faultTolerant()
                    .skipPolicy(new JobSkipPolicy()).listener(accountBalanceCustomSkipListener()).build();
            step1.registerStepExecutionListener(batchSweepStepContext());
            return step1;
        }

        @Bean(READER_NAME)
        @StepScope
        public MultiResourceItemReader<AccountBalanceFileInput> reader() {

            // Assert.notEmpty(inputFiles, "Input files on location are required.");
            MultiResourceItemReader<AccountBalanceFileInput> multiReader = new MultiResourceItemReader<AccountBalanceFileInput>();

            multiReader.setResources(inputFiles);
            multiReader.setDelegate(readerInternal());
            return multiReader;
        }

        @Bean(READER_NAME + "_internal")
        @StepScope
        public FlatFileItemReader<AccountBalanceFileInput> readerInternal() {
            CustomFlatFileItemReader<AccountBalanceFileInput> reader = new CustomFlatFileItemReader<>();
            reader.setRecordSeparatorPolicy(new MergingItemSeparator());
            reader.setLineMapper(sourceAwareLineMapper());
            reader.setFileLocation(processedFilesLocation);
            return reader;
        }

        @Bean(PROCESSOR_NAME)
        @StepScope
        public ValidatingItemProcessor<AccountBalanceFileInput> processor() {
            SpringValidator<AccountBalanceFileInput> springValidator = new SpringValidator<AccountBalanceFileInput>();
            springValidator.setValidator(validator);
            return new ValidatingItemProcessor<AccountBalanceFileInput>(springValidator);
        }

        @Bean(WRITER_NAME)
        @StepScope
        public FlatFileItemWriter<AccountBalanceFileInput> writer() {

            FlatFileItemWriter<AccountBalanceFileInput> writer = new FlatFileItemWriter<AccountBalanceFileInput>();
            writer.setResource(new FileSystemResource(getWriterFileName()));
            writer.setShouldDeleteIfEmpty(true);
            writer.setLineAggregator(new CustomDelimitedLineAggregator<AccountBalanceFileInput>() {
                {
                    setDelimiter("|");
                    setFieldExtractor(new CustomBeanWrapperExtractor<AccountBalanceFileInput>() {
                        {
                            setNames(AccountBalanceJobConstants.WRITER_HEADER);
                        }
                    });
                }
            });
            return writer;
        }

    Config :

        @Configuration
    @EnableAutoConfiguration
    @EnableBatchProcessing(modular = true)
    public class BatchJobsConfig {

        @Bean
        public ResourcelessTransactionManager transactionManager() {
            return new ResourcelessTransactionManager();
        }

        @Bean
        public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager transactionManager)
                throws Exception {
            MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(transactionManager);
            factory.afterPropertiesSet();
            return factory;
        }

        @Bean
        public JobRepository jobRepository(MapJobRepositoryFactoryBean repositoryFactory) throws Exception {
            return repositoryFactory.getObject();
        }

        @Bean
        public JobExplorer jobExplorer(MapJobRepositoryFactoryBean repositoryFactory) {
            return new SimpleJobExplorer(repositoryFactory.getJobInstanceDao(), repositoryFactory.getJobExecutionDao(),
                    repositoryFactory.getStepExecutionDao(), repositoryFactory.getExecutionContextDao());
        }

        @Bean
        public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
            SimpleJobLauncher launcher = new SimpleJobLauncher();
            launcher.setJobRepository(jobRepository);
            return launcher;
        }

    Schedule task looks like this :

        @Slf4j
    @Component
    @EnableScheduling
    public class AccountBalanceJobSchedular {

        @Autowired
        private SimpleJobLauncher jobLauncher;

        @Autowired
        @Qualifier(AccountBalanceFileLoadJob.JOB_ACCOUNT_BAL_LOAD)
        private Job batchJob;

        @Scheduled(cron = "*/6 * * * * *")
        public  void perform() throws Exception {

            JobParameters param = new JobParametersBuilder()
                    .addString("JobID", String.valueOf(System.nanoTime() + UUID.randomUUID().toString())).toJobParameters();

            JobExecution execution = jobLauncher.run(batchJob, param);

            log.info("Job finished with status :" + execution.getStatus());
        }
    }

Each job has its own name and its own class file so each bean name varies according to job name.This works fine if jobs are not running simultaneously. Any help will be much appreciated.
I am using Spring Boot 2, Spring Batch 4 and Java 10.


text:
Q: Generating unique modals for each element in php I have this project where the user selects an item from a list (fetched from a MySQL database), then outputs buttons named from the item
as such:

My (stripped down) code so far:
<!DOCTYPE html>

Select User:

    <form method="POST">

           Subject

<?php
            include('get.php');
               $query=mysqli_query($conn,"select * from `subjects`");
            while($row=mysqli_fetch_array($query)){
         ?>

                <input type="checkbox" value="<?php echo $row['subject']; ?>" name="id[]">
                <?php echo $row['subject']; ?>

            <?php
          }
       ?>

<input type="submit" name="submit" value="Submit">
   </form>

Subjects selected:

    <?php
        if (isset($_POST['submit'])){
            foreach ($_POST['id'] as $id):
                $sq=mysqli_query($conn,"select * from `subjects` where subject='$id'");
                $srow=mysqli_fetch_array($sq);
    ?>
            <button class="button animate" id="myBtn">

                    <?php echo $srow['subject']; ?>

             </button>
            <?php
              endforeach;
              }
            ?>

       ×

Some text in the Modal..

I was able to make a modal for one button but I want to make a unique modal for each button. How can I do this? Thanks.

A: Write a function which will build a modal for you. Have this function accept some input, like the content of the modal which you want to show. Then add the modal to the page. This way you can generate an infinite amount of different modals based on the button that you click on.
I've made an example below which demonstrates how this could work. The example works with building a modal, with the same structure of your example, and use the value attribute of the button the set the content of that modal. For simple text this works fine, but for larges chunks of HTML you might consider getting your content from a hidden element and copy the innerHTML value of that element.

// Flag for checking if a modal is already opened.
// This way we can keep track of the opened modal and
// not open a second one before closing the first.
let modalOpen = false;

function createModal(html = '') {

  // Create the elements.
  const modal = document.createElement('div');
  const content = document.createElement('div');
  const close = document.createElement('span');

  // Add classes to the elements.
  modal.classList.add('modal');
  content.classList.add('modal-content');
  close.classList.add('close', 'js-close-modal');

  // Add content to the elements.
  content.insertAdjacentHTML('beforeend', html);
  close.innerHTML = '×';

  // Append children to parents and to the document.
  content.appendChild(close);
  modal.appendChild(content);
  document.body.appendChild(modal);

  return modal;

}

// Listen for clicks in the document.
document.addEventListener('click', event => {

  // If the create modal button has been clicked, create a modal.
  const button = event.target.closest('.js-create-modal');
  if (button !== null && modalOpen === false) {
    const html = button.value;
    createModal(html);
    modalOpen = true;
  }

  // If the close modal has been clicked, remove the modal.
  const close = event.target.closest('.js-close-modal');
  if (close !== null) {
    const modal = close.closest('.modal');
    modal.remove();
    modalOpen = false;
  }

});
*, *::before, *::after {
  box-sizing: border-box;
}

.modal {
  display: block;
  position: fixed;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 90%;
  max-width: 32em;
  max-height: 48em;
  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25);
  padding: 15px;
  transform: translate(-50%, -50%);
  background: #ffffff;
  border: 1px solid #d0d0d0;
  border-radius: 5px;
  z-index: 99;
}

.modal-content {
  padding: 15px;
}

.close {
  position: absolute;
  top: 15px;
  right: 15px;
  cursor: pointer;
}
<button class="js-create-modal" value="This is my first modal.">Modal 1</button>
<button class="js-create-modal" value="All the modals have their own content.">Modal 2</button>
<button class="js-create-modal" value="And are unique in every way.">Modal 3</button>

Another way would be to have a single modal on the page, which you show and hide. Whenever you click a button, you should modify the content of the modal based on the button that you clicked. That way you only have to modify a single piece. But hey, if a modal is hidden, why not just remove it and build a new one when you need it? Your choice.


text:
Q: Access cell based on sheet name in another cell Suppose I have a bunch of sheets, named uninterestingly Main and then ModelA, ModelB, ... In Main, I just want to aggregate the models on these various sheets.
How can I structure it so that if cell A1 contains the name of a sheet (e.g. ModelA) then cell B1 contains the value of C14 in the cell in the sheet referenced by A1. (Explicitly, this would be ='ModelA'!C14, but I don't want to be explicit).

A: So you will have the Sheet name in column A and want to see whatever sheet that is, but cell C14's value?
=INDIRECT("'"&A1&"'!C14")

A: Actually, I think this is what you want based on your question:
=INDIRECT("'" & A1 & "'!" & B1)


text:
Q: Appcelerator ERROR | socket hang up Tengo el siguiente problema al intentar compilar directamente en un Iphone o Android ( dispositivo fisico )
[INFO] :   Alloy compiled in 68.30137s
[INFO] :   Alloy compiler completed successfully
[ERROR] :  socket hang up
Estoy probando con la ultima version del IDE de appcelerator y titanium 6.3.0
Saludos y muchas gracias.

A: Me auto respondo.
Esto error ocurre por un problema de red.
Cuando appcelerator realiza build, este realiza un request a los servidores de appcelerator( para validar cierta información), el cual , en mi empresa , se encontraba bloqueado. Comprobe lo anterior, probando directamente en otra red en la cual funciono correctamente.
Para saber lo anterior , utilice el siguiente comando "appc run -p ios -T "simulator" -l trace" , el cual me mostro el error de conexion a appcelerator.
Saludos.


text:
Q: angularjs karma test typeerror $route I am trying to test a controller for angularjs using karma, the controller inject a $route to get the current path but when I try to run karma test on it I get.
TypeError: 'undefined' is not an object( evaluating '$route.current')

Here is my controller:
angular.module('myApp').controller('EditController',['$scope', '$http', '$route', function($scope,
$http,$route){

    var myId = $route.current.params.myId;
    $scope.var1 = 'var1';
    console.log(myId);
}]);

Here is my Karma file:
'use strict';
describe('Controller: EditController', function(){
    beforeEach(module('myApp'));
    var EditCtrl,scope,route;

    beforeEach(inject(function($controller,$rootScope,$route,$http){
     scope=$rootScope.$new();
     EditCtrl = $controller('EditCtrl',{
        $scope:scope,
        $route:route
     });
    }));

    it('should have var1 equal to "var1"',function(){
        expect(scope.var1).toEqual('var1');
    });
});

A: Your beforeEach hook isn't injecting the $route service. Change it to this.
beforeEach(inject(function($controller,$rootScope,$route,$http){
 scope=$rootScope.$new();
 route = $route;
 EditCtrl = $controller('EditCtrl',{
    $scope:scope,
    $route:route
 });
}));

You may also want to mock the $route.current object in case it isn't instantiated properly, since there's no routing going on in your test. In which case you could just add
$route.current = { params: { myId: 'test' } };
in the hook as well.


text:
Q: NOT IN with 2 columns I have a query like so, I understand the syntax ain't correct but how would I perform such "action":
SELECT *
FROM accounts C
JOIN proxies P ON C.proxy_id = P.proxy_id
WHERE C.account_id NOT IN
    (SELECT send,
            receive
     FROM action
     WHERE send = C.account_id
       AND receive = ".UID.") LIMIT 1

I'm shown the following error Operand should contain 1 column(s) because of what I'm aware I'm not supposed to do NOT IN with 2 columns, so how would I do a query like so?

A: another solution would be to work with NOT EXISTS
WHERE NOT EXISTS
      (select null
       from action
       where
        (send = c.account_id or receive = c.account_id)
        and receive = '.UID.')
LIMIT 1

FYI, you can have two values in a NOT IN, but they must be on both sides.
where (x, y) not in (select (a, b) from t)


text:
Q: Puppeteer: scraping multiple urls one by one I am trying to scrape multiple URL one by one, then repeat the scrape after one minute.
But I keep getting two errors and was hoping for some help.
I got an error saying:

functions declared within loops referencing an outer scoped variable may lead to confusing semantics

And I get this error when I run the function / code:
TimeoutError: Navigation timeout of 30000 ms exceeded.

My code:
const puppeteer = require("puppeteer");

const urls = [
  'https://www.youtube.com/watch?v=cw9FIeHbdB8',
  'https://www.youtube.com/watch?v=imy1px59abE',
  'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
];

const scrape = async() => {
  let browser, page;

  try {
    browser = await puppeteer.launch({ headless: true });
    page = await browser.newPage();

    for (let i = 0; i < urls.length; i++) {
      const url = urls[i];
      await page.goto(`${url}`);
      await page.waitForNavigation({ waitUntil: 'networkidle2' });

      await page.waitForSelector('.view-count', { visible: true, timeout: 60000 });

      const data = await page.evaluate(() => { // functions declared within loops referencing an outer scoped on this line.
        return [
          JSON.stringify(document.querySelector('#text > a').innerText),
          JSON.stringify(document.querySelector('#container > h1').innerText),
          JSON.stringify(document.querySelector('.view-count').innerText),
          JSON.stringify(document.querySelector('#owner-sub-count').innerText)
        ];
      });

      const [channel, title, views, subs] = [JSON.parse(data[0]), JSON.parse(data[1]), JSON.parse(data[2]), JSON.parse(data[3])];
      console.log({ channel, title, views, subs });
    }
  } catch(err) {
    console.log(err);
  } finally {
    if (browser) {
      await browser.close();
    }
    await setTimeout(scrape, 60000); // repeat after one minute after all urls have been scrape.
  }
};

scrape();

I would really appreciate any help I could get.

A: This works. Putting the for loop in a Promise and waitUntil: "networkidle2" as an option when page.goto() resolves your problem. You don't need to generate a new browser each time, so it should be declared outside of the for loop.
const puppeteer = require("puppeteer");

const urls = [
  "https://www.youtube.com/watch?v=cw9FIeHbdB8",
  "https://www.youtube.com/watch?v=imy1px59abE",
  "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
];

const scrape = async () => {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();

  new Promise(async (resolve, reject) => {
    for (url of urls) {
      // your timeout
      await page.waitForTimeout(6 * 1000);

      await page.goto(`${url}`, {
        waitUntil: "networkidle2",
        timeout: 60 * 1000,
      });

      await page.waitForSelector(".view-count", {
        waitUntil: "networkidle2",
        timeout: 60 * 1000,
      });

      const data = await page.evaluate(() => {
        return [
          JSON.stringify(document.querySelector("#text > a").innerText),
          JSON.stringify(document.querySelector("#container > h1").innerText),
          JSON.stringify(document.querySelector(".view-count").innerText),
          JSON.stringify(document.querySelector("#owner-sub-count").innerText),
        ];
      });

      const [channel, title, views, subs] = [
        JSON.parse(data[0]),
        JSON.parse(data[1]),
        JSON.parse(data[2]),
        JSON.parse(data[3]),
      ];
      console.log({ channel, title, views, subs });
    }
    resolve(true);
  })
    .then(async () => {
      await browser.close();
    })
    .catch((reason) => {
      console.log(reason);
    });
};

scrape();

#Update
As per ggorlen suggestion, the below-refactored code should serve your problem. Comment in the code indicates the purpose of that line
const puppeteer = require("puppeteer");

const urls = [
    "https://www.youtube.com/watch?v=cw9FIeHbdB8",
    "https://www.youtube.com/watch?v=imy1px59abE",
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
];

const scrape = async () => {
    // generate a headless browser instance
    const browser = await puppeteer.launch({ headless: true });

    // used .entries to get the index and value
    for (const [index, url] of urls.entries()) {

        // generating a new page for each of the content
        const page = await browser.newPage();

        // your 60 timeout from 2nd index
        if (index > 0) await page.waitForTimeout(60 * 1000);

        // wait for the page response to available with 60 seconds timeout (error throw)
        await page.goto(`${url}`, {
            waitUntil: "networkidle2",
            timeout: 60 * 1000,
        });

        // wait for .view-count section to be available
        await page.waitForSelector(".view-count");

        // don't need json stringify or parse as puppeteer does so
        await page.evaluate(() =>
        ({
            channel: document.querySelector("#text > a").innerText,
            title: document.querySelector("#container > h1").innerText,
            views: document.querySelector(".view-count").innerText,
            subs: document.querySelector("#owner-sub-count").innerText
        })
        ).then(data => {
            // your scrapped success data
            console.log('response', data);
        }).catch(reason => {
            // your scrapping error reason
            console.log('error', reason);
        }).finally(async () => {
            // close your current page
            await page.close();
        })
    }

    // after looping through finally close the browser
    await browser.close();
};

scrape();

A: I'd suggest a design like this:
const puppeteer = require("puppeteer");

const sleep = ms => new Promise(resolve => setTimeout(resolve), ms);

const scrapeTextSelectors = async (browser, url, textSelectors) => {
  let page;

  try {
    page = await browser.newPage();
    page.setDefaultNavigationTimeout(50 * 1000);
    page.goto(url);
    const dataPromises = textSelectors.map(async ({name, sel}) => {
      await page.waitForSelector(sel);
      return [name, await page.$eval(sel, e => e.innerText)];
    });
    return Object.fromEntries(await Promise.all(dataPromises));
  }
  finally {
    page?.close();
  }
};

const urls = [
  "https://www.youtube.com/watch?v=cw9FIeHbdB8",
  "https://www.youtube.com/watch?v=imy1px59abE",
  "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
];
const textSelectors = [
  {name: "channel", sel: "#text > a"},
  {name: "title", sel: "#container > h1"},
  {name: "views", sel: ".view-count"},
  {name: "subs", sel: "#owner-sub-count"},
];

let browser;
(async () => {
  browser = await puppeteer.launch({headless: true});

  for (;; await sleep(60 * 1000)) {
    const data = await Promise.allSettled(urls.map(url =>
      scrapeTextSelectors(browser, url, textSelectors)
    ));
    console.log(data);
  }
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;

A few remarks:

*

*This runs in parallel on the 3 URLs using Promise.allSettled. If you have more URLs, you'll want a task queue or run synchronously over the URLs with a for .. of loop so you don't outstrip the system's resources. See this answer for elaboration.

*I use waitForSelector on each and every selector rather than just '.view-count' so you won't miss anything.

*page.setDefaultNavigationTimeout(50 * 1000); gives you an adjustable 50-second delay on all operations.

*Moving the loops to sleep and step over the URLs into the caller gives cleaner, more flexible code. Generally, if a function can operate on a single element rather than a collection, it should.

*Error handling is improved; Promise.allSettled lets the caller control what to do if any requests fail. You might want to filter and/or map the data response to remove the statuses: data.map(({value}) => value).

*Generally, return instead of console.log data to keep functions flexible. The caller can console.log in the format they desire, if they desire.

*There's no need to do anything special in page.goto(url) because we're awaiting selectors on the very next line. "networkidle2" just slows things down, waiting for network requests that might not impact the selectors we're interested in.

*JSON.stringify/JSON.parse is already called by Puppeteer on the return value of evaluate so you can skip it in most cases.

*Generally, don't do anything but cleanup in finally blocks. await setTimeout(scrape, 60000) is misplaced.


text:
Q: My sample doesn't start in android virtual device I'm newbie at android programming. I've just a form and there is only a textbox and button. When i run it i gives me an error that you can see in the screenshot.

My manifest.xml is below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.deitel.welcome"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity android:name="welcome" android:label="@string/app_name"
            android:theme="@android:style/Theme.Black.NoTitleBar"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Log
[2013-06-17 14:40:38 - Welcome] ------------------------------
[2013-06-17 14:40:38 - Welcome] Android Launch!
[2013-06-17 14:40:38 - Welcome] adb is running normally.
[2013-06-17 14:40:38 - Welcome] Performing com.deitel.welcome.welcome activity launch
[2013-06-17 14:40:38 - Welcome] Automatic Target Mode: launching new emulator with compatible AVD 'emulator1'
[2013-06-17 14:40:38 - Welcome] Launching a new emulator with Virtual Device 'emulator1'
[2013-06-17 14:40:38 - Emulator] Failed to create Context 0x3005
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] emulator: WARNING: Could not initialize OpenglES emulation, using software renderer.
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:38 - Emulator] could not get wglGetExtensionsStringARB
[2013-06-17 14:40:39 - Welcome] New emulator found: emulator-5554
[2013-06-17 14:40:39 - Welcome] Waiting for HOME ('android.process.acore') to be launched...
[2013-06-17 14:41:25 - Welcome] HOME is up on device 'emulator-5554'
[2013-06-17 14:41:25 - Welcome] Uploading Welcome.apk onto device 'emulator-5554'
[2013-06-17 14:41:25 - Welcome] Installing Welcome.apk...
[2013-06-17 14:42:24 - Welcome] Success!
[2013-06-17 14:42:24 - Welcome] Starting activity com.deitel.welcome.welcome on device emulator-5554
[2013-06-17 14:42:26 - Welcome] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.deitel.welcome/.welcome }

A: This shows that your application is crashing due to some reason.
Debug your Main Activity in your case it is Welcome.java. Place debug point in your onCreate and other callback methods, i.e onResume(), onPuase(), Also provide complete stack-trace, what trace you have provided is useless. Please also privide code of your Welcome Activity.


text:
Q: Move groupby selected columns into a new pandas column as dictionary I have the following pandas DataFrame in python:
df = pd.DataFrame({'id': [1, 1, 2, 2, 3],
                   'field1': [1, 2, 3, 4, 5],
                   'field2': ['a', 'b', 'c', 'd', 'e']})

    id  field1  field2
0   1   1       a
1   1   2       b
2   2   3       c
3   2   4       d
4   3   5       e

I want to group the above table by id then move all selected column values in that group into a new column as a list of python dictionaries.
So from the above I would like to produce this one:
    id  fields
0   1   [{'field1': 1, 'field2': 'a'}, {'field1': 2, 'field2': 'b'}]
2   2   [{'field1': 3, 'field2': 'c'}, {'field1': 4, 'field2': 'd'}]
4   3   [{'field1': 5, 'field2': 'e'}]

I could achieve this with the following python code:
def test(df):
    df['fields'] = [df[['field1', 'field2']].to_dict(orient='records')]*len(df)
    return df

df.groupby('id').apply(test).drop_duplicates('id')[['id', 'fields']]

But I'm sure it can be done better. The question is how?
I'm especially dissatisfied with this part:
df['fields'] = [df[['field1', 'field2']].to_dict(orient='records')]*len(df)

where I have to make a list with the length of the groups just to assign the same dictionary value to the rows.
Also, this makes it more memory hungry.

A: Maybe
df.set_index('id').groupby(level=0).apply(pd.DataFrame.to_dict, orient='r')

id
1    [{'field1': 1, 'field2': 'a'}, {'field1': 2, 'field2': 'b'}]
2    [{'field1': 3, 'field2': 'c'}, {'field1': 4, 'field2': 'd'}]
3    [{'field1': 5, 'field2': 'e'}]
dtype: object

Can always add .to_frame('fields') at the end to get a df back.

A: Also you can use:
df.groupby('id')['field1','field2'].apply(lambda x: x.to_dict('r')).rename('fields').reset_index()

   id                                             fields
0   1  [{'field1': 1, 'field2': 'a'}, {'field1': 2, '...
1   2  [{'field1': 3, 'field2': 'c'}, {'field1': 4, '...
2   3                     [{'field1': 5, 'field2': 'e'}]


text:
Q: Phone number to allow only numbers, +, and spaces I want to restrict a phone number field to only 'numbers', '+' and 'spaces', or restrict 'A-Z'. I am using jQuery Validate and I have tried:
jQuery.validator.addMethod("numero", function(value, element) {
    return this.optional(element) || value == value.match(/^[+1-9 ]*$/);
});

However the regex for my numero rule doesn't seem to be working correctly.
My code:
jQuery(document).ready(function(){

    jQuery.validator.addMethod("alpha", function(value, element) {
        return this.optional(element) || value == value.match(/^[a-zA-Z ]*$/);
    });

    jQuery.validator.addMethod("numero", function(value, element) {
        return this.optional(element) || value == value.match(/^[+1-9 ]*$/);
    });

    jQuery('.upsale-form').each(function() {
        jQuery(this).validate({
            rules: {
                'Contact.name': {
                    minlength: 3,
                    required: true,
                    alpha: true
                },
                'Contact.email': {
                    required: true,
                    email: true
                },
                'Contact.phone': {
                    minlength: 9,
                    required: true,
                    numero: true
                }
            }
        });

    });
});

A:
I want to restrict a phone number field to only 'numbers', '+' and 'spaces'

Your regex, /^[+1-9 ]*$/, was only matching 1 through 9 and leaving out any zeros.  You could use \d to represent any digit instead.
So /^[\d+ ]*$/ will work.
See:  http://jsfiddle.net/pqjfxbyt/1/
Reference:  regexr.com

A: Maybe you want "0-9" and not "1-9"?
return this.optional(element) || value == value.match(/^[+0-9 ]*$/);

A: Try this Regx this will help you out ([0-9+-])\w+


text:
Q: How to draw a rectangle without a border in Swift (MacOS) My current code is pretty basic because I'm still new to Swift. However, I can't figure out how to just draw a rectangle on screen without the border(close, minimize, enlarge buttons) like in the picture linked.
(Also please tell me what that border is actually called!)
https://i.imgur.com/FJGaXKv.png
import SwiftUI

struct ContentView: View {
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 200, height: 200)
    }
}

Anyways, I'm used to coding in Lua for Garry's Mod, where I am able to draw the rectangle on-screen anywhere I want by defining the coordinates and size of the rectangle, so I'm just wondering is it possible to do the same on Swift, or perhaps another language would be more beneficial?
Thanks in advance!

A: Title with buttons is part of window, not drawing rectangle, so you have just create another type of window (without title & buttons), so you your AppDelegate
func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()
        .edgesIgnoringSafeArea(.top) // to extend entire content under titlebar

    // Create the window and set the content view.
    window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
        styleMask: [.titled, .texturedBackground, .fullSizeContentView],
        backing: .buffered, defer: false)
    window.center()
    window.setFrameAutosaveName("Main Window")

    window.titlebarAppearsTransparent = true // as stated
    window.titleVisibility = .hidden         // no title - all in content

    window.contentView = NSHostingView(rootView: contentView)
    window.makeKeyAndOrderFront(nil)
}


text:
Q: An inner product space has a vector related to an arbitrary collection of scalars Let $V$ be a finite dimensional inner product space with inner product $\left\langle , \right\rangle$ and let $\beta = \{v_1,...,v_n\}$ be a basis for $V$. If $c_1,...,c_n$ are arbitrary scalars, show $\exists ! \alpha \in V$ with $\left\langle \alpha , v_i \right\rangle = c_i$ $\forall i \in \{1,...,n\}$.
Here's what I've thought so far. It would be easy if $\beta$ were given as an orthogonal basis, as then $\left\langle \sum_{i=1}^n c_iv_i , v_j\right\rangle = c_i \delta_{ij}$ so $\alpha = \sum_{i=1}^n c_iv_i$ is what we require.
I know we can use the Gram-Schmidt process to acquire an orthonormal basis $\{ w_1,...,w_n\}$ from $\{v_1,...,v_n\}$ but if $\alpha = \sum_{i=1}^n c_iw_i$, there's no guarantee (that I can see) that $\left\langle w_i,v_j\right\rangle = \delta_{ij}$ to get what we require.
I was also thinking we could use the matrix $M$ for $\left\langle , \right\rangle$ to get the following system of $n$ equations; $xMv_i = c_i$ in $x$, but I don't know that this would have to have a solution.
Any ideas? Thanks!

A: Hint: Show that $L : V \to \mathbb{R}^n$ defined by
$$L(v) = \begin{bmatrix} \langle v, v_1\rangle\\ \vdots\\ \langle v, v_n\rangle\end{bmatrix}$$
is an isomorphism.


text:
Q: Excluding methods from inheritance (without: private) I have a front controller that is instantiated as follows:
$request = new FrontController();
$request->route();

The route() method then dynamically calls the appropriate controller as needed based on the request.
Now (I think) I want all of my controllers to extend the FrontController so that they can all have access to a shared set of methods and properties, but I don't want them to inherit the route() method as that could potentially lead to an infinite loop. If the route() method is marked as private, however, then I can't instantiate the object as demonstrated above.
The only solution I've found is to call self::route() from the FrontController's constructor, and then to define a blank constructor in each child controller. That just feels sloppy.
Is there a way to exclude certain methods from inheritance without marking them as private? Or should I be looking at the problem from another angle?

A: You can prepend the final modifier to a method to prevent it from being overridden by subclassing.
class FrontController{
   final public function route() {
       // ...
   }
}

See the following PHP manual entry for more examples and a detailed explanation:
http://php.net/manual/en/language.oop5.final.php

A:
Or should I be looking at the problem from another angle?

Most probably, yes. First you should think about what exactly you are trying to solve because I don't even see a real problem there. From what you've written there is no risk of an infinit loop.

A: Are you asking whether you can selectively "turn off" inherited items? The answer to this is "no" I'm afraid, and this is basically by definition.
Two alternatives:
in a child class, where you don't want to implement such-and-such a method (/property), you can override it and return some kind of "not implemented" result.
create a series of base classes in a hierarchy, if you can, each building on the last. Then your child classes can inherit from one of the base classes, but you don't necessarily have all children inheriting from the same base class.
imo both of these approaches are pretty ugly. When I was young(er) I used to agrue about which of these was preferable, but I've long since given up doing so because its basically a six and two threes. I think if anything it depends on what the norms are in the actual environment you're writing for.
But presumably if you sit and think about it you can see why inheritance gets implemented this way.


text:
Q: What are the prerequisites for considering any other planet to be habitable? Well, there is a measure of how a planet could be considered like Earth, called Planetary habitability. Based on this measure, what are the prerequisites needed to consider a planet to be a habitable one?

A: We have essentially one criteria for looking for planets that contain life: liquid water. This requirement covers planets that:

*

*have water

*have an average temperature which allows that water to be in liquid form

But that's just because the one trait shared by all life on Earth is that they need water to survive. We don't know what other kinds of life are possible, because we haven't found any on other planets.
But consider that all life on Earth requires water because that is pretty much the one condition that has remained constant through Earth's history (since the beginning of life). Conditions which changed caused extinctions and adaptations (such as the oxygen catastrophe) until we get to the present earth with most of its life drinking water and breathing oxygen. So if the earth could go from being oxygen-free to containing an abundance of oxygen which nearly all life requires to survive (a big change), maybe the water could have also been substituted for something else? After all, life didn't come from water, it evolved to use water as its solvent of choice because there was an abundance of it.
So maybe life is possible without water if it grew up in an environment without it. But how did life get started on Earth? Can we look for that on other planets? Actually, nobody knows. There are some processes we think probably contributed to the process (see the Miller-Urey experiment) which involve the presence of a few elements and some weather conditions. But we don't know the full process (we couldn't make abiogenesis happen in a lab, for example) and even if we did, it's unlikely we could look for that on another planet. We can't even really see other planets, aside from indirect data and small points of light. We don't know what conditions are necessary for abiogenesis, or how to look for it -- even if we find a planet which is nearly identical to Earth, there's no guarantee that abiogenesis happened there.
As far as we know, any planet could contain some kind of life. But to maximize our chances, we're only getting excited about earth-like planets since we already know the kinds of life which can exist there.

A: Habitable by whom?  There are conditions that are uninhabitable by humans, however, many "extremophiles" survive perfectly happy.
Although, if you are talking about humans, here is a small list (all the rest are probably more "nice to have" requisites):

*

*Approximately 20% oxygen (more or less depending on the pressure)

*Temperatures that allow for liquid water

*Adequate access to water (and food)

*Adequate protection from radiation.

*Then a whole host of conditions that wouldn't end human life.  Such as deadly pathogens on chemicals in the atmosphere.

All this said, since we only have a sample size of one currently for planetary life, we really don't know what is possible, or how to bound the problem.  ANYTHING is just speculation drawn from this one sample.  That said, we have found life on our own planet where we never suspected it to be.  Life has proven to be nearly unstoppable in propagating throughout every niche on this planet.  So, the better question I think would be what are the requisites for abiogenesis?  I think once life manages to start on any planet, it will adapt to whatever conditions the planet presents (to within a reasonable degree).


text:
Q: Reverse proxy + IIS + Docker I have two services running in a swarm (I'll call them A and B) with replica as 1 which means one container for each service.
Service A has a web application (UI) that calls another web app (api) in service B.
Service A is exposed on 8082 and Service B on 8081.
However I will have to implement some kind off reverse proxy to make this work due to the difference in ports and CORS won't allow A to call B(even though they are available on same url as they are part of the swarm).
My idea was to have a dummy web api in A along with the existing UI application and add urlReWrite rule to the dummy api so that the request from UI app to dummy web app in Service A will be redirected to the actual one in service B.
For whatever reason this doesn't work. I just get 404 error. Can someone help me with this?
I'm also posting the dockerfile contents below for Service A which has urlRewrite written into it.

# escape=`

FROM microsoft/aspnet
SHELL ["powershell", "-command"]

# Install urlRewrite
RUN Invoke-WebRequest http://download.microsoft.com/download/E/9/8/E9849D6A-020E-47E4-9FD0-A023E99B54EB/requestRouter_amd64.msi -UseBasicParsing -OutFile C:/requestrouter.msi; `
  Start-Process msiexec -ArgumentList '/i C:\requestrouter.msi /qn' -Wait; rm C:\requestrouter.msi

# Install ARR
RUN Invoke-WebRequest http://download.microsoft.com/download/C/9/E/C9E8180D-4E51-40A6-A9BF-776990D8BCA9/rewrite_amd64.msi -UseBasicParsing -OutFile C:/rewrite.msi; `
  Start-Process msiexec -ArgumentList '/i C:\rewrite.msi /qn' -Wait; rm C:\rewrite.msi

# Enable ARR proxy
RUN Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Name 'enabled' -Filter 'system.webServer/proxy' -Value 'True'

# Configure website
EXPOSE 8082
RUN Set-WebBinding -Name 'Default Web Site' `
    -BindingInformation '*:80:' `
    -PropertyName Port -Value 8082; `
    md C:\inetpub\wwwroot\Application; `
 md C:\inetpub\wwwroot\webapi; `
    md c:\transformedsettings; `
 New-WebApplication -Name 'UIApplication' `
    -Site 'Default Web Site' `
    -PhysicalPath 'C:\inetpub\wwwroot\Application' `
    -ApplicationPool '.NET v4.5'; `
 New-WebApplication -Name 'webapi' `
    -Site 'Default Web Site' `
    -PhysicalPath 'C:\inetpub\wwwroot\webapi' `
    -ApplicationPool '.NET v4.5';

RUN Add-WebConfigurationProperty -PSPath 'IIS:\Sites\Default Web Site\webapi' -filter "system.webServer/rewrite/rules" -name '.' -value @{name='umrp'; patterSyntax='Regular Expressions'; stopProcessing='False'}; `
 Set-WebConfigurationProperty -PSPath 'IIS:\Sites\Default Web Site\webapi' -filter "system.webServer/rewrite/rules/rule[@name='umrp']/match" -name 'url' -value '(.*)'; `
 Set-WebConfigurationProperty -PSPath 'IIS:\Sites\Default Web Site\webapi' -filter "system.webServer/rewrite/rules/rule[@name='umrp']/action" -name 'type' -value 'Rewrite'; `
 Set-WebConfigurationProperty -PSPath 'IIS:\Sites\Default Web Site\webapi' -filter "system.webServer/rewrite/rules/rule[@name='umrp']/action" -name 'url' -value 'http://(manager nodes ip):8081/{R:1}'

# The final instruction copies the site you published earlier into the container.
COPY ./Xpo.LastMile.Portal/bin/Release/PublishOutput C:/inetpub/wwwroot/Application
COPY ./InitializeContainer.ps1 c:/
COPY ./transformedsettings c:/transformedsettings
COPY ./Xpo.LastMile.Portal/angular2 C:/inetpub/wwwroot/Application/angular2
COPY ./Xpo.LastMile.Portal/node_modules C:/inetpub/wwwroot/Application/node_modules
COPY ./Default.html C:/inetpub/wwwroot/webapi

ENTRYPOINT powershell c:\InitializeContainer


text:
Q: Receiving Mockito UnfinishedStubbingException for doNothing.when clause in Android Unit Test Firstly, my setup is RXJava 1, Retrofit 2 and I'm using Java 7.
I have a method that, when it is called, will set an atomic boolean to true.
That method then calls a retrofit API.
Upon completion, timeout etc... the atomic boolean is reset to false.
So, I would therefore like to uni test that when I call my method, the Atomic Boolean is set to true.
So, I do the following:
    assertFalse(orderUseCase.isOrderInProcess());

    orderUseCase.execute(id, orderWrapper, ts);

    assertTrue(orderUseCase.isOrderInProcess());

Test that the boolean is false.
Execute my use case
Test that the boolean is true.
Now, in order to perform the last test I need to ensure the API does nothing when it is called (the execute method will call the retrofit API.
To try and doNothing I am using the following line at the start of my test case.
doNothing().when(orderAPI.orderComplete(anyString(), any(OrderWrapper.class)));

I am however receiving the following error:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.tfds.xms.unit_test.SingleTest.TestAtomicBooleanLocked(SingleTest.java:90)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

From reading where other people had a similar issue, the answers were suggesting that their 'when' line was calling another Mock (which I don't believe I am doing) or that they hadn't done the 'PrepareForTest' step which I have done. I am however wondering if what is in my prepareForTest section is correct or not...
Incidentally I understand that the error is pointing me to add a 'thenReturn' but that would mean that the API 'does' something and would consequently cause the Atomic Boolean to unlock again, which is not what I want..
Any help is very much appreciated.
My full test case is:
@RunWith(TestRunner.class)
@PrepareForTest({OrderApiService.class, OrderUseCase.class})
public class SingleTest {

    @Rule
    public RxJavaResetRule pluginsReset = new RxJavaResetRule();

    private OrderApiService orderAPI;
    private OrderUseCase orderUseCase;
    private OrderRepository orderRepository;

    @Mock App app;

    @Before
    public void setUp() {

        orderAPI = mock(OrderApiService.class);

        orderRepository = new OrderRepository(app, orderAPI);

        orderUseCase = new OrderUseCase(orderRepository);

    }

    @Test
    public void TestAtomicBooleanLocked() throws Exception {

        doNothing().when(orderAPI.orderComplete(anyString(), any(OrderWrapper.class)));

        String id = "5";

        Order order = new Order();

        OrderWrapper orderWrapper = new orderWrapper(order);

        TestSubscriber<GenericResponse> ts = new TestSubscriber<GenericResponse>();

        assertFalse(orderUseCase.isOrderInProcess());

        orderUseCase.execute(id, orderWrapper, ts);

        assertTrue(orderUseCase.isOrderInProcess());

    }
}

A: The doNothing() method from Mockito works a bit different then the standalone when() method. You should be fine by just pushing the method call out of the .doNothing() like this:
doNothing().when(orderAPI)
    .orderComplete(anyString(), any(OrderWrapper.class));

Happy testing!


text:
Q: Proving equilateral triangle Show that the lines $x^2+16xy-11y^2=0$ form an equilateral triangle with the line $2x+y+1=0$ and find its area.
--------________________________---------
My solution is here;
Here $x^2+16xy-11y^2=0$ represents a pair of straight lines.
Comparing with $ax^2+bx+c=0$ and using the quadratic formula i.e. $x={-b+/-√(b^2-4ac)}/2a$ I got $x=-8y+/-5y√3$.
Now, how do i move ahead

A: The pair of lines intersect at the origin, so let each line be $y=mx$. Substitute for $y$:
$$x^2+16mx^2-11m^2x^2=0$$
This gives the quadratic equation, satisfied by both gradients:
$$11m^2-16m-1=0\Rightarrow m=\frac{8\pm5\sqrt{3}}{11}$$
Now consider the line through the origin which is perpendicular to the third side $2x+y+1=0$ which is $$2y=x$$
We can rotate this line by $\pm 30^o$ by using the rotation matrix $$Rot(\alpha)=\left(\begin{matrix}\cos \alpha &-\sin \alpha \\ \sin\alpha& \cos\alpha\end{matrix}\right)$$
This leads to two lines, passing through the origin, whose gradients are exactly as before, $\frac{8\pm5\sqrt{3}}{11}$.
This confirms that the triangle formed by these lines is equilateral.
To calculate the area, you just need the height of the triangle, which is the perpendicular distance from the origin to the line $2x+y+1$, namely $$\frac{1}{\sqrt{5}}$$ then the area of the triangle is $$\frac 15 \tan 30$$.
I hope this helps.


text:
Q: google says my site is not mobile-friendly and it is I have created a site, complete with responsive layout which works well.
Apparently google thinks the site isn't mobile friendly, and has listed a whole pile of resoures that I notice are included in this text in the robots.txt file
Disallow: /administrator/
Disallow: /bin/
Disallow: /cache/
Disallow: /cli/
Disallow: /components/
Disallow: /includes/
Disallow: /installation/
Disallow: /language/
Disallow: /layouts/
Disallow: /libraries/
Disallow: /logs/
Disallow: /media/
Disallow: /modules/
Disallow: /plugins/
Disallow: /templates/
Disallow: /tmp/

It looks like I need to allow access to some of these files/folders including media, templates and plugins
I am concerned that google will then be putting up administrator type pages within its search results
What should I do?
Is it ok to do this - and which ones should I allow?
Thanks

A: After some more rooting around I just made image, media and templates viewable to robots. Now my site is friends with google.


text:
Q: CodeIgniter email error I use codeigniter to send email
but i have this error
Fatal error: Call to a member function load() on a non-object in /home/brokarsi/public_html/test/system/libraries/Email.php on line 1922

what is this error?

A: In my version of CodeIgniter (1.7.2) this corresponds to the following line :
$CI->lang->load('email');

I would guess the problem is that the Language library is not loaded but is required by the Email library.  Could you try auto-loading the Language library?
system/application/config/autoload.php
$autoload['libraries'] = array(...., 'language');


text:
Q: Filter list by date value I have a Date attribut(date1) in the entity(object), and i want to show a list<object> who is filtring by date when ( date1 < next 15 days )   like :
 (today+15days> date1>today).
Im using Jpa repository,springData on springBoot and primefaces 6,2
 Thank you

A: If you are using Date, use LocalDateTime instead,
Now, your repository should look like this,
interface YourEntityRepository extends JpaRepository<YourEntity, String> {

    List<YourEntity> findByDateBetween(LocalDateTime from, LocalDateTime to);

}

Now you can filter,
List<YourEntity> entities = repository.findByDateBetween(date1, date1.plusDays(15));

Using LocalDateTime you can PLUS date with different date and time fields.


text:
Q: Timer for sending request at some time period I have specific trouble: I'm using Yandex.Disk cloud storage and working with this by Yandex.Disk REST API. I have some functionality for syncing data and saving to db. Specially it's file name, file md5, file download url. But trouble is that download url is temporary. And I'm looking for solution, to have ability for apdating download url for all saved in db files, each 24 hours. First solution I found is another project that will be launching by windows task scheduler, but my hosting provider not giving this ability. Help me please to find good solution for this.

A: You can probably use hangfire http://hangfire.io/ to create a recurring task within your ASP.NET application.


text:
Q: Deliver JMS message to a single node in a Weblogic Cluster with a Distributed Topic I would like to have my Weblogic cluster listen on a distributed topic.  Whenever a JMS message is sent on that topic, I would like for only one node in the cluster to handle this message.  Is this possible?
I can't use a distributed queue because there are multiple listeners (other clusters) on the topic.

A: With WebLogic 10.3.4 this is possible with Partitioned TOpics.  In order to enable this you should set the replication mode to 'Partitioned'.  The default is 'Replicated' which delivers the message to every node in the cluster.


text:
Q: How to run this Chmod.java? Here is the link to the example:
https://docs.oracle.com/javase/tutorial/essential/io/examples/Chmod.java
The code in this example is as follows:
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.attribute.PosixFilePermission.*;
import static java.nio.file.FileVisitResult.*;
import java.io.IOException;
import java.util.*;

public class Chmod {

    public static Changer compile(String exprs) {
        // minimum is who and operator (u= for example)
        if (exprs.length() < 2)
            throw new IllegalArgumentException("Invalid mode");

        // permissions that the changer will add or remove
        final Set<PosixFilePermission> toAdd = new HashSet<PosixFilePermission>();
        final Set<PosixFilePermission> toRemove = new HashSet<PosixFilePermission>();

        // iterate over each of expression modes
        for (String expr: exprs.split(",")) {
            // minimum of who and operator
            if (expr.length() < 2)
                throw new IllegalArgumentException("Invalid mode");

            int pos = 0;

            // who
            boolean u = false;
            boolean g = false;
            boolean o = false;
            boolean done = false;
            for (;;) {
                switch (expr.charAt(pos)) {
                    case 'u' : u = true; break;
                    case 'g' : g = true; break;
                    case 'o' : o = true; break;
                    case 'a' : u = true; g = true; o = true; break;
                    default : done = true;
                }
                if (done)
                    break;
                pos++;
            }
            if (!u && !g && !o)
                throw new IllegalArgumentException("Invalid mode");

            // get operator and permissions
            char op = expr.charAt(pos++);
            String mask = (expr.length() == pos) ? "" : expr.substring(pos);

            // operator
            boolean add = (op == '+');
            boolean remove = (op == '-');
            boolean assign = (op == '=');
            if (!add && !remove && !assign)
                throw new IllegalArgumentException("Invalid mode");

            // who= means remove all
            if (assign && mask.length() == 0) {
                assign = false;
                remove = true;
                mask = "rwx";
            }

            // permissions
            boolean r = false;
            boolean w = false;
            boolean x = false;
            for (int i=0; i<mask.length(); i++) {
                switch (mask.charAt(i)) {
                    case 'r' : r = true; break;
                    case 'w' : w = true; break;
                    case 'x' : x = true; break;
                    default:
                        throw new IllegalArgumentException("Invalid mode");
                }
            }

            // update permissions set
            if (add) {
                if (u) {
                    if (r) toAdd.add(OWNER_READ);
                    if (w) toAdd.add(OWNER_WRITE);
                    if (x) toAdd.add(OWNER_EXECUTE);
                }
                if (g) {
                    if (r) toAdd.add(GROUP_READ);
                    if (w) toAdd.add(GROUP_WRITE);
                    if (x) toAdd.add(GROUP_EXECUTE);
                }
                if (o) {
                    if (r) toAdd.add(OTHERS_READ);
                    if (w) toAdd.add(OTHERS_WRITE);
                    if (x) toAdd.add(OTHERS_EXECUTE);
                }
            }
            if (remove) {
                if (u) {
                    if (r) toRemove.add(OWNER_READ);
                    if (w) toRemove.add(OWNER_WRITE);
                    if (x) toRemove.add(OWNER_EXECUTE);
                }
                if (g) {
                    if (r) toRemove.add(GROUP_READ);
                    if (w) toRemove.add(GROUP_WRITE);
                    if (x) toRemove.add(GROUP_EXECUTE);
                }
                if (o) {
                    if (r) toRemove.add(OTHERS_READ);
                    if (w) toRemove.add(OTHERS_WRITE);
                    if (x) toRemove.add(OTHERS_EXECUTE);
                }
            }
            if (assign) {
                if (u) {
                    if (r) toAdd.add(OWNER_READ);
                      else toRemove.add(OWNER_READ);
                    if (w) toAdd.add(OWNER_WRITE);
                      else toRemove.add(OWNER_WRITE);
                    if (x) toAdd.add(OWNER_EXECUTE);
                      else toRemove.add(OWNER_EXECUTE);
                }
                if (g) {
                    if (r) toAdd.add(GROUP_READ);
                      else toRemove.add(GROUP_READ);
                    if (w) toAdd.add(GROUP_WRITE);
                      else toRemove.add(GROUP_WRITE);
                    if (x) toAdd.add(GROUP_EXECUTE);
                      else toRemove.add(GROUP_EXECUTE);
                }
                if (o) {
                    if (r) toAdd.add(OTHERS_READ);
                      else toRemove.add(OTHERS_READ);
                    if (w) toAdd.add(OTHERS_WRITE);
                      else toRemove.add(OTHERS_WRITE);
                    if (x) toAdd.add(OTHERS_EXECUTE);
                      else toRemove.add(OTHERS_EXECUTE);
                }
            }
        }

        // return changer
        return new Changer() {
            @Override
            public Set<PosixFilePermission> change(Set<PosixFilePermission> perms) {
                perms.addAll(toAdd);
                perms.removeAll(toRemove);
                return perms;
            }
        };
    }

    /**
     * A task that <i>changes</i> a set of {@link PosixFilePermission} elements.
     */
    public interface Changer {
        /**
         * Applies the changes to the given set of permissions.
         *
         * @param   perms
         *          The set of permissions to change
         *
         * @return  The {@code perms} parameter
         */
        Set<PosixFilePermission> change(Set<PosixFilePermission> perms);
    }

    /**
     * Changes the permissions of the file using the given Changer.
     */
    static void chmod(Path file, Changer changer) {
        try {
            Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
            Files.setPosixFilePermissions(file, changer.change(perms));
        } catch (IOException x) {
            System.err.println(x);
        }
    }

    /**
     * Changes the permission of each file and directory visited
     */
    static class TreeVisitor implements FileVisitor<Path> {
        private final Changer changer;

        TreeVisitor(Changer changer) {
            this.changer = changer;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            chmod(dir, changer);
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            chmod(file, changer);
            return CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
            if (exc != null)
                System.err.println("WARNING: " + exc);
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println("WARNING: " + exc);
            return CONTINUE;
        }
    }

    static void usage() {
        System.err.println("java Chmod [-R] symbolic-mode-list file...");
        System.exit(-1);
    }

    public static void main(String[] args) throws IOException {
        if (args.length < 2)
            usage();
        int argi = 0;
        int maxDepth = 0;
        if (args[argi].equals("-R")) {
            if (args.length < 3)
                usage();
            argi++;
            maxDepth = Integer.MAX_VALUE;
        }

        // compile the symbolic mode expressions
        Changer changer = compile(args[argi++]);
        TreeVisitor visitor = new TreeVisitor(changer);

        Set<FileVisitOption> opts = Collections.emptySet();
        while (argi < args.length) {
            Path file = Paths.get(args[argi]);
            Files.walkFileTree(file, opts, maxDepth, visitor);
            argi++;
        }
    }
}

Firstly I am using the Netbeans IDE. I have very little knowledge of how chmod works because i am not a linux user.
How should this chmod.java work? Basically you don't need to explain everything as I will learn it by myself if the code already works.
Here is the arguments i have tried on netbeans
-R u+w,o-rwx C:\Users\Josh\Desktop\chin.txt

But it gives an error
Exception in thread "main" java.lang.UnsupportedOperationException
    at      sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:192)
at java.nio.file.Files.readAttributes(Files.java:1737)
at java.nio.file.Files.getPosixFilePermissions(Files.java:2004)
at chmod.Chmod.chmod(Chmod.java:269)
at chmod.Chmod$TreeVisitor.visitFile(Chmod.java:294)
at chmod.Chmod$TreeVisitor.visitFile(Chmod.java:279)
at java.nio.file.Files.walkFileTree(Files.java:2670)
at chmod.Chmod.main(Chmod.java:336)

Java Result: 1

A: You use a Windows filesystem and chmod expects a filesystem which supports POSIX; which Windows, well, doesn't.
As a proof, try and do that:
final FileSystem fs = FileSystems.getDefault(); // <-- that's your filesystem
System.out.println(fs.supportedFileAttributeViews());

You won't see posix displayed.
If you want to play with it, try and use memoryfilesystem which does have a way to build a FileSystem with Unix-like capabilities:
final FileSystem fs = MemoryFileSystemBuilder.newLinux()
    .build("testfs");

// fs.getPath() etc

Also have a look at this project, with which you can do that:
MoreFiles.setMode(somePath, 0644); // for instance


text:
Q: Removing touch event listeners from single objects removes touch functionality from all other objects on the screen I want to remove touch listeners from a single object and want to remove listeners from gameloop but the problem is, if i remove touch listeners from ball object, touch event listeners also gets removed from the other objects which includes button also, which i want to press to continue on the next screen, below are the blue print of the codes but it is not exact code what i am using. Please try to solve the problem .. thanks
function displayScreen()
    local btnGroup = display.newGroup()
    local graphic = display.newRect( 0, 0, display.contentWidth, display.contentHeight)
    graphic:setFillColor(0, 0, 0, 50)
    btnGroup:insert(graphic)
    ball:removeEventListener("touch", moveball)
    restartMenu()
end

 function restartMenu()
    local menuGp = display.newGroup()
    graphic1 = display.newImageRect("Reset.png", 564, 216,true )
    graphic1.x = display.contentWidth / 2
    graphic1.y = display.contentHeight - display.contentHeight / 4
    graphic1:addEventListener("touch", restart)
    menuGp:insert(graphic1)
end

function restart()
{}

A: Currently you are using Runtime for your touch events. So it's natural that all other objects touch listeners are removed. If you want to manupulate event listeners individually you should create event listeners just for one object. What I mean is something like that:
local ball = display.newCircle( 250, 250, 60 )
ball.x = display.contentCenterX
ball.y = display.contentCenterY
ball:setFillColor(240, 200, 0)
ball:addEventListener( "touch", ballTouchHandler )

And for removing;
ball:removeEventListener( "touch", ballTouchHanler )

I dont suggest to use Runtime:addEventListener( "touch", functiıon() {} ) at all.
You should use it only with "enterFrame" functions


text:
Q: Protractor: get element on the basis of innerhtml I do e2e-tests with Protractor.
There I need to get an element on the basis of the innerhtml content. But I don't know how to do this.
In the html code it looks like that:

     <input type="radio" name="group" ng-checked="false" ng-click="updateLocale(locale)">

        English (USA)

Now I need the element "input" on the basis of the innerhtml of "English (USA).
What I have tested is that here:
var languageOption = element(by.className('input div item-content ng-binding').getText()).toBe('English (USA)');

I always get the error "has no method 'getText'"
What I do wrong?

A: It's very hard, so you have to create unique ids for every input element (or another elements) in ng-repeat.
I did this so:
<input id="locale{{$index}}"...>

You can define the first one as you want. With the solution from above I get this:
locale0
locale1
locale2
... and so on
Then you can get the element like this:
element(by.id('locale0'));

A: I would recommend you to use map and then filter. Use map to return then text of the div and the input, then filter the result of the map based on the div text.
it('should ...', function() {
  var localeToLookFor = 'English (USA)';

  // Use map to return the text and the input.
  $$('.item.item-radio').map(function(row) {
    return {
      text: row.$('item-content').getText(),
      input: row.$('input');
    }
  }).then(function(rows) {
    // Here you have an array with elements.
    // Array.<{text: string, input: WebElement}>
    // Find the text you are looking for and return.
    for (var i = 0; i < rows.length; i++) {
      if (rows[i].text === localeToLookFor) {
        return rows[i];
      }
    }
    throw Error('Could not find element');
  }).then(function(radioInput) {
    // Here you should have a WebElement with the radio.
  });
});


text:
Q: Springboot and Liberty Server - Spring JPA - Having database credentials in server settings file instead of Spring application.properties I am using Springboot with Spring JPA.  My application is connecting to database and I am currently using
spring.datasource.url=jdbc:oracle:thin:@.....
spring.datasource.username=blahblah
spring.datasource.password=xyz

, specified in Spring application.properties file.
This is all working fine; however, we dont want to proivide this information to developers but instead let our servers team set these inside the production servers running WAS Liberty (or Open Liberty).
How to use these credentials in Liberty server.xml and have Spring JPA still do what it needs to do?

A: Spring boot documentation here indicates that you can use the spring.datasource.jndi-name property instead to point at the JNDI name of a configured data source.
Here is how to configure an Oracle data source in Liberty server configuration (server.xml file),
<server>
  <featureManager>
    <feature>jdbc-4.2</feature>
    <feature>jndi-1.0</feature>
    <!-- ... other features here -->
  </featureManager>

  <dataSource jndiName="jdbc/oracle">
    <jdbcDriver libraryRef="OracleJDBCLib"/>
    <properties.oracle URL="jdbc:oracle:thin:@//..." user="blahblah" password="xyz"/>
  </dataSource>

  <library id="OracleJDBCLib">
    <fileset dir="/path/to/oracle/ojdbc8.jar"/>
  </library>

</server>

and then you should be able to set,
spring.datasource.jndi-name=jdbc/oracle

Here is a link to documentation on creating data sources in Liberty.


text:
Q: Incorrect figure numbering using wrapfigure I am having an issue with wrapfigure and I can't seem to find a solution anywhere. Not even in the documentation. What happens is as follows: I have a wrapfigure environment in my code followed by a standard figure environment. The standard figure is placed on top, but gets a figure number higher than the wrapped figure. This is my code:
\documentclass{article}

\usepackage{lipsum}
\usepackage{wrapfig}
\usepackage{graphicx}

\begin{document}
    \begin{wrapfigure}{r}{3cm}
    \includegraphics[width=\linewidth]{C:/Users/<username>/Desktop/1.jpg}
    \caption{Picture of a dog.}
    \end{wrapfigure}
    \lipsum[1-2]
    \begin{figure}
        \centering
        \includegraphics[width=.7\linewidth]{C:/Users/<username>/Desktop/2.jpg}
        \caption{Another picture of a dog.}
    \end{figure}
\end{document}

And this is my output:

Does any of you perhaps know the solution?

A: that is expected as wrapfigure is a non floating environment so floating figures can float past it.
If it is still that way in the final document version after all other edits done, you can fix as follows:
put
\addtocounter{figure}{1}

in the wrapfig before the caption and
\addtocounter{figure}{-2}

in the figure just before the caption.