text:
Q: Story ID: Early cyberpunk is restored with IQ-increasing drugs after a failed mission I'm guessing it is an 80s story or novellete.
The main character is a pretty unemotional mercenary.  After a failed mission he is put into the hospital, where the AIs there keep him alive, milking his bank account to pay for an experimental drug which later turns out to increase IQ.
After his account is empty, he's woken up and released, whereupon he goes back and finishes his earlier mission

A: Videostar by Walter Jon Williams.
The protagonist is Ric - I don't think we ever learn his surname. Ric is a member of a gang called the Cadillacs, and at the beginning of the story he goes into a meeting with other gang leaders:

So there was a last meeting, Ric of the Cadillacs, Mares of the Squires, Jacob of the Last Men. Ric walked into the meeting with a radar-aimed dart gun built into the bottom of his briefcase, each dart filled with a toxin that would stop the heart in a matter of seconds. When he walked out it was with a money spike in his pocket, a stainless steel needle tipped with liquid crystal. In the heart of the crystal was data representing over eighty thousand Seven Moons dollars, ready for deposit into any electric account into which he could plug the needle.

But:

He began to feel sick in the Tangier to Houston suborbital shuttle, a crawling across his nerves, pinpricks in the flesh. By the time he crossed the Houston port to take his domestic flight to L.A. there were stabbing pains in his joints and behind his eyes. He asked a flight attendant for aspirin and chased the pills with American whiskey.
...
As they strapped him into a stretcher at the unscheduled stop in Flagstaff, Ric was still screaming, unable to stop himself. Jacob had poisoned him, using a neurotoxin that stripped away the myelin sheathing on his nerves, leaving them raw cords of agonized fiber. Ric had been in a hurry to finish his business and had only taken a single sip of his wine: that was the only thing that had saved him.

The drug is Genesios Three:

Genesios Three was a new neurohormone, developed by the orbital Pink Blossom policorp, that could repair almost any amount of nerve damage. As a side effect it built additional neural connections in the brain, thus raising the IQ, and made people high.

and as you say the AI keeps Ric in hospital until his money is all gone:

The week of Genesios therapy took fifteen thousand dollars out of Ric's spike.

The previous months of treatment had accounted for another sixty-two thousand.

What Ric didn't know was that Genesios therapy could have been started at once and saved him most of his funds, but that the artificial intelligences working for the hospital had tagged him as a suspect character, an alien of no particular standing, with no work history, no policorporate citizenship, and a large amount of cash in his breast pocket. The AIs concluded that Ric was in no position to complain, and they were right.

Computers can't be sued for malpractice. The doctors followed their advice.


text:
Q: Cannot copy files between mapped drives when using @file variable Desired behaviour:
I wish to copy .log files from one network location to another. This does work when one drive is local and another is network, however network to network location and I get a error when using @files variable.
Specific problem:
The following below will list all files in a given directory and then copy them to another network location. I always get the same error: Invalid argument/option - '@file'. This does however work when I copy from local drive to network location, but not network location to network location, even if I map the drives:
forfiles /M *.log /P "\\10.11.233.91\vol_tx01\AsRunLogs\Playbox25" /c "cmd /c COPY @file "\\172.16.2.118\Live_Engineering\AsRuns\PBOX01""
    #ERROR: Cannot use UNC

Or mapped folders:
forfiles /M *.log /P ":Z\" /c "cmd /c COPY @file ":/Y""
    #ERROR: INVALID argument/option - '@file'

A: What's wrong with (this does ini files)
copy \\127.0.0.1\C$\windows\*.ini \\127.0.0.1\D$\*.*

You are using no features of forfiles that copy doesn't have.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using initParams in Silverlight 4 project I'm trying to upgrade a project that uses Silverlight 2 to use Silverlight 4 but I have problem with initparam to set domain.
The old Silverlight 2 project:
 <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

            <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/EKAKC.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

          </form>

And from Default.aspx.cs: Xaml1.InitParameters += "Domain=" + domain;
The new Silverlight 4 project:

    <form id="form1" runat="server" style="height: 100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

        <object  type="application/x-silverlight-2" data="data:application/x-silverlight,"
            width="300" height="300">
            <param name="source" value="EKAKC.xap"/>
            <param name="initParams" value="<%= string.Format("WCFReferenceURL={0}", ConfigurationManager.AppSettings["WCFReferenceURL"])%>" />
            </object>

The Domain will not be set in my new Silverlight 4 project

A: It may be necessary to encode the value:-
       <param name="initParams" value="<%= "WCFReferenceURL=" + Server.HTMLEncode(ConfigurationManager.AppSettings["WCFReferenceURL"])%>" />


text:
Q: Suggestion for Multi-points slider for angular I can't find a slider that works with angular that can have more than 2 points.
I found the ng5-slider library (https://www.npmjs.com/package/ng5-slider) that works perfectly for a minValue and maxValue but what I'm trying to acheive is this:
a slider that holds time data (24 hours) and shows events based on the time on it.
Any suggestions please?
Thank you in advance.

A: I couldn't found any slider that can handle multi points but I found a better slider that is compatible with Angular:
https://www.npmjs.com/package/@angular-slider/ngx-slider


text:
Q: LINQ to SQL selecting all records which have any word in the string split string1: How
string2: How Are you ?
What i want to do is select all records from the database by checking string2 against string1 and selecting any record which have either "How" or "Are" or "you".
 pager1.ItemCount = appliedQuery.Where(q => q.string1.Contains(string2)).count();

PlEASE NOTE: String1 is just one word and I just want to get all records in the db with any occurance of any word in string2.
I understand that string2 needs to split, however after the split how do i use it in the linq query statement to fetch the records?
Thanks in advance

A: Split string2 into an array of strings:
string[] words = string2.Split(' ');

Then check if string1 is in any of the items in the array:
pager1.ItemCount = appliedQuery.Where(q => words.Contains(q.string1)).Count();

A: One possible solution could be following:
foreach(string s in string2.Split(' '))
{
    pager1.ItemCount += appliedQuery.Where(q => q.string1.Contains(s)).count();
}

A: Check out how I constructed my linq query. I hope this helps.
Just try to copy and paste the code in your console app to see the result.
class Program
{
    static void Main(string[] args)
    {
        // List of strings that you may consider it from your
        /// database which is String1
        List<string> lstStrings = new List<string>();
        lstStrings.Add("twenty one");
        lstStrings.Add("twenty two");
        lstStrings.Add("twenty three");
        lstStrings.Add("twenty four");

        // The string to compare to which is your String2
        string strString = "one two four";

        // Splitting the strings to be compared
        string[] strArray = strString.Split(' ');

        // The linq that helps you query the data exactly as what you wanted
        var result = (from string A in lstStrings
                               from string B in strArray
                               where A.Contains(B)
                               select A).Distinct();

        // Count result
        Console.WriteLine(result.Count());

        // Individual values
        foreach (string str in result)
        {
            Console.WriteLine(str);
        }

        Console.ReadLine();
    }
}


text:
Q: input from file in batch file problem i need to enter password two time for this command when it ask
createuser -h localhost -P -p 5432 -s -d -r -e postgres

i tried
createuser -h localhost -P -p 5432 -s -d -r -e postgres < temp.txt

where temp.txt contains

password
  password

it still asks for password
any suggestions?

A: The createuser program probably makes its own connection to the terminal rather than reading from its standard input, this is common behavior where passwords are concerned. You'll probably have better luck using the SQL CREATE ROLE rather than createuser:
echo "CREATE ROLE postgres CREATEROLE CREATEDB SUPERUSER PASSWORD 'password';" \
    | psql -h localhost -p 5432 databasename

Where "databasename" is the name of your database.
From the fine manual:

createuser is a wrapper around the SQL command CREATE ROLE. There is no effective difference between creating users via this utility and via other methods for accessing the server.


text:
Q: Solr Spatial search two coordinates I'm trying to query with the lat/long bounds but am having troubles.
fq=geo-coordinates:"[(40.87967,-74.0183) TO (40.7,-73.9072)]" does not work, I have also tried
fq=geo-coordinates:"[(40.87967 TO 40.7,-74.0183 TO -73.9072)]"
I am aware there is a coordinate plus a radius query but I need this query to be strictly between two coordinates.
This question is similar: How to search records between two coordinates using solr spatial search
But the answer does not take into consideration a single location_rpt schema field.

A: Your first try was almost right. Those parenthesis shouldn't have been there, nor the double-quotes:
fq=geo-coordinates:[40.87967,-74.0183 TO 40.7,-73.9072]

The quotes you had made the query look like a field/term query, which this isn't -- it's a range query.


text:
Q: Making ANTLRWorks handle whitespaces automatically I have an ANTLR grammar like this:
grammar HelloGrammar1;

ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;
STATEMENT : 'hello' ID ';' ;
WS  :   (' '|'\t'|'\r'|'\n')* ;

I want it to parse the following text: hello qwerty ;. It doesn work this way. If I change my string to helloqwerty;, everything is fine. I can also change grammar to:
grammar HelloGrammar2;

ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;
STATEMENT : 'hello' WS ID WS ';' ;
WS  :   (' '|'\t'|'\r'|'\n')* ;

And in this case, hello qwerty ; works fine. Is it possible to make ANTLR skip whitespaces automatically? (i.e. - I want to make HelloGrammar1 work with hello qwerty ;)
Update
If it makes sense: I'm testing it in ANTLRWorks.
Update 2
Also tried this way:
grammar HelloGrammar;

ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;
STATEMENT : 'hello' ID ';' ;
WS  :   (' '|'\t'|'\r'|'\n') { $channel = HIDDEN; } ;

Still doesn't work.
Update 3
I'm using "Interpreter" tab with "STATEMENT" rule selected.

A: I think the issue may be that you should change STATEMENT (currently a lexer rule) to statement (a parser rule)
grammar HelloGrammar;

statement : 'hello' ID ';' ;
ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;
WS  :   (' '|'\t'|'\r'|'\n') { $channel = HIDDEN; } ;

In ANTLRWorks this accepts:
hello qwerty;
hello   qwerty;
hello loki2302;
hello   qwerty  ;

but does not accept:
helloqwerty;
helloqwerty ;
hello;
hello qwerty


text:
Q: How to dynamically create cron jobs with Django model? I need to create a cron job for each object in a model. I researched about celery and crontab, but these libraries use a static crons directly from code. Any library that help to dynamically create a tasks to each object in a model?

A: from django.db.models import signals
from django.db import transaction
from django.dispatch import receiver

from .tasks import <some celery task>

@receiver(signals.post_save, sender=User)
def run_task_on_user_save(sender, instance, created, **kwargs):
    if created:
        transaction.on_commit(
            lambda: <some celery task>
        )

You can use django signals to run a task on every new User save.
or
You could use django celery beat to run periodic tasks and have the task loop through all your objects to preform the logic you need.

A: I found some sample code that is model-driven here (Django model cron jobs)
The crontab is synchronised when an entry is changed, and relevant environment variables, function name and arguments are provided. You might want to store this as an app called "scheduler" to match the imports.
# FILE: models.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
      Title: Scheduler models
     Author: Will Hardy (http://willhardy.com.au)
       Date: December 2007
 Test suite: manage.py test scheduler
  $Revision: $

Description: Integrates Python and the native crontab.
             A more beginner-friendly interface is offered, and entries are stored in a database.
             The database is used to update the local crontab.

"""

__all__ = ('Task', 'update_crontab')

import os
import tempfile
from django.db import models
from datetime import datetime, timedelta
import calendar
from django.utils.translation import ugettext as _

TIME_SCALES = (
            ("hour", _("hour")),
            ("day", _("day")),
            ("week", _("week")),
            ("month", _("month")),
            ("year", _("year")),
            )

class Task(models.Model):
    """
        Add a task to be entered into this user's crontab.
        When the time comes, a simple python function is called with a single text
        argument. This interface is not intended to be comprehensive, rather, it is
        intended to be pointed to a python function that is specially prepared to
        carry out the intended function and only needs to be told when.

        name:       A name is good for the user to remember this, but is not necessary.
        active:     Allows the task to be temporarily switched off.
        start:      A date and time when this task should be run.
        stop:       A date and time after which repetitions should not take place.
        time_scale: The type of repetition that will take place.
        period:     How often the repetitions will take place. (zero is for no repetitions)
        times_run:  How many times this has already been executed
        function:   The full path to the python function to be executed (with periods).
        argument:   A single string argument to be given to the function.
        expert:     Allows direct manipulation of the crontab entry (only the time/date part please!)
    """
    name = models.CharField(_("name"), max_length=200, default="", blank=True)
    active = models.BooleanField(_("active"), default=True)
    start = models.DateTimeField(_("start"), default=datetime.now(), null=True, blank=True)
    stop = models.DateTimeField(_("stop"), null=True, blank=True)
    time_scale = models.CharField(max_length=5, choices=TIME_SCALES, null=True, blank=True)
    period = models.PositiveSmallIntegerField(default=0, null=True)
    times_run = models.PositiveSmallIntegerField(default=0, editable=False)
    function = models.CharField(max_length=200)
    arguments = models.CharField(max_length=200, default="", blank=True)
    #expert = models.CharField(max_length=100, default="", blank=True)

    class Meta:
        verbose_name = _("task")
        verbose_name_plural = _("tasks")

    class Admin:
        list_display = ('__unicode__', 'start', 'time_scale', 'times_run')

    def __unicode__(self):
        " A useful textual description of this task. "
        if self.name:
            return self.name
        elif self.arguments:
            # TODO: A better automatic description i.e. "Automatic task every tuesday."
            return u"%s %s" % (self.get_function_name(), self.arguments)
        else:
            return u"Task %d" % self.id

    def save(self):
        """ Updates the crontab when a task is saved.
        """
        super(Task, self).save()
        update_crontab()

    def get_module_path(self):
        """ Get the module path, without the function name.
            >>> start = datetime(2007, 12, 1, 6, 23)
            >>> task = Task(function="path.to.test", start=start)

            >>> task.get_module_path()
            'path.to'
            >>> task.function = "test"
            >>> task.get_module_path()
            ''
            >>> task.function = ""
            >>> task.get_module_path()
            ''
        """
        return ".".join(self.function.split(".")[:-1])

    def get_function_name(self):
        """ Get the function name, without the module path.
            >>> start = datetime(2007, 12, 1, 6, 23)
            >>> task = Task(function="path.to.test", start=start)

            >>> task.get_function_name()
            'test'
            >>> task.function = "test"
            >>> task.get_function_name()
            'test'
            >>> task.function = ""
            >>> task.get_function_name()
            ''
        """
        return self.function.split(".")[-1]

    def get_crontab_entry(self):
        """ Gets the entire contrab line, including time specification and command.
            >>> start = datetime(2007, 12, 1, 6, 23)
            >>> task = Task(function="test", start=start)

            >>> task.get_crontab_entry() is None
            True
            >>> task.id = 5
            >>> len(task.get_crontab_entry().split())
            9
        """
        crontab_time = self.get_crontab_time()
        crontab_command = self.get_crontab_command()
        crontab_argument = self.get_crontab_argument()
        if crontab_time and crontab_command and crontab_argument:
            return ' '.join([crontab_time, crontab_command, crontab_argument])

    def get_crontab_argument(self):
        """ Forms the argument to be used for the crontab command.
            >>> start = datetime(2007, 12, 1, 6, 23)
            >>> task = Task(function="test", start=start)

            >>> task.get_crontab_argument() is None
            True
            >>> task.id = 5
            >>> task.get_crontab_argument()
            'task_005'
        """
        if self.id:
            return 'task_%03d' % self.id

    def get_crontab_command(self):
        """ Forms the command to be used for the crontab command.
            >>> start = datetime(2007, 12, 1, 6, 23)
            >>> task = Task(function="test", start=start)
            >>> task.get_crontab_command().rstrip("c").endswith("py") or task.get_crontab_command()
            True

            TODO: Prevent issues with spaces in filename
        """
        path = get_command_path()
        return "%s %s" % ("/usr/bin/env python", path)

    def get_crontab_time(self):
        """ Get the time part of a crontab line for this task.
            This is a space separated list of 5 entries:
                 "2 * * * *"
            Multiple values are also possible, if self.period is set:
                 "2,32 * * * *"

            >>> the_time = datetime(2007, 12, 1, 6, 23) # Sat 1 Dec 2007, 6:23am
            >>> task = Task(function="test", start=the_time)
            >>> task.period = 1

            >>> task.time_scale = "hour"
            >>> task.get_crontab_time()
            '23 * * * *'

            >>> task.time_scale = "day"
            >>> task.get_crontab_time()
            '23 6 * * *'

            >>> task.time_scale = "week"
            >>> task.get_crontab_time()
            '23 6 * * 6'

            >>> task.time_scale = "month"
            >>> task.get_crontab_time()
            '23 6 1 * *'

            >>> task.period = 2
            >>> task.time_scale = "day"
            >>> task.get_crontab_time()
            '23 6,18 * * *'

            >>> task.time_scale = "year"
            >>> task.get_crontab_time()
            '23 6 1 6,12 *'

            >>> task.period = 6
            >>> task.time_scale = "month"
            >>> task.get_crontab_time()
            '23 6 1,6,11,16,21,26 * *'

            >>> task.period = 0
            >>> task.get_crontab_time()
            '23 6 1 12 *'

            >>> task.period = 5
            >>> task.time_scale = None
            >>> task.get_crontab_time()
            '23 6 1 12 *'
        """
        def with_repeats(start, max):
            """ Get a sequence of repeated values in CSV form.
                e.g. with_repeats(14, 31) with a period of 3 will give: "4,14,24"
            """
            values = get_stepped_sequence(start, max, self.period)

            # Convert to string and join using commas
            return ",".join([ str(v) for v in values ])

        # Synchronise our period and timescale if repetition is turned off
        if self.period == 0:
            self.time_scale = None
        if self.time_scale is None:
            self.period = 0

        # Default all values to stars
        minute = hour = day = month = weekday = "*"

        if self.time_scale == "hour":
            minute = with_repeats(self.start.minute, 60)

        elif self.time_scale == "day":
            minute = str(self.start.minute)
            hour = with_repeats(self.start.hour, 24)

        elif self.time_scale == "week":
            minute = str(self.start.minute)
            hour = str(self.start.hour)
            weekday = with_repeats((self.start.weekday() + 1) % 7, 7)

        elif self.time_scale == "month":
            minute = str(self.start.minute)
            hour = str(self.start.hour)
            day = with_repeats(self.start.day, 31)

        else: # catch both "year" and None
            minute = str(self.start.minute)
            hour = str(self.start.hour)
            day = str(self.start.day)
            month = with_repeats(self.start.month, 12)

        return " ".join([minute, hour, day, month, weekday])

    def next_occurrence(self, reference=None):
        """ The time and date of the next occurace to take place.
            >>> reference = datetime(2007, 12, 12, 17, 51) # Wed 12 Dec 2007, 5:51pm
            >>> start = datetime(2007, 11, 3, 6, 23) # Sat 3 Nov 2007, 6:23am
            >>> task = Task(function="test", start=start)

            >>> task.period = 2
            >>> task.time_scale = "hour"
            >>> task.next_occurrence(reference=reference)
            datetime.datetime(2007, 12, 12, 17, 53)

            >>> task.time_scale = "day"
            >>> task.next_occurrence(reference=reference)
            datetime.datetime(2007, 12, 12, 18, 23)

            >>> task.time_scale = "week"
            >>> task.period = 1
            >>> task.next_occurrence(reference=reference)
            datetime.datetime(2007, 12, 15, 6, 23)

            >>> task.time_scale = "month"
            >>> task.next_occurrence(reference=reference)
            datetime.datetime(2008, 1, 3, 6, 23)
        """
        #def get_next_step(start, ref, max):
            #" A convenience function that provides the next step "
            #steps = get_stepped_sequence(start, max, self.period)
            #steps = [ (i > ref and i) or i+max for i in steps ]
            #value = min(steps)
            #return value

        if not reference:
            reference = datetime.now()

        attempt = None
        period_delta = None

        if self.start > reference:
            return self.start

        minute, hour, day, month, year = reference.minute, reference.hour, reference.day, reference.month, reference.year

        # For each possible time scale, work out a naive start time and a period delta.
        # If the start time is behind the reference time, increment until we have a time in the future.

        if self.time_scale == "hour":
            period_delta = timedelta(minutes=60/self.period)
            minute = self.start.minute

        if self.time_scale == "day":
            period_delta = timedelta(hours=24/self.period)
            minute = self.start.minute
            hour = self.start.hour

        if self.time_scale == "week":
            period_delta = timedelta(hours=7*24/self.period)
            minute = self.start.minute
            hour = self.start.hour

            # Move backwards in time to the correct day of the week
            day_correction = self.start.weekday() - reference.weekday()
            if day_correction > 0:
                day_correction - 7
            correction_delta = timedelta(days=day_correction)
            attempt = datetime(year, month, day, hour, minute) + correction_delta

        if self.time_scale == "month":
            minute = self.start.minute
            hour = self.start.hour
            day = self.start.day

            # Days in current month needs to be accurate, to avoid landing on
            # another day of the month
            days_in_month = reference.month in (1,3,5,7,8,10,12) and 31 or \
                             reference.month in (4,6,9,11) and 30 or \
                             calendar.isleap(reference.year) and 29 or 28
            period_delta = timedelta(days=days_in_month/self.period)

        if self.time_scale == "year":
            days_in_year = calendar.isleap(reference.year) and reference.month <= 2 and 366 or \
                           calendar.isleap(reference.year+1) and reference.month > 2 and 366 or 365
            period_delta = timedelta(days=days_in_year/self.period)
            minute = self.start.minute
            hour = self.start.hour
            day = self.start.day
            month = self.start.month

        # If nothing was matched either, given up
        if not period_delta:
            return self.start > reference and self.start or None

        # If not done already, make an attempt
        if not attempt:
            attempt = datetime(year, month, day, hour, minute)

        # Keep incrementing the attempt until it is in the future
        while attempt < reference:
            attempt += period_delta

        return attempt

    def upcoming(self, reference=None):
        """ If the task has started or is due to start in the next 24 hours.

            >>> reference_01 = datetime(2007, 11, 11, 17, 51)
            >>> reference_02 = datetime(2007, 11, 12, 17, 51)
            >>> start = datetime(2007, 11, 13, 6, 23)
            >>> task = Task(function="test", start=start)
            >>> task.upcoming(reference=reference_01)
            False
            >>> task.upcoming(reference=reference_02)
            True
            >>> task.upcoming()
            True
        """
        if not reference:
            reference = datetime.now()
        return self.start - reference < timedelta(hours=24)

    def imminent(self, reference=None):
        """ If this task needs to be executed very soon
            (and thus should be done immediately).

            >>> reference_01 = datetime(2007, 11, 11, 17, 51)
            >>> reference_02 = datetime(2007, 11, 12, 17, 51)
            >>> start        = datetime(2007, 11, 12, 17, 52)
            >>> task = Task(function="test", start=start)
            >>> task.imminent(reference=reference_01)
            False
            >>> task.imminent(reference=reference_02)
            True
            >>> task.imminent()
            False
        """
        if not reference:
            reference = datetime.now()
        next = self.next_occurrence(reference=reference)
        if next:
            return next - reference < timedelta(minutes=5)

        return False

def get_stepped_sequence(start, max, period):
    """ Get a stepped sequence, wrapping around a max value.
        period is the number of values involved.
        >>> get_stepped_sequence(3, 56, 4)
        [3, 17, 31, 45]
        >>> get_stepped_sequence(45, 46, 2)
        [22, 45]
        >>> get_stepped_sequence(45, 46, 1)
        [45]
        >>> get_stepped_sequence(45, 46, 0)
        [45]
        >>> get_stepped_sequence(47, 46, 0)
        []
        >>> get_stepped_sequence(5, 11, 12)
        []
    """

    # Some exceptional cases
    if start > max:
        return []
    if period > max:
        return []
    if not period:
        return [ start ]

    step = max / period

    values = []
    while len(values) < period:
        offset = len(values) * step
        value = ((offset + start - 1) % max) + 1
        values.append(value)

    values.sort()

    return values

def get_command_path():
    """ Returns the path to the command to be run through cron. """
    return '%s/%s' % (os.path.dirname(__file__), 'run_task.py')

def update_crontab():
    """ Synchronises the database and the crontab.
        Issue: any jobs that are imminent may not be run.
    """
    tasks = Task.objects.all()
    # Create a series of entries from each of the tasks
    lines = [ task.get_crontab_entry() for task in tasks ]
    # Add an extra line for maintenance
    #lines.append(Task.get_maintenance_entry())
    # Join the lines into a single file
    crontab = "\n".join(lines)

    # Get the preexisting crontab and remove old lines
    old_crontab = tempfile.NamedTemporaryFile()
    filename = old_crontab.name
    os.system('crontab -l > %s' % filename)

    # Remove old lines
    crontab_lines = []
    for line in old_crontab.readlines():
        if get_command_path() not in line:
            crontab_lines.append(line)
    old_crontab.close()

    # Append environment lines to the crontab
    # Whatever environment is being used to update the crontab
    # will be set in the crontab so that the script that is
    # eventually run, will run with the same environment variables..

    # 1. name of the settings module for django
    settings_key = 'DJANGO_SETTINGS_MODULE'
    if settings_key in os.environ:
        settings_module = os.environ[settings_key]
    else:
        settings_module = 'settings'
    if settings_module.split('.')[-1] == '__init__':
        settings_module = ".".join(settings_module.split(".")[:-1] + ['settings'])
    environment_line = '%s=%s\n' % (settings_key, settings_module)
    if environment_line not in crontab_lines:
        crontab_lines.append(environment_line)

    # 2. python path
    pythonpath_key = 'PYTHONPATH'
    environment_line = '%s=%s\n' % (pythonpath_key, os.environ[pythonpath_key])
    if pythonpath_key in os.environ and environment_line not in crontab_lines:
        crontab_lines.append(environment_line)

    # Append new lines
    for task in Task.objects.filter(active=True):
        entry = task.get_crontab_entry() + '\n'
        if entry:
            crontab_lines.append(entry)

    # Set the new crontab
    new_crontab = tempfile.NamedTemporaryFile()
    new_crontab.writelines(crontab_lines)
    new_filename = new_crontab.name
    new_crontab.flush()
    os.system('crontab %s' % new_filename)
    new_crontab.close()

# FILE: views.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
      Title: Scheduler views
     Author: Will Hardy (http://willhardy.com.au)
       Date: December 2007
 Test suite: ../models test scheduler
  $Revision: $

Description: Intergrates Python and the native crontab.
             A more beginner-friendly interface is offered, and entries are stored in a database.
             The database is used to update the local crontab.

"""

from scheduler.models import Task

def run_task(task_id):
    """ Run the task with the given ID.

        >>> task = Task(function="scheduler.tests.test_function")
        >>> task.save()
        >>> run_task(task.id)
        Success!
    """

    task = Task.objects.get(id=task_id)
    module = __import__(task.get_module_path(), [], [], task.get_function_name())
    function = getattr(module, task.get_function_name())
    if task.arguments:
        args = task.arguments.split(",")
        function(*args)
    else:
        function()

    # Do some accounting
    task.times_run += 1
    task.save()

# FILE: run_task.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
      Title: Scheduler crontab entry point
     Author: Will Hardy (http://willhardy.com.au)
       Date: December 2007
  $Revision: $

Description: This script is to be called directly.

"""
import os
import sys
from scheduler.models import Task, update_crontab
from scheduler.views import run_task

if __name__ == "__main__":

    # If this module is called directly, run the given task
    usage = 'USAGE: %s task_id' % sys.argv[0]
    if len(sys.argv) == 2:
        command = sys.argv[1]
        if command == "update":
            update_crontab()
            exit()
        # Try to parse the task id from the command
        if command.startswith('task_'):
            command = command[5:]
        try:
            task_id = int(command)
        except ValueError:
            sys.exit(usage)

        # Run the task matching the given task_id
        try:
            run_task(task_id)
        except Task.DoesNotExist:
            sys.exit("Task with this ID (%s) does not exist." % task_id)
    else:
        sys.exit(usage)


text:
Q: SharePoint 2013 - User Profile Photo's Image Rendition Is it possible to activate image rendition on the MySites Host Collection?  I need to be able to allow users to edit (crop etc.) their profile photos upon upload.  Is image rendition applicable to MySites?  Will I need a third party tool instead to accomplish this?

A: I am not sure you can do it with Mysite, You can enable it using the hacking the url.

*

*Enable the BlobCache on Mysite

*then go this url "www.mysite.com/_layouts/15/ImageRenditionSettings.aspx" and create item here.

But i am not sure will it work, But another thing Bydefault Profile picture having three sizes when people upload the picture.
Read more here:
SharePoint 2013: User Profile Photo Sizes
Image Renditions in SharePoint 2013


text:
Q: How to import constants from .h file into python module What is a recommended way to import a bunch of constants defined in a c-style (not c++, just plain old c) .h file into python module so that it can be used in python's part of a project. In the project we use a mix of languages and in perl I can do this importing by using h2xs utility to generate .pm module.
Constants definition looks like
#define FOO 1
enum {
    BAR,
    BAZ
};

etc.
C-style comments are also presented an have to be properly handled.

A: I recently used the pyparsing library to scan for enum constants.  Here it is, along with a sample string and the resulting output.  Notice it also handles comments and commented out sections.  With a little modification it could stuff the constants in a dictionary.
from pyparsing import *

sample = '''
    stuff before

    enum hello {
        Zero,
        One,
        Two,
        Three,
        Five=5,
        Six,
        Ten=10
    }

    in the middle

    enum blah
    {
        alpha, // blah
        beta,  /* blah blah
        gamma = 10 , */
        zeta = 50
    }

    at the end
    '''

# syntax we don't want to see in the final parse tree
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_equal = Suppress('=')
_comma = Suppress(',')
_enum = Suppress('enum')

identifier = Word(alphas,alphanums+'_')
integer = Word(nums)

enumValue = Group(identifier('name') + Optional(_equal + integer('value')))
enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl

enum.ignore(cppStyleComment)

for item,start,stop in enum.scanString(sample):
    id = 0
    for entry in item.list:
        if entry.value != '':
            id = int(entry.value)
        print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
        id += 1

OUTPUT:
HELLO_ZERO = 0
HELLO_ONE = 1
HELLO_TWO = 2
HELLO_THREE = 3
HELLO_FIVE = 5
HELLO_SIX = 6
HELLO_TEN = 10
BLAH_ALPHA = 0
BLAH_BETA = 1
BLAH_ZETA = 50

A: I once had to do something similar, and in the end I did something strange but highly reliable. Dealing with all the possibilities for how values might be defined is tricky... for instance, you have to handle
#include "someotherfile.h"
enum NewEnum {
   A = -5,
   B = SOME_OTHER_ENUM,
   C,
   D = 3
};

(which is really nasty and no one should ever do...)
In the end, part of my build process was a perl script that parsed the header file for all enums and defines, and then produced a .c file that included the header and was nothing more then a bunch of print statements, printing the actual value for each define. This file was compiled and executed, and the output of that was used to produce the next source file ( Java, in my case ).
This ensured that I got the right values, as I was using the C preprocessor and compiler to produce the answers.

A: I'd suggest the other way round, if possible: define all your constants in a Python dict or module and auto-generate the .h in Python. It will be much, much easier.

A: Create a script/program that is called from make and creates the necessary python file. If you only need #define and enum it shouldn't be too hard to write. Then remember NOT to check this python file into source control as you want the build process to force the regeneration of the file every time.


text:
Q: How to map a particular field in firestore database For example, if I have the fields like
empId,empName in Employees collection and
empName,city in another collection called EmployeeCities
If I change the empName in the Employees collection, the change should reflect in EmployeeCities.
I know I can update them manually but, I am asking if we can map certain fields as in SQL primary key and foreign key.

A: Firestore is a NoSQL database, (not a relational database), which means it doesn't enforce relationships between documents and collections.  You cannot designate fields as primary or foreign key.  Any relationship between documents and collection are those that you impose for yourself in your source code.  The database will not enforce them for you.


text:
Q: I get a FileNotFoundError when I run this Program I'm dealing with moving files from subfolders to another location to organize my Files. While doing so I encountered some errors from this program.
import os
from shutil import move

src = "C:\\Users\\User\\Desktop\\SMALL"
dst = "C:\\ALL IN ONE\\Temporary Folder"

if not os.path.exists(dst):
    os.makedirs(dst)
for x, y, z in os.walk(src):
    for files in z:
        if files.endswith("txt"):
            move(files, dst)

When I run the program, it raises a FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.txt' -> 'C:\\ALL IN ONE\\Temporary Folder\\0.txt' error and a bunch of other "Traceback Errors" (if that's what they're called)

A: You need to construct the source path.  Try changing:
move(files, dst)

to:
path = os.path.join(x, files)
move(path, dst)

You might also want to rename files to file, since it's just a single file each time through the loop.
Justin Ezequiel pointed out that including src in the call to os.path.join is incorrect, so I've updated the answer to simply join x and files.


text:
Q: Intellij IDEA. Several SBT consoles How I can run several SBT consoles in Intellij IDEA 12? I need it because I want to run 3 project modules, but when I run first it blocks SBT console until I kill process. I can achieve same result using 3 command line windows (cmd) but I want to run all from IDE.
P.S. I have installed sbt plugin.

A: You could open multiple terminal windows in the IDE and use SBT (see highlighted area):


text:
Q: CreateNdefMessageCallback conflict with ContentProvider permissions I write a program provider a provider for another apps of our company. The provider need a permission to access the data.
We also have a interface need use NFC send json data to another devices.
When we access the provider in CreateNdefMessageCallback.createNdefMessage like
    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        Context context = this;

        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse("content://demo/data-lists"),
                null,
                null,
                null,
                null);
        // FIXME Strange: Will never goes here ...
        mMessage = getMessage(cursor);

        NdefMessage msg = new NdefMessage(
                new NdefRecord[] {
                        createMimeRecord(mMimeType, mMessage.getBytes())
                });
        return msg;
    }

There is very strange, we never get a cursor until remove the permission.
Permission Declear
<permission
    android:name="com.client.permission.MY_PERMISSION"
    android:label="@string/provider_label"
    android:protectionLevel="signatureOrSystem" />

Request permision
<uses-permission android:name="com.client.permission.MY_PERMISSION" />

Provider permission declear
    <provider
        android:name=".provider.DemoProvider"
        android:authorities="demo"
        android:multiprocess="true"
        android:permission="com.client.permission.MY_PERMISSION" />

Currenty the provider and the NFC-send activity in the same application and read the provider data will but the NFC callback.
And if I remove the permission for the provider, this will work fine.
like the
Provider without permission
    <provider
        android:name=".provider.DemoProvider"
        android:authorities="demo"
        android:multiprocess="true"/>

Please help.
Thanks.

UPDATED 2013-03-14
It's very strange. I found this issue only when the provider and the NFC Activity in the same application. like this.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfcdemo"
    android:versionCode="6"
    android:versionName="build-svn291" >

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

    <permission
        android:name="com.client.permission.MY_PERMISSION"
        android:label="@string/provider_label"
        android:protectionLevel="signatureOrSystem" />

    <uses-permission android:name="com.client.permission.MY_PERMISSION" />

    <activity
        android:name=".ui.MainTabActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <provider
        android:name=".provider.DemoProvider"
        android:authorities="demo"
        android:multiprocess="true"
        android:permission="com.client.permission.MY_PERMISSION" />
</manifest>

But if I use two separated application, it works will like.
<!-- Application Provider -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfcdemo.provider"
    android:versionCode="6"
    android:versionName="build-svn291" >

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

    <permission
        android:name="com.client.permission.MY_PERMISSION"
        android:label="@string/provider_label"
        android:protectionLevel="signatureOrSystem" />

    <provider
        android:name=".provider.DemoProvider"
        android:authorities="demo"
        android:multiprocess="true"
        android:permission="com.client.permission.MY_PERMISSION" />
</manifest>

<!-- Application UI -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfcdemo.ui"
    android:versionCode="6"
    android:versionName="build-svn291" >

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

    <uses-permission android:name="com.client.permission.MY_PERMISSION" />

    <activity
        android:name=".ui.MainTabActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</manifest>


text:
Q: Is it possible 1 application consume multiples exchanges? What i have to do is consume 2 diferents queues in rabbitMQ, each one in a diferent vhost and diferent exchange.
Do i have to create 2 connections? is it possíble?
My .env is something like this:
CONSUMER_DIRECT_HOST=localhost
CONSUMER_DIRECT_VHOST=pd_logs
CONSUMER_DIRECT_LOGIN=guest
CONSUMER_DIRECT_PASSWORD=guest
CONSUMER_DIRECT_PORT=5672
CONSUMER_DIRECT_TYPE=direct
CONSUMER_DIRECT_QUEUE=queue-notification
CONSUMER_DIRECT_EXCHANGE=direct-notification
CONSUMER_DIRECT_ROUTING_KEY=callback
CONSUMER_PAYMENTS_HOST=localhost
CONSUMER_PAYMENTS_VHOST=/
CONSUMER_PAYMENTS_LOGIN=guest
CONSUMER_PAYMENTS_PASSWORD=guest
CONSUMER_PAYMENTS_PORT=5672
CONSUMER_PAYMENTS_TYPE=direct
CONSUMER_PAYMENTS_QUEUE=queue-payment-notification
CONSUMER_PAYMENTS_EXCHANGE=x-payment-events
CONSUMER_PAYMENTS_ROUTING_KEY=callback
I think i must have 2 applications, one for each vhost. I was thinking to have the same applications, just with diferent environment configuration.
Is not what i want, but i dont know how to do, is it possible?
I tried to create 2 connections at the same time, but it didnt work, or i implemented it wrong.


text:
Q: Twitter Bootstrap modals I've been freaking out for two days with this...
I've set up a page with the Bootstrap CSS, with the following code in the page head:
<link rel="stylesheet" href="bootstrap.min.css">

In my body I have this:
<button class="btn btn-large btn-primary" data-toggle="modal" data-target="#modal-signin" data-backdrop="true" data-keyboard="true">Launch Modal</button>

        ×

Sign in or sign up

Teste

In the Bootstrap docs this is what I have to do to get this working but when I click the button it doesn't do anything...
I don't know what the problem is...
I need urgent help
Thanks.

A: jQuery will need to be included first as the twitter bootstrap depends on it.


text:
Q: Properly parse CSV file to JSON file in JavaScript I have a CSV file and I want to parse it using PapaParse.  How do I do this properly?
I have so far:
Papa.parse(fileInput, {
    download: true,
    complete: function(results) {
        console.log(results.data);
        console.log(results.errors);
    }
});

However, is there a better way to do this?  Is this the proper way to get errors?  The documentation didn't emphasize download: true or anything so I was wondering if there are any experts on this subject here.
EDIT: Also, am I suppose to further parse the file with papacsv or do it in react.  For instance, if I have multiple arrays in my data file which have a similar name reference.  Should I initially somehow parse the file so it groups all those references together and how would I go about doing this?
For instance,
Date, Name , Win/Lose
I want to group all the winners together.  How do I do that?

A: The method you are using of Papa parse, is for remote CSV.
download: true is for downloading the remote file.
By using Papa parse, this is the only way of getting errors, data, meta with parse result object.

A:

//If(header:true)
var data = [
 {
    "date": "8/12/2018",
  "name": "foo",
  "win/loose": "win"
 },
 {
    "date": "8/12/2018",
  "name": "foo",
  "win/loose": "loose"
 },
  {
    "date": "8/12/2018",
  "name": "foo1",
  "win/loose": "win"
 },
];
var winners = data.filter(d => d['win/loose'] == 'win');
console.log(winners);
//If you want to group winners and losers then:
var grouped = data.reduce(function(acc, co) {
  var key = co['win/loose'];
  if(!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(co);
  return acc;
}, {});
console.log(grouped);

This'll give you separate array of winners from extracted data.


text:
Q: Use do_upload function with hardcoded image location (Codeigniter) My problem is following. I'm writing this test data seed file. I already have all functionalities wrote (creating thumbnalins, hd, watermarking img, etc...) so now I would like just to reuse this code, but with some hardcoded image data location.
$imgToUploadLocation = "../../static/img/test.jpg";
$_FILE['userfile'] = imgToUploadLocation;

$config['upload_path'] = '/pictures/';
$config['allowed_types'] = 'jpeg|jpg';
$config['remove_spaces'] = true;
$config['max_size'] = '25000';
$config['encrypt_name'] = true;
$this->upload->initialize($config);
if ($this->upload->do_upload()) {
  echo "finaly!";
} else {
  echo "error";
}

The problem is that however i specify my image location i will always get error you did not select any image to upload.
I wonder how to use upload library without view form? If you need any additional informations please let me know and I will provide. Thank you!

A: This is not the proper way of defining. Files are expected in a certain way on the $FILES global variable to be uploaded.
In order to define the file you want to upload do:
$_FILES['userfile']['name'] = 'what name you want';
$_FILES['userfile']['tmp_name'] = $imgToUploadLocation;

Read more about the $_FILES in https://secure.php.net/manual/en/features.file-upload.post-method.php


text:
Q: Trim string to a certain word count I have a description in my template

{{data.description}}

I want to trim this description to certain word number, like to first 20 words. I have seen many filters but they trim to a certain characters. This causes the last word to break in most cases.

A: You need to split the description string into words, using spaces, then count it:
app.filter('words', function () {
  return function (input, words) {
    if (isNaN(words)) {
      return input;
    }
    if (words <= 0) {
      return '';
    }
    if (input) {
      var inputWords = input.split(/\s+/);
      if (inputWords.length > words) {
        input = inputWords.slice(0, words).join(' ') + '\u2026';
      }
    }
    return input;
  };
});

First I check if the parameter is a number, then I'm checking if the description is longer than  what we what to trim at, and then I trim the rest.
 and in the view:
{{data.description | words:250}}

A: a cleaner solution would be something like this:
{{((longStringArray = longString.split(' ')) | limitTo: wordLimit = 20).join(' ')}}
 wordLimit"> ...

this even displays ' ...' at the end, to indicate that the given string was shortened.

A: //Manish Bhardwaj
var regex = /\s+/gi;
//for count the words.
var count = (data.description).trim().replace(regex,' ').split(' ').length;
// for split all string data in array form
$scope.substr = (data.description).trim().replace(regex,' ').split(' ');
//make substring with space which is trimmed.
$scope.substr1 = $scope.substr.slice(0,20).join(' ');
$scope.substr2 = $scope.substr.slice(20,40).join(' ');
$scope.substr3 = $scope.substr.slice(40,$scope.substr.length).join(' ');


text:
Q: RDLC file DataSet and Overlapping error messages I am working on RDLC reports in asp.net.
I had one datasource for my report. It was working perfectly.
But now I changed it and assigned another datasource to it as well.
here is the code:
<rsweb:ReportViewer ID="rptAdmissionNote" runat="server" Font-Names="Verdana"
        Font-Size="8pt" Height="100%" Width="100%"
        InteractiveDeviceInfos="(Collection)" WaitMessageFont-Names="Verdana"
        WaitMessageFont-Size="14pt">
        <LocalReport ReportPath="Reports\Admission\rptAdmissionNoteReport.rdlc">
            <DataSources>
                <rsweb:ReportDataSource DataSourceId="odsAdmission" Name="DSAdmission" />
                <rsweb:ReportDataSource DataSourceId="odsInitialService" Name="DSInitialService" />
            </DataSources>
        </LocalReport>
    </rsweb:ReportViewer>

    <asp:ObjectDataSource ID="odsAdmission" runat="server"
        OldValuesParameterFormatString="original_{0}"
        SelectMethod="SelectAdmissionForReport"
        TypeName="PrecisionCareBLL.AdmissionBLL.AdmissionLogic">
        <SelectParameters>
            <asp:QueryStringParameter Name="admissionId" QueryStringField="Id"
                Type="Int32" />
        </SelectParameters>
    </asp:ObjectDataSource>

    <asp:ObjectDataSource ID="odsInitialService" runat="server"
        OldValuesParameterFormatString="original_{0}"
        SelectMethod="SelectAdmissionForReport"
        TypeName="PrecisionCareBLL.AdmissionBLL.AdmissionLogic">
        <SelectParameters>
            <asp:QueryStringParameter Name="admissionId" QueryStringField="Id"
                Type="Int32" />
        </SelectParameters>
    </asp:ObjectDataSource>

Still it worked fine and project successfully built.
But when I added another DataSet in RDLC file, I am getting these errors:
Error   27  The rectangle 'rectAdmission' and the rectangle 'rectServicePlanDue' overlap. Overlapping report items are not supported in all renderers.

And lots of such errors.
Why it was working fine previously and what happened now?
When I remove newly added dataset from RDLC file, it again works fine.
Please anyone can tell me the reason behind that?
Thank you.

A: Open the rdlc file.. Go to Report menu ->Data sources. Select the datasource which you newly added and press the Remove button then give Ok.


text:
Q: Javascript : why i have to click 2 times to run the function? window.onload = function(){
   var about2 = document.getElementById("about");
   about2.addEventListener("click",about);

}

function about(){
var divabout = document.getElementById("aboutme");
 if(divabout.style.display == "none"){
    divabout.style.display = "flex";
    divabout.style.justifyContent ="center";
 }else{
    divabout.style.display ="none";
 }
}

please tell me the reason why i have to click twice to run this function .And how to fix pls . many thanks .
i just set display:none for  1 div tag in css , and i want to change display attributes .

A: Because you haven't set any dislplay property to your HTML by default.
That's why On first click javascript sets everything it needs. then started working from 2nd click.
Here is your code, where you dind't add style in html

Hello

About Me

And Here if I fix/add this style="display:flex;justify-content: center;" in your about me like this

Hello

About Me

Now you can check you need only one click to run

window.onload = function() {
  var about2 = document.getElementById("about");
  about2.addEventListener("click", about);

}

function about() {
  var divabout = document.getElementById("aboutme");
  if (divabout.style.display == "none") {
    divabout.style.display = "flex";
    divabout.style.justifyContent = "center";

  } else {
    divabout.style.display = "none";

  }
}

Hello

OK About Me


text:
Q: grave in the Go Language After looking around for a while I was able to understand how the json: tags are used in the Go language. However two tags I have come across I'm still lost on, and can't seem to find documentation on it.
Both pertain to a REST api service and the full code can be found here-> code.google.com
What is the root: tag used for
gorest.RestService    `root:"/orders-service/" consumes:"application/json" produces:"application/json"`

as well how does the method: tag work?
userDetails gorest.EndPoint `method:"GET" path:"/users/{Id:int}" output:"User"`

I didn't know if anyone had any links to a site or document that might explain this more, from the examples I can learn enough to use it. However, I would really like to fully understand it.
Thanks for your time!

A: Tags are nothing but strings, they don't have any meaning per-se.
Libraries can use reflection to introspect struct fields and interpret their tags. See reflect.StructTag.
In your case, gorest parses the following tags on Services:

*

*root

*consumes

*produces

and these on Endpoints:

*

*realm

*method

*path

*output

*input

*role

*postdata

Their meaning is described in gorest's documentation.

A: These are gorest tags. See gorest wiki http://code.google.com/p/gorest/wiki/GettingStarted


text:
Q: Passing variable to included file in a method I could not find the answer to this problem. I have a class written in PHP. Files included within a PHP class method do not seem inherit variables within the method scope.
class Classname {
    public function template_editor (){
        $GLOBALS['template_editor'] = true;
        $editable=false;
        $GLOBALS['editing'] = false;
        $template_html =  $this->thetemplate (array('editable'=>$editable));
        include (TEMPLATE_DIR_URI."/inc/template_editor.php");
    }
}

I want the variable $template_html to be passed to the included file so that I can echo it. I have written many functions and all the variables declared in the functions are passed on to the included files but it does not work in class methods.
In the included file I currently have;
<?php echo  $template_html;  ?>

...and some html and Jquery. I want all the method variables to be availble in the included file so that I can use them in the included file.

A: From the documentation of include():

If the include occurs inside a function within the calling file, then
  all of the code contained in the called file will behave as though it
  had been defined inside that function. So, it will follow the variable
  scope of that function. An exception to this rule are magic constants
  which are evaluated by the parser before the include occurs.

Your problem is most likely that either this line isn't assigning a value to $template_html
$template_html =  $this->thetemplate (array('editable'=>$editable));

or you are referencing the variable incorrectly in template_editor.php.
Checking the value of $template_html like so may give you insight into the reason:
class Classname {
    public function template_editor (){
        $GLOBALS['template_editor'] = true;
        $editable=false;
        $GLOBALS['editing'] = false;
        $template_html =  $this->thetemplate (array('editable'=>$editable));

        // Add this for debugging
        if (is_empty($template_html)) {
            error_log('$template_html is empty.');
        }

        include (TEMPLATE_DIR_URI."/inc/template_editor.php");
    }
}


text:
Q: php7.2-gd can't find package (tried everything) I have Ubuntu 14.04 and php7.2 but can't install php7.2-gd
I need to install package php7.2-g
when i run apt-get install php7.2-gd it says that:

E: Unable to locate package php7.2-gd
  E: Couldn't find any package by regex 'php7.2-gd'

I added repository add-apt-repository ppa:ondrej/php and did apt-update
but when i use apt-cache search php7 it doesn't show me that i have php7.2-gd and of course i can't install it.
Maybe problem in ubuntu 14.04 but not sure

A: Try this:
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install php7.2-gd


text:
Q: To friend vs. to befriend I overheard a mother correct her child who said something to the effect of

There was a new kid in my class today and I friended him.

The mother said befriended and I was inclined to mentally agree (given the kid was maybe six or seven, it's unlikely that he was referring to social networking).
However, with a little Googling, I discovered an article from The Atlantic which suggests that 'Friend,' as a Verb, Is 800 Years Old.

*

*"Make no purses, for to friend yourself therewith." -- the Guide for Anchoresses, early 13th century

*"And after soon friended were the King David of Scotland and Stephen, king then of England." -- Andrew of Wyntoun, Chronicles, c. 1425

This answer regarding the be prefix offers:

The general form is:
   be + [quality]

and the corresponding meaning is:
 to turn into + [quality].

So, I guess my question, then, is what is the difference between the verbs to friend and to befriend? Was the kid right?

A: Friend as a verb is very old, but its use is now limited to adding someone to a list of social network contacts. Befriend doesn't necessarily mean 'make a friend of'. It is typically used when a person offers support to someone in difficulties, rather like the good Samaritan.
If you're describing the establishment of a close, but not sexual or romantic, relationship, you have to say that two people are, or have become, friends.


text:
Q: Finding Closest Driving Distance I have a series of functions used to calculate the closest driving distance from the target address to one of my several locations and for the most part it works well. It first gets my closest location as the crow flies, then uses that address to calculate the actual driving distance to the target address and this is where the problem is. Sometimes the as the crow flies distance is far closer to one location but closer to drive from another so how can I calculate the driving distance from the start and skip the as the crow flies calculation?
// Provides "as the crow flies" distance from my closest location to target address
function closestLocation($Address) {
    $values = locationFromAddress($Address);
    $center_lat = $values[0];
    $center_lng = $values[1];
    // My locations
    $query = sprintf("SELECT ID, Address, (3959 * acos(cos(radians('%s')) * cos(radians(lat)) * cos(radians(lng) - radians('%s')) + sin(radians('%s')) * sin( radians(lat)))) AS Distance
    FROM locations
    WHERE Address > 0 AND lat <> 0 AND lng <> 0
    ORDER BY Distance ASC
    LIMIT 1",
      $center_lat,
      $center_lng,
      $center_lat);
    $rowCat = DBConnect($query, "Select", "pchome_geoip");

    // Returns array of the location
    return $rowCat;
}

You can see that the query simply uses the latitude and longitude stored in the database to calculate it using the latitude and longitude of the target address provided by locationFromAddress() function:
function locationFromAddress($Address) {
    $Address = urlencode($Address);
    if ($Address) :
        $geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$Address&sensor=false");
        $output = json_decode($geocode);
        $lat = $output->results[0]->geometry->location->lat;
        $long = $output->results[0]->geometry->location->lng;
        return array($lat,$long);
    else:
        return "";
  endif;
}

And then the details are used to calculate the driving distance using the Google API:
function compareDistance($unit,$inLatitude,$inLongitude,$outLatitude,$outLongitude) {
    $url = "http://maps.googleapis.com/maps/api/directions/json?origin=$inLatitude,$inLongitude&destination=$outLatitude,$outLongitude&sensor=false";

    // Retrieve the URL contents
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_URL, $url);
    $jsonResponse = curl_exec($c);
    curl_close($c);

    $dataset = json_decode($jsonResponse);
    if(!$dataset)
        return 0;
    if(!isset($dataset->routes[0]->legs[0]->distance->value))
        return 0;
    $miles = ($dataset->routes[0]->legs[0]->distance->value * .00062);
    // Google API returns meters, multiplied by .00062 to get miles

    // Round up to nearest unit
    if ($unit == "K") :
        return ceil($miles * 1.609344);
    elseif ($unit == "N") :
        return ceil($miles * 0.8684);
    else :
        return ceil($miles);
    endif;
}

function getDrivingDistance($myAddress, $custAddress, $unit) {
    // 'M' is statute miles
    // 'K' is kilometers
    // 'N' is nautical miles
    // Get accurate latitude and longitude based on actual location
    $myValues = locationFromAddress($myAddress);
    $myLat = $myValues[0];
    $myLng = $myValues[1];

    $custValues = locationFromAddress($custAddress);
    $custLat = $custValues[0];
    $custLng = $custValues[1];

    // Returns actual driving distance
    return compareDistance($unit,$myLat,$myLng,$custLat,$custLng);
}

Also, is there an API parameter for closest rather than fastest route?

A: I reworked this function and entirely eliminated closestLocation() and another function so it does simplify things a bit. I'll need to rearranged a few of the other areas of where this is being called but it does seem to be pulling out a valid driving distance although sometimes it's the fastest, not the closest. Is there a switch for the Google API for closest?
function getDrivingDistance($Address,$unit="M") {
    if ($Address) :
        $values = locationFromAddress($Address);
        $inLatitude = $values[0];
        $inLongitude = $values[1];

        // Fetch all of my locations
        $sqlLocation = "SELECT ID, Address, lat, lng
                        FROM locations";
        $rowLocation = DBConnect($sqlLocation, "Multiple", "pchome_geoip");

        // Create array of driving distances based on latidude and longitude
        foreach ($rowLocation as $key) :
            $outLatitude = $key['lat'];
            $outLongitude = $key['lng'];
            $output[] = compareDistance($inLatitude,$inLongitude,$outLatitude,$outLongitude,$unit);
        endforeach;

        //sort($output, SORT_NUMERIC);
        if (array_sum($output) > 0) :
            return min(array_diff($output,array(0)));
        else :
            return 0;
        endif;
    endif;
}


text:
Q: Creating random Bool in Swift I'm needing to create a random bool value in my game, in Swift.
It's basically, if Yes (or 1), spawn one object, if No (or 0), spawn the other.
So far, looking at this question and a similar one on here, I found this:
let randomSequenceNumber = Int(arc4random_uniform(2))

Now it works, but it seems bias to 0 to me... like ridiculously bias...
This is how I'm then using the value:
if(randomSequenceNumber == 0)
    //spawn object A
else
    //spawn object B

Is there a better way to implement this using a random bool value? That isn't bias to a certain value?
Update
Bit of an experiment to see how many 1's vs 0's were were generated in 10,000 calls:
func experiment() {
    var numbers: [Int] = []
    var tester: Int = 0
    var sum = 0

    for i in 0...10000 {
        tester = Int(arc4random_uniform(2))
        numbers.append(tester)
        print(i)
    }

    for number in numbers {
        sum += number
    }

    print("Total 1's: ", sum)
}

Test 1: Console Output: Total 1's: 4936
Test 2: Console Output: Total 1's: 4994
Test 3: Console Output: Total 1's: 4995

A: Xcode 10 with Swift 4.2
Looks like Apple  engineers are listening
let randomBool = Bool.random()

A: import Foundation

func randomBool() -> Bool {
    return arc4random_uniform(2) == 0
}

for i in 0...10 {
    print(randomBool())
}

for more advanced generator the theory is available here
for basic understanding of Bernoulli (or binomial) distribution check here

A: extension Bool {
    static func random() -> Bool {
        return arc4random_uniform(2) == 0
    }
}

// usage:
Bool.random()


text:
Q: How to create an if else condition with ArcGIS Javascript API for slider and imageLayers from switch statement The code below is the switch statement that I am currently using.  I can't seem to get the values (case) to match up with the horizontal slider I am using (4 unique values-each layer).  I was thinking of trying an if else condition instead.  Anyone have the best way to accomplish this?
function setPixelFilter() {
        var val = slider.get("value");
        switch (val) {
          case 0:
            var imageLayer = new ArcGISImageServiceLayer("https://...ImageServer")
            map.addLayer(imageLayer)
            break;
          case 100/3:
            var imageLayer = new ArcGISImageServiceLayer("https://...ImageServer")
            map.addLayer(imageLayer)
            break;
          case 100/3*2:
            var imageLayer = new ArcGISImageServiceLayer("https://...ImageServer")
            map.addLayer(imageLayer)
            break;
          case 100:
            var imageLayer = new ArcGISImageServiceLayer("https://...ImageServer")
            map.addLayer(imageLayer)
            break;


text:
Q: StructureDefinition post request return 404 error I have just done the local setup of hapi fhir in my machine.
And I can able to reach the fhir metadata http://localhost:8888/fhir/metadata but when I try to post any structure Definition using this url(http://localhost:8888/StructureDefinition) its returning "Error 404 Not Found".
This is the error from local setup:
2021-03-01 13:12:20.441 [qtp1256142210-23] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /StructureDefinition
2021-03-01 13:12:20.446 [qtp1256142210-23] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /error
2021-03-01 13:12:40.279 [qtp1256142210-19] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /StructureDefinition
2021-03-01 13:12:40.280 [qtp1256142210-19] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /error
2021-03-01 13:12:45.532 [qtp1256142210-23] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /StructureDefinition
2021-03-01 13:12:45.533 [qtp1256142210-23] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /error
2021-03-01 13:13:03.615 [qtp1256142210-19] WARN  o.s.web.servlet.PageNotFound [DispatcherServlet.java:1271] No mapping for POST /StructureDefinition

What is the issue? Please help me to resolve this problem.

A: Found the answer for my question below,
I should include /fhir like this http://localhost:8888/fhir/StructureDefinition.
And it is working now.


text:
Q: Layered painting on java? I am basically trying to do something like classic "Paint" (Microsoft's program). But i want to work with layers when painting. I thought i can use JPanel component as layer.
I was testing the code below. The goal is drawing a rectangle with mouse. There is a temp layer (temp) to draw on it while dragging the mouse, and there is actual layer (area) to draw when mouse released. But every time i start drawing a new rectangle, old ones are disappear. Also if i execute setVisible(false) and true again, everything disappears.
MouseInputAdapter mia = new MouseInputAdapter() {
    private int startx = 0, starty = 0, stopx = 0, stopy = 0;

    public void mousePressed(MouseEvent evt) {
        startx = evt.getX();
        starty = evt.getY();
    }

    public void mouseDragged(MouseEvent evt) {
        Graphics2D tempg = (Graphics2D) temp.getGraphics();

        int width = Math.abs(startx - evt.getX());
        int height = Math.abs(starty - evt.getY());
        int x = evt.getX(), y = evt.getY();
        if(x > startx)
            x = startx;
        if(y > starty)
            y = starty;

        Rectangle r = new Rectangle(x, y, width, height);
        tempg.clearRect(0, 0, getWidth(), getHeight());
        tempg.draw(r);
    }

    public void mouseReleased(MouseEvent evt) {
        Graphics2D g = (Graphics2D) area.getGraphics();
        stopx = evt.getX();
        stopy = evt.getY();

        int width = Math.abs(startx - stopx);
        int height = Math.abs(starty - stopy);
        int x = startx, y = starty;
        if(x > stopx)
            x = stopx;
        if(y > stopy)
            y = stopy;

        Rectangle r = new Rectangle(x, y, width, height);
        g.draw(r);
    }
};
area.addMouseListener(mia);
area.addMouseMotionListener(mia);
temp.addMouseListener(mia);
temp.addMouseMotionListener(mia);

What is wrong with that code?

A: Every time there's a repaint there's no guarantee you'll get the same graphics in the state you left it.
Two a two-step instead:

*

*Create a List of Rectangles in your class.

*In your mouse listener instead of drawing to the graphics, add a rectangle to the list.

*Override paintComponent and in there draw the list of rectangles to the graphics it is passed.

Using the list is nice as items at the start of the list will be painted below ones at the end.

A: Classic bitmap-based graphics painting software operates on a target bitmap. You can render multiple Layers in paintComponent(), as @Keily suggests for Rectangles.
Alternatively, you may want to to look at classic object-based drawing software, outlined here.

A: Here's a general idea: (I'm assuming you mean layers such as in photoshop)
Set up a single JPanel for drawing.
Make a data structure containing all drawable objects you need for drawing.
In this data structure, also make a field containing an integer expressing which layer that specific drawable object is tied to.
In your paintComponent() method, check which layer is currently active and only draw the the data in that layer or below it.

A: This is what i was looking for; http://www.leepoint.net/notes-java/examples/mouse/paintdemo.html
My mistake; using getGraphics() method out of paintComponent() and expecting keep changes.
Why @Keilly's answer not working for me; Because if i put shapes in a list or array, when a shape changed (for example; deleting a circle's 1/4) i can't update the element in the list. Because it doesn't be same shape anymore. So i have to keep shapes as drawings, and i don't have to (and dont want to) keep them separately.


text:
Q: Segmentation Fault for large arrays defined in a class I am trying to program a 3-D vector field in a 2-D surface.
I defined a class for it, along with several functions.
Everything works fine as long as Lx*Ly stays under a certain value.
If I try to define a larger array it gives me a segmentation fault.
This is the very simple code:
class CampVec{

public:
    double R[Lx][Ly][3]; //this makes space for the 3 components of the vector
                         //for each point in a Lx*Ly grid.
};

From what I understand, the problem is the CampVec objects are stored in the stack instead of the heap, but I haven't been able to find how to fix this when the definitions are inside a class.
I bet this isn't really complicated, so sorry if this is a stupid question, I sincerely have searched and tried several things to no avail.
Best wishes and thank you.

A: Why do you want to do it on the stack?
The internals of a vector are taken from the heap and can be cast to look like your array:
#include <vector>
class CampVec{
    std::vector<double> _R;
public:
    typedef double __AT[Lx][Ly][3];
    __AT &R;
    CampVec():_R(Lx*Ly*3),R( reinterpret_cast<__AT&>(&_R[0]) ){} // ctor
};

You could also try to find what compiler options your compiler uses to increase the stack size, but why does it have to be on a stack?


text:
Q: SQL Server, Restore Latest Differential We have a development server that has a job that runs overnight which restores backed up databases.  Our primary database server backs up the databases overnight and our development server then restores these databases to keep them up-to-date with one another on a daily basis (not transactional basis).
As our databases are pushing many gigabytes in size we now face the problem that restores take many hours overnight.  Instead we're wanting to push out the use of differential database backups and restores.
The problem I have is that the development server does a restore, but how can I tell which file to pick out in the differential backup? You have to specify a file i.e. FILE = 9 in the restore statement, but what if I don't know which file it is? What if I just want the latest one?
So how do you specify the latest file from a differential database backup?
http://msdn.microsoft.com/en-us/library/ms186858.aspx
Cheers

A: There are a couple of different options for automating this using a stored procedure / TSQL or a powershell script (I'd recommend the powershell script). If you want to write your own automation for doing this, you'll basically want to look into the "restore filelist only" statement which will give you a listing of all files in a given backup set (and in this case figure out which filenumber is the most recent diff backup for the full backup you have).
Note that if you want to restore the differential, you'll have to have restored the most recent FULL backup that is associated with the given DIFF backup as well in order for this to work, or potentially have left the restored dev database in a recoverable state.
For example, this would work:

*

*Restore full backup from Sunday on DEV

*Restore diff backup from Monday on DEV

this would work as well:

*

*Restore full backup from Sunday on DEV

*Restore diff backup from Tuesday or Wednesday or Thursday on DEV

however, this will not work:

*

*Restore full backup from Sunday on DEV

*Take full backup on Monday on PROD

*Restore diff backup from Tuesday on DEV

In this final case, you'd also have to restore the full backup from Monday on DEV before restoring the Diff backup from Tuesday would be allowed. There are exceptions (for example if the full backup on Monday was a COPY_ONLY backup and didn't break the diff backup chain). See this article for more details on using DIFF backups and the restore chain required for use.

A: You should be able to get the record of the latest differential backup and the path to it out of the msdb backup tables. But as noted above, if you want to restore a diff, you'll have to restore the full first. At this point, you're probably better off reconsidering a different solution like log shipping or snapshot replication, or reconsidering the requirements.


text:
Q: java poker card arrays I have been going crazy on this program im writing. My decks dont seem to work and I have hunted for every tidbit of information but after 8 hours straight it still does not work =( Please help on pointing out where i need to work on better or how to go about coding it better.
package poker;

public class Deck {

private Card[] cards;

// deck constructor with initial array
public Deck() {
    Card[] x= new Card[52];
    int index = 0;
    for (int suit = 0; suit < 3; suit++) {
        for (int value = 1; value < 13; value++) {
            cards[index] = new Card(value, suit);
            index++;

        }

    }
}

// copy constructor with a shallow copy of the array
public Deck(Deck other) {
    Card[] c = new Card[52];

    int index = 0;
    for (int suit = 0; suit <= 3; suit++) {
        for (int value = 1; value <= 13; value++) {
            cards[index] = new Card(suit, value);
            index++;
        }

    }
}

// method for cards in any position
public Card getCardAt(int position) {
    if (position >= cards.length) {
        throw new IndexOutOfBoundsException("Values are out of bounds");
    } else {
        return cards[position];
    }
}

// number of cards left after each draw
public int getNumCards() {

    return cards.length;
}

// Randomized rearrangement of cards

//have no idea to go about this any further
public void shuffle() {
    int temp=0;
    for (int row=0;row<cards.length;row++){
        int random = (int)(Math.random()*((cards.length-row)+1));
    Deck.this.cards[temp]= this.getCardAt(row);
    cards[row]=cards[random];
    cards[random]=cards[temp];
    }
}
    //cutting of the cards
public void cut(int position) {
    //int temp = this.cards
}

// something to think about on dealing from taking the differences in
// dealing the cards
public Card[] deal(int numCards) {
    /* numCards = 5;
    for (int i = 0; i < numCards; i++) {

        numCards = cards.length - numCards;
    }
    return deal(numCards);*/
     {
             numCards = this.getNumCards();
            numCards ++;

            return deal(5);
        }

}

}

I tried to Junit test but i seem to suck at them but i tried
package poker;

import junit.framework.TestCase;

public class StudentTests extends TestCase {
public void testDeck() {
    int value=0;
    int suit = 0;
    Card[] x = new Card[52];
    //Card = new Card(getValue(), getSuit());

    assertTrue(getValue() == 1 && getSuit() == value);
    assertTrue(getValue() == 1 && getSuit() == suit);
    ;
}
public void testCopyConstructor(){

        int value = 0;
        int suit = 0;
        Card[] sc = new Card[52];
        //Card = new Card(getValue(), getSuit());

        assertTrue(getValue() == 1 && getSuit() == 0);

}
/* public void testShuffle()
   {
     Card[] sc = new Card[52];
     Card[] sc2 = new Card[52];
      assertTrue(sc==(sc2));
       //shuffle method
      assertFalse(sc==(sc2));

      //another shuffle method here
      //i have no idea

      assertFalse(sc==(sc2));} */

private int getValue() {
    // TODO Auto-generated method stub
    return 1;
}

private int getSuit() {
    // TODO Auto-generated method stub
    return 0;
}
}

A: Your default constructor for Deck makes a deck of 36 cards, not 52.  Start by fixing that.

A: In your Deck constructor, initialize your cards member array as follows:
public Deck()
{
   cards = new Card[52];

   int index = 0;

   for (int suit = 0; suit <= 3; suit++)
   {
      for (int value = 1; value <= 13; value++)
      {
         cards[index] = new Card(value, suit);
         index++;
      }
   }
}

Also, your Deck copy constructor doesn't do any actual copying.

A: From your default constructor:
cards[index] = new Card(value, suit);

From your copy constructor:
cards[index] = new Card(suit, value);

Order matters in Java; you can't expect the compiler to know what the suit means and what the value means just by variable names.
Also, inside deal(int numCards), you call deal(5). That's going to keep calling itself over and over again forever until the computer runs out of memory. (This is called recursion, and it's very tricky to use correctly. You shouldn't need to use it at all.)
That's in addition to the valid points made by other answerers.


text:
Q: Saving application settings in a SharePoint application best practices What are the best practices for saving application settings in a Sharepoint application?
Would anyone save the settings in the web.config's appsettings?
What about saving them in a SharePoint list?
Any other ideas? pros? cons?

A: As is often the case when developing with SharePoint, the answer is really "it depends"!
If you are configurating webparts, often the best way to configure them are using custom properties and either use UI or .webpart xml file to configure them.
If we are talking connection strings for InfoPath, theres data connection libraries
Connection strings could be stored in web.config connectionstring settings, but could also be stored in the property bag for a site or a list: SPPropertyBag.
For features you can store properties in the feature xml. Example here.
For timerjobs you can store it in the object itself, since it per definition is a persisted object and hence stored in the persisted configuration cache. See an example here and here how to store this kind of data.
As you can see it is not easy to give one general answer to your question :-)

A: I'm not remotely biased of course, but I think my Config Store solution is a good option (based on storing config values in a list). In addition to what I list on the codeplex site, there are some later enhancements such as allowing hierarchical config and providing an expression builder for use in ASPX markup, so it has a lot of features which can be useful. It's unlikely to be the right choice for every scenario, but if a list seems like the right approach it should be a much better starting point than nothing due to things like the caching layer.
Suggest also checking out Microsoft's SharePoint Patterns & Practices Guidance on this - in the PDF they have a good table comparing some options (they also mention my Config Store solution, but I promise that's not the only reason I think it's good info!)

A: I would recommend you take a look at Chris O'Brien's SharePoint Config Store:
http://www.codeplex.com/SPConfigStore

A: Generally, my "rule-of-thumb" is that if it is "application (site) specific" then store it in a list.  If it is something that needs to be "tuned" by an administrator rarely and applies to multiple "applications" then store it in the "web.config".
One thing, if you do store settings in a list - ensure versioning is turned on - I just had a situation where a vendor was blaming my team for making changes - we did not, heck at the time we did not even know their settings were stored in a list.

A: Here is a list that I compiled with six different ways (and a few alternatives in the discussions).
Six ways to store settings in SharePoint


text:
Q: GLSL gl_FragDepth equivalent in Metal shaders I'm looking to adjust a fragments depth in a Metal shader. Previously I was achieving this via GLSL's built-in output variable gl_FragDepth. Is there an equivalent approach using Apple's Metal shaders on iOS?

A: Yes, you specify this with the depth attribute on a member of the struct you return from your fragment shader. For example, you'd create a type such as:
struct FragmentOut {
    half4 color [[color(0)]];
    float depth [[depth(any)]];
};

Then, in your fragment function, create an instance of this struct, populate, and return it:
fragment FragmentOut my_frag_function(...) {
    FragmentOut out;
    out.color = // compute fragment color (for first color attachment)
    out.depth = // compute fragment depth
    return out;
}

Note that rather than any, you can specify one of greater or less as the depth attribute argument, which indicates that the fragment depth you provide will be, respectively, greater than or less than the interpolated fragment depth. The semantics of these specifiers match those of the same name in OpenGL, and you should use them when possible for optimization purposes.


text:
Q: Why can't Jackson deserialize single field class with RequiredArgsConstructor? If I have a class using Lombok:
@RequiredArgsConstructor
@Getter
class Example {
  private final String id;
}

And try to deserialize it from
{
  "id": "test"
}

Jackson throws an exception that although at least one creator was provided, it could not deserialize.
If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.
Does anyone know what's going on here? Why are you unable to deserialize if you only have one field?

A: When only way to intialize object properties is through contructor, Jackson needs to be told that deserialization should happen using constructor via @JsonCreator annotation.
Also, all the property names should be provided via @JsonProperty annotation because Jackson needs to know the sequence of attributes passed in contructor to correctly map json values to Java object attributes.
So, if you are not using lombok contructor, then constructor will look like
    @JsonCreator
    public Example (@JsonProperty("id") String id) {
        this.id = id;
    }

If you don't want to manually write the contructor, go ahead with @tashkhisi's answer.
Also, I highly doubt following could happen. Could you update the question with code showing this?

If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.


text:
Q: Manipulate binding attribute in Angular 2 with jQuery I have an element that has attribute binding like this:

Am I able to detect the changes of url if I use some jQuery code to manipulate that attribute, something like:
$('#myDiv').attr('data-url', 'example.com');
I have looked at some other questions but there is no answer that I'm looking for.
PS: If I change data-url attribute with jQuery, url variable will change accordingly, or not? If not, does that mean we cannot be able to change [attr.data-url] after all? I'm so confused right now.


text:
Q: Cannot Create instance of the Abstract Class or Interface 'system.xml.XmlWriter' Guys i am Having trouble with Advance OOP and design patterns also in Xmlserialization
this would be my code:
    public void Send(Message message, string recipient)
    {
        XmlSerializer ser = new XmlSerializer(typeof(XmlNode));
        XmlWriter writer = new XmlWriter(Messenger.outbox + message.Recipient);
        ser.Serialize(writer, message);
        writer.Close();
    }

A: You can't instantiate an abstract class, you are looking for XmlWriter.Create method.

Creates a new XmlWriter instance using the specified filename.

A: You can't directly create a new XmlWriter, instead you use the XmlWriter static class to create a writer instance.
Given a class Message:
public class Message
{
    public string Outbox { get; set; }
    public string Recipient { get; set; }
}

You could serialize it like this:
XmlSerializer ser = new XmlSerializer(typeof(Message));
using (StringWriter sww = new StringWriter())
{
    using (XmlWriter writer = XmlWriter.Create(sww))
    {
        ser.Serialize(writer, new Message() { Outbox = "onething", Recipient = "another thing" });
        var xml = sww.ToString();
    }
}


text:
Q: Copy image URL and paste in form on separate page I have two pages. One is a page with a text input where you can type the url for a profile image.
There is a button next to this text are where it opens another page.
This second page you can upload images. I want to be able to click an image on this second page, have it copy the URL, close the window, and paste the URL into the input form from the first page.
Here is the code from the first page:

    Logo URL
    <input type="text" class="form-control" value= "{{ $affiliate->logo_url }}" name="logo_url" required>
    <button class="button" onClick="window.open('{{route('affiliate.logo')}}'); return false;">
    Open
    </button>

This successfully opens the second page.
Here I list the images uploaded with the ability to click on them.
foreach($imagelist as $image)
            {
                $url = Storage::disk('s3')->url('').$image['name'];
                echo '

';
            }

Here I am able to take the url of the image and put it into the variable 'url':

Console.log(url) shows that the url is coming through properly, but I have no idea how to send it back to the first page and insert it into the text input.
Any help is appreciated! Thanks!

A: You can save the url in localStorage
localStorage.setItem("imgName", "url");

and then on the other page check if it exists
if (localStorage.getItem("imgName")) {
  console.log(localStorage.getItem("imgName"));
}

once done, remove your localStorage Item
localStorage.removeItem("imgName");

But If you are opening a pop up for image selection and your main page is still open  you can use window.postMessage
here is a good example from davidwalsh website
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain +
'/windowPostMessageListener.html','myWindow');

//periodical message sender
setInterval(function(){
    var message = 'Hello!  The time is: ' + (new Date().getTime());
    console.log('blog.local:  sending message:  ' + message);
    myPopup.postMessage(message,domain); //send the message and target URI
},6000);

//listen to holla back
window.addEventListener('message',function(event) {
    if(event.origin !== 'http://scriptandstyle.com') return;
    console.log('received response:  ',event.data);
},false);

A: In the popup window I simply changed the script to this:
parentform = name of form on parent window
logo_url is the name of the input in the form


text:
Q: VM endpoint is not invoked The payload doesn't get routed to the Global outbound queue jms://orders-queue. It is commented out in the flow.  However, when I use the flow-ref=process-orders the message gets dispatched to the process-orders flow. Why does dispatching throught the vm not work?
    <vm:endpoint name="orders-queue" path="email.orders.in" exchange-       pattern="one-way" doc:name="VM"/>

         <vm:endpoint name="events-queue" path="email.orders.in" exchange-pattern="one-way" doc:name="VM"/>

<flow name="order-flow" processingStrategy="synchronous">
        <vm:inbound-endpoint exchange-pattern="one-way" path="order-process.queue1" doc:name="VM" />
    <!--<vm:outbound-endpoint exchange-pattern="one-way" ref="email.orders.in" doc:name="VM"/>-->
    <flow-ref name="process-orders" />
              <catch-exception-strategy doc:name="Processing Exception">
        <logger
            message="Error  during  flow - #[message] :: ExceptionSummary::= #[exception.summaryMessage]"
            level="ERROR" doc:name="Logger" />
    </catch-exception-strategy>
</flow>

<flow name="process-orders" processingStrategy="synchronous">
    <vm:inbound-endpoint exchange-pattern="one-way" ref="email.orders.in" doc:name="VM"/>
    <custom-transformer class="com.sw.CustomTransformer" doc:name="Java"/>

    <logger message="Received Order : #[payload]" level="DEBUG" doc:name="Logger"/>
        <foreach collection="#[message.payload]" doc:name="For Each"
            rootMessageVariableName="Original">
            <flow-ref name="process.order" doc:name="Flow Reference"/>
        </foreach>
</flow>

<sub-flow name="process.order">
    <processor-chain doc:name="Processor Chain" name="Event_Process_Queueing">
        <jms:outbound-endpoint queue="per.order.queue"
            connector-ref="jmsConnector" doc:name="JMS - Send to Processing Queue"/>
    <test:component/>
    </processor-chain>
   </sub-flow>

A: There are few mistakes in your config :-
First process.order is not a flow but a sub-flow and you cannot keep a inbound VM endpoint in a sub-flow to call it.
So,inorder to route the payload through the Global VM queue which you configured email.orders.in you can follow the follow config example:-
    <vm:endpoint name="orders-queue" path="email.orders.in" exchange-pattern="one-way" doc:name="VM"/>
    <http:listener-config name="HTTP_Listener_Configuration2" host="localhost" port="8081"  doc:name="HTTP Listener Configuration" />

    <flow name="Flow">
        <http:listener config-ref="HTTP_Listener_Configuration2" path="/test" doc:name="HTTP"/>
        <set-payload value="Test payload" doc:name="Set Payload"/>
        <vm:outbound-endpoint exchange-pattern="one-way" ref="orders-queue" doc:name="VM"/>
    </flow>

    <flow name="Flow2">
        <vm:inbound-endpoint exchange-pattern="one-way" ref="orders-queue"  doc:name="VM"/>
      <logger message="Received Message in Processing Queue : #[payload]" level="INFO" doc:name="Logger" />
    </flow>

UPDATE:-
As per your comment below, you are making major mistake in referring your VM inbound and outbound endpoint with Global VM connector.
It should be as follows:-
 <vm:outbound-endpoint exchange-pattern="one-way" ref="events-queue" doc:name="VM"/>

and
 <vm:inbound-endpoint exchange-pattern="one-way" ref="events-queue" doc:name="VM"/>

You are referring ref="email.orders.in" which is wrong and should be ref="events-queue" as mentioned above with the name of Global VM connector


text:
Q: scanf and printf just skips after 1st time what is the problem here? scanf doesnt seems to working in while loop. i was trying to find out vowel & consonent until user wants.
Here's the code:
#include <stdio.h>
main()
{
    char x,c;
    do
    {
        printf("enter\n");
        scanf("%c",&x);
        if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
            printf("vowel\n");
        else
            printf("consonent\n");

        printf("do u want to continue ?(y/n)\n");
        scanf("%d",&c);
        if(c=='n')
            printf("thnks\n");

    } while(c=='y');
    return 0;
}

A: You are trying to read a character using %d which is wrong. Use %c instead.

A: Change code to scanf("%c",&c) your original code is getting the y/n entries as digits not characters
Edit:
Probably you are getting the carage return instead of the character try using getc or fgets instead and get the first character.

A: I think the problem might be here:
        scanf("%d",&c);
It should be:
    scanf("%c",&c);

A: Here is the Correct code:
#include <stdio.h>

int main()
{
    char x,c;
    do
    {
        printf("enter\n");
        scanf("%c",&x);
        getchar(); //to remove the \n from the buffer
        if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
            printf("vowel\n");
        else
            printf("consonent\n");
        printf("do u want to continue ?(y/n)\n");
        scanf("%c",&c); //Here you were using %d instead of %c
        getchar(); //to remove the \n from the buffer

        if(c=='n')
            printf("thnks\n");
    }while(c=='y');

    return 0;
}

A: Both scanfs should be changed like this:
scanf(" %c",&x);

...
scanf(" %c",&c);

Note the space before the %, it's important: it consumes leading whitespace, which includes the endline characters left over in stdin after processing the input.

A: Please try with this code to run the loop multiple times.
EDIT: Different solution without fflush(stdin). Please define a string of 8 characters as
char str[8];

and modify the code in the loop as
fgets(str, 8, stdin); // To read the newline character
printf("do u want to continue ?(y/n)\n");

scanf("%c",&c);
fgets(str, 8, stdin); // To read the newline character


text:
Q: Real differentiability of $f\circ g$ Let $A\subset\mathbb{R}^n, B\subset\mathbb{R}^m$ and $C\subset\mathbb{R}^k$ be open subsets, $f:A\to B$, $g:B\to C$ such that $f$ is $C^{\infty}$ and surjective and $g\circ f:A\to C$ is $C^{\infty}$. Does it follow that $g$ is $C^{\infty}$?
Intuitively, I think it's true, but I'm having trouble formalizing it, since I would have to show that each partial derivative of $g$ exists, which looks complicated.

A: No, it fails even when all dimensions are 1: for example, consider $f(x) = x^3$, $g(x) = x^{1/3}$.