text:
Q: Arithmetic problem: forward declaration and always returning zero after division Problem Statement
I'm trying to write a util function to help me calculate time elapsed between two moments, and this function is put into a seperate util.c file.
However, whenever I try to access the arithmetic calculation through external function call, the result is always zero. And the code looks like this:
double timing(struct timeval before, struct timeval after){
     struct timeval result;
     timersub(&after, &before, &result);
     double res = (double) result.tv_sec + ((double)result.tv_usec)/1e6;
     return res;
}

I try to call timing in my main function
gettimeofday(&before,NULL);
usleep(some seconds);
gettimeofday(&after,NULL);
double salad_time = timing(before, after);
printf("THE TIME used for a salad is %f \n",salad_time);

Now the weird thing is that:
If I simply do this, the final printf would always give me a 0.000000 as result.
As timing is defined in another util.h file and has its function code written in util.c, I simply include util.h and try to use it in my main function.
My Research
I found many posts talking about similar problems, where performing divisions give zero as result, and the reasons were that people used integer division, and the results were somehow rounded and gave zero. Therefore, I added some type double conversion in my timing function, when I'm performing the arithmetic operation, as you can see.  But this does not help.
My Tentative Solution
The interesting part happened when I put a forward declaration of function timing on top of my main function, and the whole thing just worked, and the calculation result is being correctly shown!
The edition looks like, on top of the main function:
double timing(struct timeval before, struct timeval after);
int main(int argc, char ** argv){ ... }

What is this happening? What am I doing wrong?

A: In ANSI C it is possible to call a function that has no prototype. Compiler will assume the return value is 'int'.
To be more precise, the compiler will assume that the prototype is:
int foo();

This may explain why return value of zero is observed.
Anyway, returning double from a function of incompatible type is undefined behaviour.


text:
Q: Expected minimum number of transpositions to sort permutation For a permutation $\pi$, let $S(\pi$) be the minimum number of transpositions required to sort the elements in increasing order.
Show that for a random permutation $\pi \in S_{10001}$ $E[S(\pi)] ≥ 5000$, and
deduce that $P(S(\pi) ≤ 4500) < 1/20$.
By using the probability space suggested in the answer to this question: https://mathoverflow.net/questions/120163/concentration-bounds-for-sums-of-random-variables-of-permutations it can be easily seen that the random variable S is 2-Lipschitz. If $E[S(\pi)] ≥ 5000$ then $P(S(\pi) ≤ 4500) < 1/20$ follows immediately by using the Azuma-Hoeffding inequality.
My question is: How can I show that $E[S(\pi)] ≥ 5000$?

A: You can partition a permutation into cycles. For example, the permutation
$\begin{pmatrix} 1 & 2 & 3 & 4 & 5 \\ 5 & 1 & 3 & 4 & 2\end{pmatrix}$
has cycles $(5, 2, 1)$, $(3)$ and $(4)$.
Now let's do a transposition. When swapping two elements that belong to the same cycle, the cycle is split into two smaller cycles. When swapping two elements that belong to different cycles, the two cycles merge into one cycle.
Let $n$ be the number of elements and $c$ be the number of cycles in the permutation. As soon as we have $n$ cycles, the permutation is sorted. So we need $n$ - $c$ transpositions.
The expected number of cycles in a permutation is $H_n$, the $n$-th harmonic number. This makes the expected minimum number of transpositions to sort a permutation equal to $n - H_n$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Speed up python code - can I vectorize double for loop? I am new to python. I am using dbscan code for clustering purpose with some changes.Now code is running fine but its very slow. So I found out that I have to remove 'for loop' from my code.Here is a part of the code:
class Point:
    def __init__(self, x = 0, y = 0, visited = False, isnoise = False):
        self.x = x
        self.y = y
        self.visited = False
        self.isnoise = False

    def show(self):
        return self.x, self.y

    def dist(self, p1, p2):
        #Calculate the great circle distance between two points on the earth (specified in decimal degrees)return distance between two point
        # convert decimal degrees to radians
        dlat = radians(p2.x-p1.x)
        dlon = radians(p2.y-p1.y)
        a = sin(dlat/2) * sin(dlat/2) + cos(radians(p1.x))* cos(radians(p2.x)) * sin(dlon/2) * sin(dlon/2)
        c = 2 * atan2(sqrt(a), sqrt(1-a))
        d = 6371 * c
        return d

    def distanceQuery(self,neighbor_pts):
        dista=[]
        for i in range(len(neighbor_pts)):
          for j in range(i+1,len(neighbor_pts)):
            z=self.dist(neighbor_pts[i],neighbor_pts[j])
            dista.append(z)
        return max(dista)

distanceQuery function is using double for loop. Is there any way I can remove this? Can I vectorize this double for loop? As this is clustering code there are some steps which require appending. I have read that numpy array work different than python list when it comes to appending. Appending numpy arrays is inefficient.
Edit:
So this can be vectorize. But here is other part of code where appending is happening just after that I check for certain condition.
def expandCluster(self, P, neighbor_points):
     self.cluster[self.cluster_inx].append(P)
     iterator = iter(neighbor_points)
     while True:
       try:
         npoint_tmp = iterator.next()
       except StopIteration:
         # StopIteration exception is raised after last element
         break
       if (not npoint_tmp.visited):
         #for each point P' in NeighborPts
         npoint_tmp.visited = True
         NeighborPts_ = self.regionQuery(npoint_tmp)
         if (len(NeighborPts_) >= self.MinPts):
           for j in range(len(NeighborPts_)):
            neighbor_points.append(NeighborPts_[j])
            if self.distanceQuery(neighbor_points)>0.10:
              break

Now if I vectorize neighbor_points also. I will have to tackle the problem of appending? So each point will append into neighbour_points and then it will make a distanceQuery . And this process is also part of a iteration. So kind of two loops are here also.I just want to make sure that appending in numpy array wont be inefficient

A: import numpy as np

def dist(p1, p2):
    # Initially, p1.shape() == (n, 2) and p2.shape() == (m, 2)
    # Now, p1.shape() == (1, n, 2) and p2.shape() == (m, 1, 2)
    p1 = p1[np.newaxis, :, :]
    p2 = p2[:, np.newaxis, :]

    # get all the vectory things
    from numpy import sin, cos, radians, sqrt, arctan2 as atan2

    # do the same math as before, but use `p[..., 0]` instead of `p.x` etc
    dlat = radians(p2[..., 0] - p1[..., 0])
    dlon = radians(p2[..., 1] - p1[..., 1])
    a = sin(dlat/2) * sin(dlat/2) + cos(p1[..., 0])*cos(p2[..., 0]) * sin(dlon/2) * sin(dlon/2)
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    d = 6371 * c
    return d

def distanceQuery(neighbor_pts):
    return np.max(dist(neighbor_pts, neighbor_pts))

e.g:
>>> points = np.array([[0, 0], [45, 0], [45, 45], [90, 0]], dtype=float)
>>> dist(points, points)
array([[     0.        ,   5003.77169901,   6272.52596983,  10007.54339801],
       [  5003.77169901,      0.        ,   2579.12525679,   5003.77169901],
       [  6272.52596983,   2579.12525679,      0.        ,   4347.69702221],
       [ 10007.54339801,   5003.77169901,   4347.69702221,      0.        ]])
>>> np.max(_)
10007.543398010286

Timing:
def dist_slow(p1, p2):
    """your function, adjusted to take an array instead of a `Point`"""
    from math import radians, cos, sqrt, atan2
    # compute the distance for all possible pairs
    dlat = radians(p2[0]-p1[0])
    dlon = radians(p2[1]-p1[1])

    a = sin(dlat/2) * sin(dlat/2) + cos(radians(p1[0]))*cos(radians(p2[0])) * sin(dlon/2) * sin(dlon/2)
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    d = 6371 * c
    return d

def query_iter(p):
    return max(dist_slow(p1, p2) for p1, p2 in itertools.combinations(p, 2))

def query_orig(p):
    dista=[]
    for i in range(len(p)):
      for j in range(i + 1, len(p)):
        z = dist_slow(p[i], p[j])
        dista.append(z)
    return max(dista)

def query_mine(p):
    return dist(p, p).max()

Then:
>>> points = np.random.rand(1000, 2)
>>> timeit query_orig(points)
1 loops, best of 3: 7.94 s per loop
>>> timeit query_iter(points)
1 loops, best of 3: 7.35 s per loop
>>> timeit query_mine(points)
10 loops, best of 3: 150 ms per loop

A: You can do everything in "vector" form with numpy ufunc:
from numpy import radians, sin, cos, sqrt, arctan2
from numpy import random

def max_dist(p1x,p1y,p2x,p2y):
    # give them "orthogonal" shape
    p1x = p1x.reshape(p1x.size,1)
    p1y = p1y.reshape(p1y.size,1)
    p2x = p2x.reshape(1,p2x.size)
    p2y = p2y.reshape(1,p2y.size)

    # compute the distance for all possible pairs
    dlat = radians(p2x-p1x)
    dlon = radians(p2y-p1y)

    a = sin(dlat/2) * sin(dlat/2) + cos(radians(p1x))*cos(radians(p2x)) * sin(dlon/2) * sin(dlon/2)
    c = 2 * arctan2(sqrt(a), sqrt(1-a))
    d = 6371 * c

    return d.max()

if __name__=='__main__':
    # generate random samples
    N = 1000
    p1x,p1y,p2x,p2y = random.rand(4,N)

    print 'max_dist=',max_dist(p1x,p1y,p2x,p2y)

A: Not sure about vectorizing, but you can certainly turn the double-for loop into a list comprehension. And since you just take the max value of that list, you can just as well use a generator expression for that.
def distGen(pts):
    return max(dist(pts[i], pts[j]) for i in range(len(pts))
                                    for j in range(i+1, len(pts)))

I did some timing analysis on this and this seems to be at least a bit faster. Interestingly, though, contrary to my intuition, using a list comprehension instead of a generator is even faster, but the generator should have the advantage of using far less memory.
1.15502595901   # your approach
1.37675499916   # your approach single max value var instead of list
1.00971293449   # above generator expression
0.916918992996  # above with list comprehension, i.e., max([...])

(Tested with Python 2.7 using a list of 1000 random numbers instead of Points and dist measuring the absolute distance between those numbers.)

Even better -- much cleaner and still a bit faster -- is using itertools.combinations to get all the combinations of two points:
import itertools
def distComb(pts):
    return max(dist(p1, p2) for p1, p2 in itertools.combinations(pts, 2))

A: Here's another solution, which first maps all your points onto a unit sphere:
import numpy as np
import scipy.spatial

def sphereify(points):
    """lat, long -> x, y, z  for a unit sphere"""
    lat = np.radians(points[:, 0, np.newaxis])
    long = np.radians(points[:, 1, np.newaxis])
    return np.hstack((
        np.cos(lat) * np.cos(long),
        np.cos(lat) * np.sin(long),
        np.sin(lat)
    ))

def arcDistance(chordDistance):
    """Get the surface distance corresponding to the chord distance"""
    return np.arcsin(chordDistance / 2) * 2

earthRadius = 6371
def query(points):
    dists = scipy.spatial.distance.pdist(sphereify(points))
    surfaceDist = earthRadius * arcDistance(dist.max())
    return surfaceDist

Then:
>>>  timeit query(points)
100 loops, best of 3: 6.23 ms per loop


text:
Q: Uima Ruta Out of Memory issue in spark context I'm running an UIMA application on apache spark. There are million of pages coming into batches to be processed by UIMA RUTA for calculation. But some time i'm facing out of memory exception.It throws exception sometime as it successfully process 2000 pages but some time fail on 500 pages.
Application Log
Caused by: java.lang.OutOfMemoryError: Java heap space
        at org.apache.uima.internal.util.IntArrayUtils.expand_size(IntArrayUtils.java:57)
        at org.apache.uima.internal.util.IntArrayUtils.ensure_size(IntArrayUtils.java:39)
        at org.apache.uima.cas.impl.Heap.grow(Heap.java:187)
        at org.apache.uima.cas.impl.Heap.add(Heap.java:241)
        at org.apache.uima.cas.impl.CASImpl.ll_createFS(CASImpl.java:2844)
        at org.apache.uima.cas.impl.CASImpl.createFS(CASImpl.java:489)
        at org.apache.uima.cas.impl.CASImpl.createAnnotation(CASImpl.java:3837)
        at org.apache.uima.ruta.rule.RuleMatch.getMatchedAnnotations(RuleMatch.java:172)
        at org.apache.uima.ruta.rule.RuleMatch.getMatchedAnnotationsOf(RuleMatch.java:68)
        at org.apache.uima.ruta.rule.RuleMatch.getLastMatchedAnnotation(RuleMatch.java:73)
        at org.apache.uima.ruta.rule.ComposedRuleElement.mergeDisjunctiveRuleMatches(ComposedRuleElement.java:330)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:213)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueMatch(ComposedRuleElement.java:225)
        at org.apache.uima.ruta.rule.ComposedRuleElement.continueOwnMatch(ComposedRuleElement.java:362)
        at org.apache.uima.ruta.rule.ComposedRuleElement.fallbackContinue(ComposedRuleElement.java:459)

UIMA RUTA SCRIPT
WORDLIST EnglishStopWordList = 'stopWords.txt';
WORDLIST FiltersList = 'AnchorFilters.txt';
DECLARE Filters, EnglishStopWords;
DECLARE Anchors, SpanStart,SpanClose;

DocumentAnnotation{-> ADDRETAINTYPE(MARKUP)};

DocumentAnnotation{-> MARKFAST(Filters, FiltersList)};

STRING MixCharacterRegex = "[0-9]+[a-zA-Z]+";

DocumentAnnotation{-> MARKFAST(EnglishStopWords, EnglishStopWordList,true)};
(SW | CW | CAP ) { -> MARK(Anchors, 1, 2)};
Anchors{CONTAINS(EnglishStopWords) -> UNMARK(Anchors)};

(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM)? (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) (SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM)? EnglishStopWords? { -> MARK(Anchors, 1, 4)};
(SW | CW | CAP ) (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) EnglishStopWords? { -> MARK(Anchors, 1, 3)};

Anchors{CONTAINS(MARKUP) -> UNMARK(Anchors)};
MixCharacterRegex -> Anchors;

"<Value>"  -> SpanStart;
"</Value>" -> SpanClose;

Anchors{-> CREATE(ExtractedData, "type" = "ANCHOR", "value" = Anchors)};

SpanStart Filters? SPACE? ExtractedData SPACE? Filters? SpanClose{-> GATHER(Data, 2, 6, "ExtractedData" = 4)};

A: Normally, the reasons for high memory usage in UIMA Ruta can be found in RutaBasic (many annotation, coverage information) or in RuleMatch (inefficient rules, many rule element matches).
This your example, the problem seems to origin somewhere else. The stacktrace indicates that the memory is used up by some disjunctive rule element, which requires to create new annotations for storing the match information.
It seems that the version of UIMA Ruta is rather old since line number do not match at all with the source I am looking at.
There are seven (!!!) calls of continueOwnMatch in the stacktrace. I was looking for a rule that could cause something like this but found none. This could be a old flaw which has been fixed in newer versions, or some preprocessing added additional CW/SW/CAP annotations.
As a first advice, I would suggest two things:

*

*Update to UIMA Ruta 2.6.0

*Get rid of all disjunctive rule elements

The disjunctive rule elements are not really needed in your script. In general, they should not used at all if not really required. I do not use them at all in productive rules.
Instead of (SW | CW | CAP ) you can simply write W.
Instead of (SPECIAL{REGEXP("['\"-=()\\[\\]]")}| PM) you can write ANY{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))}.
Using ANY as a matching condition can reduce the runtime performance. In this example, two rules instead of the rule lement rewrite might be better, e.g., something like
SPECIAL{REGEXP("['\"-=()\\[\\]]")} W ANY?{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))} EnglishStopWords? { -> MARK(Anchors, 1, 4)};
PM W ANY?{OR(REGEXP("['\"-=()\\[\\]]"),IS(PM))} EnglishStopWords? { -> MARK(Anchors, 1, 4)};

(optional rule elements at the start of a rule without any anchors in the rule are not optional)
btw, there is a lot of room for optimization in your rules. If I had to guess, I'd say you can get rid at least of half the rules and 90% of all created annotations, which would also considerably reduce the memory usage.
DISCLAIMER: I am a developer of UIMA Ruta


text:
Q: How to get machine name from ip address in SQL Server 2008? I have to get the machine name from IP address in SQL Server, is there anything that I could do to accomplish my task

A: DB:
IPAdd | MachineName

Query:
select MachineName from DBTable where IPAdd='yourIPAddress'

Try with:
SELECT SERVERPROPERTY('MachineName')

Or
SELECT
   CONNECTIONPROPERTY('net_transport') AS net_transport,
   CONNECTIONPROPERTY('protocol_type') AS protocol_type,
   CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
   CONNECTIONPROPERTY('local_net_address') AS local_net_address,
   CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
   CONNECTIONPROPERTY('client_net_address') AS client_net_address

Or
SELECT @@SERVERNAME;

Refer:
http://msdn.microsoft.com/en-us/library/ms187944.aspx
Hope its helpful.

A: You can't do this natively in the SQL language, your best bet is to either:
1/ shell out via xp-cmdshell and run nslookup, which will require some string manipulation to get the command right and then some cleaning up of the output to return the machine name
2/ Write a C# CLR function that takes the IP address as an input and makes use of the Dns.GetHostEntry method to resolve and return the name.
See here for the documentation:
Dns.GetHostEntry Method
I wrote a really quick simple CLR function for getting the machine name from the IP Address is below, please note there is no error handling or input checking to make sure the IP is valid before trying to resolve it, and it won't give you the IP address if you pass it a hostname, but it can be easily modified to include all these things, it's just to give you an idea of how it could work:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Net;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString dnsResolve(String ipAddress)
    {
        IPHostEntry host = Dns.GetHostEntry(ipAddress);
        return new SqlString(host.HostName.ToString());
    }
}

A: I might be wrong but as far as I know, SQL Server can not do what you want. Resolving machine names from IP address is something your network's DNS server does.
Best idea I come up with to get that info from SQL Server is using xp_cmdshell command to execute command prompt commands from SQL.
xp_cmdshell 'NBTSTAT -A 10.10.10.10'

However, please note that xp_cmdshell needs to be enabled on your server first in order to work, and often it is not beacause of possible security issues. Read more about xp_cmdshell at http://msdn.microsoft.com/en-us/library/ms175046.aspx
Also, result from this will be just like from command prompt and it will require some parsing to get exact machine name from it. Check this topic for more info: Get Results from XP_CMDSHELL
I don't know your solution architecture and how you get the IP address, but if it is from some client side applications, it might be easier to find client's machine name executing SELECT HOST_NAME() from client's side query or with .NET and sending machine names directly.

A: What you want is called a Reverse DNS lookup. There are command line tools that can do it (nslookup.exe) or you can use the DnsQuery API. You have no business doing either from T-SQL so don't try to do it. Resolve the IP to name in the client.

A: You can try this to get the name of your machine.
SELECT SERVERPROPERTY(N'MachineName');

May be above can serve your purpose.

A: --Im using command line for checking host name after IP
declare @IP as varchar(15)
declare @cmd as varchar(1000)
set @IP='192.168.0.1'
SET @cmd = 'ping -a -n 1 ' + @IP
Create Table #Output (Output varchar(150) default(''))
INSERT INTO #Output
EXEC xp_cmdshell @cmd
Begin try
Select top 1 Replace(LEFT([Output],CHARINDEX('[', [output])-2),'Pinging ','') as HostName from #Output where Output is not null
End Try
Begin catch
Select 'Host name for:' + @IP +' could not be find'
End catch
drop table #Output

A: This actually works: Modified answer from Sky Diver
--Im using command line for checking host name after IP
    declare @IP as varchar(15)
    declare @cmd as varchar(1000)
    set @IP='137.201.17.204'
    SET @cmd = 'ping -a -n 1 ' + @IP
    Create Table #Output (Output varchar(150) default(''))
    INSERT INTO #Output
    EXEC xp_cmdshell @cmd
    Begin try
    Select top 1 Replace(LEFT([Output],CHARINDEX('[', [Output])-2),'Pinging ','') as HostName from #Output where Output like 'Pinging%'
    End Try
    Begin catch
    Select 'Host name for:' + @IP +' could not be find'
    End catch
    --drop table #Output

A: Try this you will get a system Name.......
select HOST_NAME()
regards : Rajsri Vyshnnavi


text:
Q: Predicate filtration of collection in c# with LINQ and necessity to compare results with List elements I am  filtering in C# with LINQ my collection  according to below given code. It is working for my purpose at first good. But I have a situation that in the filtering I have to compare one of the fields of my object (ProductNo) with values from List. As long as I know how many elements will have this table I can do this. But I want to extend functionality so that my code will automatically check how many  times should check this statement:
((ProductList)item).ProductNo.Contains(foundPT[i])

Please help me I was looking for solutions and the closest solution which I found was this one:
How to find if a string contains any items of an List of strings?
But I cannot implement it in my case.
static public ICollectionView ProductionTravelersFilter(ObservableCollection<ProductList> obProductList, string searchedString)
{
            // Collection which will take ObservableCollection
            var _itemSourceList = new CollectionViewSource() { Source = obProductList };
            // ICollectionView the View/UI part
            ICollectionView Itemlist = _itemSourceList.View;
            List<string> foundPT = FilteredProductionTravelers(searchedString);
            int arrayLength=foundPT.Count;
            // your Filter
            var CustomFilter = new Predicate<object>(item =>
                                    ((ProductList)item).TakenFromProductNo.Contains(searchedString) ||
                                    ((ProductList)item).DrawingNumber.Contains(searchedString) ||
                                    ((ProductList)item).ProductType.Contains(searchedString) ||
                                    ((ProductList)item).Material.Contains(searchedString) ||
                                    ((ProductList)item).CreationDate.Contains(searchedString) ||
                                    ((ProductList)item).ProductNo.Contains(searchedString) ||
                                    ((ProductList)item).Application.Contains(searchedString) ||
                                    ((ProductList)item).Description.Contains(searchedString)||
                                    ((ProductList)item).ProductNo.Contains(foundPT[0]) ||
                                    ((ProductList)item).ProductNo.Contains(foundPT[1]) ||
                                    ((ProductList)item).ProductNo.Contains(foundPT[2]) ||
                                    );

            //add our Filter
            Itemlist.Filter = CustomFilter;
            return Itemlist;
}


text:
Q: Angular application with Java This is very basic question and i am new to this..Can anyone tell me the structure for Angular js with Java & Maven. I want to create application using angular 1.x with Java using maven and also i want to use jersey(rest api) to make microservice call to pull data.How would be the structure for this application?
Note: I want to use grunt or gulp for development purpose and even integrate with jenkins jobs

A: The same one as any Maven web application. Maven doesn't care about what JS framework you use, if any. JS files are static files that must be served by the app, just like any other static file.
See https://maven.apache.org/plugins/maven-war-plugin/usage.html for the structure of a war project.


text:
Q: How to create an array within the constructor? I want to create a new array as an attribute of the object once I create a new instance. But I get the following error in Chrome: "Uncaught TypeError: Cannot call method 'push' of undefined". Players seems to be unkown. But why?
function Team(name) {
    this.Name = name;
    this.Players = new Array();
}

Team.prototype.AddPlayer = new function (player) {
    this.Players.push(player); //error
}

A: Just remove the 'new' in this line
Team.prototype.AddPlayer = function (player) {

A: Your code is correct, but you need to be sure to make a new Team instance using new.
var t = new Team("foo");
t.AddPlayer("bar");

Oops, one error in your code. Remove new from before function in the .prototype assignment.
function Team(name) {
    this.Name = name;
    this.Players = new Array();
}

Team.prototype.AddPlayer = /*new*/ function (player) {
    this.Players.push(player);
}

Because you had new before the function, you were actually using the anonymous function as a constructor, which means it was being invoked.
To be clear, new does not make a new function unless it is placed before the Function constructor.


text:
Q: Html access through link only, cannot be visited? I was wondering if there is a way that a link on my site is clicked on for access, but cannot be visited directly. Is it possible, and if so, how? JScript?

A: This is not fully possible in the sense of absolute prevention against bots or automatic programs.
There are two possibilities:

*

*Check the HTTP Referrer. Some browsers send the previous URI in there. But note that users may have disabled this (e.g. I switched it off).

*Force the user to view the first site. If the user loads the second site without having visited the first site, redirect him to a fake URI or whatever.
Sample for the second point:
first.php:
<?php
session_start();
$_SESSION['firstPageDate'] = time();

second.php:
<?php
session_start();
$firstPageDate = isset($_SESSION['firstPageDate']) ? $_SESSION['firstPageDate'] : 0;
$maxDiff = 60 * 3; // The user has 3 minutes for clicking the link

if (time() - $firstPageDate > $maxDiff) {
  header('HTTP/1.1 401 Unauthorized', true, 401);
  exit('No access');
}

A: Sure, you just have to prevent the default event. For example, here's how it would be done using jQuery:
$('#myLink').on('click', function (event) {
    event.preventDefault();

    // ... something else
});

EDIT I believe I misread the question and got it exactly backwards. I now think the question is "can I have a link that the user can interact with, but can't be accessed directly (for example, by typing in the url)." The answer is "yes."
Click me!

script:
$("#myLink").on("click", function (event) {
    // either set the window.location for redirect or
    // perform some other operation.
});

Clicking the link will have the desired affect. If you truly want to go to a destination page that cannot be accessed from the outside, you'll need to coordinate with your server to set up some sort of authentication.

A: No this is not possible as you describe.


text:
Q: Get variable from Adaptive card `Action.Submit` in Botframework How can I get the value when user clicks the button? I have this example card.
{
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "type": "AdaptiveCard",
  "version": "1.0",
  "speak": "<s>Your  meeting about \"Adaptive Card design session\"<break strength='weak'/> is starting at 12:30pm</s><s>Do you want to snooze <break strength='weak'/> or do you want to send a late notification to the attendees?</s>",
  "body": [
    {
      "type": "TextBlock",
      "text": "Adaptive Card design session",
      "size": "large",
      "weight": "bolder"
    },
    {
      "type": "TextBlock",
      "text": "Conf Room 112/3377 (10)",
      "isSubtle":true
    },
    {
      "type": "TextBlock",
      "text": "12:30 PM - 1:30 PM",
      "isSubtle":true,
      "spacing":"none"
    },
    {
      "type": "TextBlock",
      "text": "Snooze for"
    },
    {
      "type": "Input.ChoiceSet",
      "id": "snooze",
      "style":"compact",
      "value": "5",
      "choices": [
        {
          "title": "5 minutes",
          "value": "5",
          "isSelected": true
        },
        {
          "title": "15 minutes",
          "value": "15"
        },
        {
          "title": "30 minutes",
          "value": "30"
        }
      ]
    }
  ],
  "actions": [
    {
      "type": "Action.Submit",
      "title": "Snooze",
      "data": { "x": "snooze" }
    },
    {
      "type": "Action.Submit",
      "title": "I'll be late",
      "data": { "x": "late" }
    }
  ]
}

The example is here: http://adaptivecards.io/samples/CalendarReminder.html
How to access it in the session.message object?

A: I figured it out. In this case it is the x, so to reply it back it would be:
if (session.message && session.message.value) {
    // A Card's Submit Action obj was received
    session.send(session.message.value.x)
}


text:
Q: javaScript and HTML-Textarea Text not erasing Html file with JavaScript functions

<title>Voice to Text</title>

<form>
Enter Text:
<textarea placeholder="Enter text here for detection." id="name" name="name" class="result" >
</textarea>
</form>

Language

          <select name="input-language" id="language"></select>

      <button class="btn record" id='myid'>

  Start Listening

      </button>

        <button class="btn clear" id='clr' style="margin-left:150px" onClick="erasText()">
          Clear
        </button>

When i click on clear button than the text on textarea is not erasing and when i press 'Start Listening' than this button works. i think 'erasText' function is not calling and only the following function is calling in the above code:

clr.addEventListener("click", () => {
      document.getElementById("name").innerHTML = "";
    })

I called erasText function on button click but i do not know why the erasText button is not calling. Is there a way to call this function?

A: The field you are actually looking for is value instead of innerText.
clr.addEventListener("click", () => {
      document.getElementById("name").value = "";
});


text:
Q: How to send file using ajax file upload to controller along with other parameters like textbox data in spring mvc? Also need to send data in json to server side with file. how to handle this on server and client side?

A: As I know you can send just text with an file and not in JSON format or an binary file.
You can check them all with postman!
There is one Controller example in backend:
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/uploadImageGallery", method = RequestMethod.POST)
public ResponseEntity<JPresent<Boolean>> imageGallery(@RequestParam("file") MultipartFile file,
                                                      @RequestParam("marketerId") Long marketerId) {

        Boolean result = new Boolean(false);

        MarketerPictureModel pictureModel = new MarketerPictureModel();
        byte[] bytes;
        if (!file.isEmpty()) {
            try {
                pictureModel.setContentType(file.getContentType());
                service.addToImageGallery(pictureModel);
                return jpresent.getResponse(result = true);
            } catch (IOException e) {
                e.printStackTrace();
                return ...
            } catch (Exception e) {
            ...

    }


text:
Q: How to do multiple if, else statements in this case in bash script? Right now I am running a few programs with bash scripts (with Cygwin).
Basically what I am doing is after the program is starting, a loop is ran that checks that the program is still running.
I was doing:
while true
do
    if [ "$(ps -W | grep -w name | gawk '{print $8,$9}' | gawk -F \\ '{print $4}')" == 'program' ];then
        sleep 1
    else
        "start program" (whatever is needed here)
    fi
done

But I started to realize having such a script multiple times is just causing unnecessary system resources to be used.
I tried doing an if then, elif, but it never goes past the first if.
I need it to go "alright the first if is negative, try the next, go to the end, start over".
Here is the copy of my script and I forgot to say I was using Cygwin but that really doesn't change anything cause it seems to still use normal bash scripting just maybe different paths to start files. http://pastebin.com/s8ZdPQMn and yes the h. is not there I just can't seem to edit the pastebin.
My overall plan is check that first SRPro is running, check the next, etc, only triggering if it's detected one is not running.
EDIT: I solved it. Not exactly sure why but in my original single file per program, gawk printing $4 at the end gave me what I wanted, but for some reason when doing it this way, it turned to $5. So changing $4 to $5 made the script work.
EDIT: One really strange issue though is, it will work minutes on end, then all the sudden get confused at times, and start 7 copies of one program or something. Also it can be random on which it starts.

A: You might find the wait command (try help wait from a bash prompt) useful. It's unclear exactly what you want, but as an example, here's a basic respawn function:
$ respawn () {
>   while true
>   do
>     "${@}" &
>     wait ${!}
>     echo "respawning ..."
>   done
> }
$ respawn some_program arg1 arg2 etc


text:
Q: get value name from array for specific index In the code below, if I use 'let' instead of 'var' for declaration of array , it seems to work fine. I am not able to figure out why is this case in the below code.
And the second case is when I change the name of array from 'name' to something else like 'itemNames' , the code seems to work fine, is it something i am missing? I thought it might have to do with reserved keywords in JavaScript , however i had no luck with it . I have tried giving reserved keywords name to array for testing purpose (which is not recommended ) and the output was fine.
var name = ["ravina","Aditya","Rohit","shruti"]
function checkThree() {
    for(var i = 0; i<name.length; i++) {
        if (name[i].length == 3) {
            return name[i];
        }
    }
}
console.log(checkThree())

A: Maybe this can help: https://developer.mozilla.org/en-US/docs/Web/API/Window/name
'var name' refers to the global window.name.
this global.name will be converted to a string of you log it to the console. (see output below)

With 'let name' you declares a block-scoped local variable. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#:~:text=Description,function%20regardless%20of%20block%20scope.)


text:
Q: ASP.NET MVC Model Patterns: What works best? I've done a couple of projects in ASP.NET MVC and there is a topic that I haven't really seen covered anywhere. I wanted to get some other peoples' opinions on this.
What are some best practices for designing models? I've taken two approaches in the past: Should models represent distinct entities, or should you have domain specific (sub-domain specific? view specific?) models? The difference really being models representing distinct entities are used in more than one view where as the domain specific models are tied to specific views.
Consider the following: I have a User entity in my application. Should I have a single UserModel that I use in the Register view, the Show view, the Index view, etc., or would it be preferred to have a RegisterUserModel, a ShowUserModel, a ListUserModel, etc.?
I've used both patterns before. The up side of the domain specific models is that any validation logic applied via attributes can be different between views. The down side is you violate DRY and your models get pretty hairy -- even if you separate them in to namespaces. Conversely, using the single model-to-entity pattern leads to overly generic validation data (usually with regard to error messages) but you have a nice, tight model layer and converting between models and entities is a lot easier (less code).
What approach does SO prefer? Or is there an approach that I'm not even considering?

A: I like to create my data models and then create specific view models as I need them.
The Case for ViewModel
The ViewModel Pattern

A: When I think of domain models, I think about business logic as well. I try to keep the M in MVC to refer to the models that assist in the presentation aspect of the application, and not the entities (domain objects) that represent my real-world objects.

A: Model and View shuld be a pair. Building huge Model classes and huge Views is not good idea. In my opinion in your view-Model you should represent only needed part of your business logic. For example. When you'r creating Registration form make your Model and View that simple as it can be possible - Create RegisterUserModel.cs and RegisterUserView.aspx. Do not pass there whole User object. Make it light, don't break Single Responibility Principle.


text:
Q: Widget double click I have a widget (AppWidgetProvider) and i want to know if there is a way to support multiple clicks.Example:
1)If is the first click on the widget, then the ImageButton of the widget changes (for example, changes the color).
2)If is the second time, then open an Activity.
-- There is some way to handle click events inside AppWidgetProvider?
My code:
public class MyWidgetProvider extends AppWidgetProvider
{

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            Intent intent = new Intent(context, MyActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.control_widget);

            views.setOnClickPendingIntent(R.id.asdf, pendingIntent);

             appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

My widget is working fine. When i click the ImageButton(R.id.asdf), it goes to the activity MyActivity.
Id like to know how can i handle click events on my widget to make a different action (example: change the color of the ImageButton) instead of go to some activity. Is there some other way to some click handle besides setOnClickPendingIntent()?

A: Maybe this could help. It works for me:
public class WidgetProvider extends AppWidgetProvider {

private static final int DOUBLE_CLICK_DELAY = 500;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
    Intent intent = new Intent(context, getClass());
    intent.setAction("Click");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.image, pendingIntent);
    appWidgetManager.updateAppWidget(appWidgetIds, views);
    context.getSharedPreferences("widget", 0).edit().putInt("clicks", 0).commit();

}

@Override
public void onReceive(final Context context, Intent intent) {

    if (intent.getAction().equals("Click")) {

        int clickCount = context.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);
        context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", ++clickCount).commit();

        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                int clickCount = context.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);

                if (clickCount > 1) Toast.makeText(context, "doubleClick", Toast.LENGTH_SHORT).show();
                else Toast.makeText(context, "singleClick", Toast.LENGTH_SHORT).show();

                context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", 0).commit();
            }
        };

        if (clickCount == 1) new Thread() {
            @Override
            public void run(){
                try {
                    synchronized(this) { wait(DOUBLE_CLICK_DELAY); }
                    handler.sendEmptyMessage(0);
                } catch(InterruptedException ex) {}
            }
        }.start();
    }

    super.onReceive(context, intent);

}

}

A: I did it this way:
1)If is the first click on the widget, then the ImageButton of the widget changes
2)If is the second time, then open an Activity and return to the inicial ImageButton state.
Im handling click events with setOnClickPendingIntent:
private int[] RESOURCES = {R.drawable.button1,R.drawable.button2};

@Override
        public void onUpdate(Context context, AppWidgetManager mgr, int[] appWidgetIds) {

            ComponentName me = new ComponentName(context, MyWidgetProvider.class);
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.my_widget);

            Intent widgetIntent = new Intent(context, MyWidgetProvider.class);
            Intent myIntent= new Intent(context, MyOtherActivity.class);

            widgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            PendingIntent pendingIntent;

            if(clicks == 0)
            {
                clicks = 1;
                remoteViews.setImageViewResource(R.id.my_image_button, RESOURCES[0]);
                pendingIntent = PendingIntent.getBroadcast(context, 0, widgetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
            else if(clicks == 1)
            {
                clicks = 2;
                remoteViews.setImageViewResource(R.id.my_image_button, RESOURCES[1]);
                pendingIntent = PendingIntent.getActivity(context, 0, myIntent,0);
            }
            else //clicks == 2
            {
                clicks = 0;
                remoteViews.setImageViewResource(R.id.my_image_button, RESOURCES[0]);
                pendingIntent = PendingIntent.getBroadcast(context, 0, widgetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }

            remoteViews.setOnClickPendingIntent(R.id.my_image_button, pendingIntent);

            mgr.updateAppWidget(me, remoteViews);
        }

        @Override
        public void onEnabled(Context context) {
            clicks = 0;
            super.onEnabled(context);

        }

A: Unlike Button and its subclasses, AppWidget doesn't have the concept of an onClickListener.  AppWidgets have to provide a PendingIntent for the application that hosts them to fire when the widget is clicked.  If you wanted to track multiple clicks, you would need to have a receiver that filters on an intent specific to your widget and keeps track of how many times it has received it.
Slightly-less-relevant:  You might reconsider your behavior model.  Android is a one-click-to-take-action environment that doesn't have the same "click-once-to-select" concept like you'd find in, say, Windows.  By emulating that behavior, your widget won't behave like all of the other UI elements and may cause confusion.  Additionally, if there are two of your widgets on the screen and the user taps one and then the other, both will appear "selected," which probably isn't what you want.

A: Why not just count the clicks yourself?
private class MyAwesomeClickListener implements OnClickListener {
    private int clicks = 0;
    @Override
    public void onClick(View v) {
        ++clicks;
        //do some cool stuff
    }

}

A: Don't count it in a listener (it's ridiculous, you don't know when your widget will be recycled from the memory and you will lose the value of int clicks)
Persist the number of clicks (add +1 each time it is clicked, restart to 0 when you reach the end of the click "cycle", the end of different click behaviors).
You could persist them in a database, with serialization, or with the shared preferences (I guess the preferences are the easiest way)

A: This is what I'm doing. Works beautifully =]
public class MyWidgetProvider extends AppWidgetProvider {

    //Length of allowed time in between clicks in milliseconds
    private static final long DOUBLE_CLICK_WINDOW = 400;
    private static volatile long firstClickTimeReference;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            long currentSystemTime = System.currentTimeMillis();

            if(currentSystemTime - firstClickTimeReference <= DOUBLE_CLICK_WINDOW) {
                //double click happened in less than 400 miliseconds
                //so let's start our activity
                Intent intent = new Intent(context, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity( intent );
            } else {
                firstClickTimeReference = currentSystemTime;

                RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                        R.layout.control_widget);

                Intent intent = new Intent(context, WidgetProvider.class);
                intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                        0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
                appWidgetManager.updateAppWidget(widgetId, remoteViews);
            }
        }
    }
}

A: The solution by almisoft provides a double-click feel rather than simply successive clicks. And it works. Unfortunately you also get a lint message telling you that the 'handler class should be static or leaks might occur'. The solution is to use a weak reference and static handler - a generic version is here. Converting almisoft's code gives:
public class WidgetProvider extends AppWidgetProvider {

private static final int DOUBLE_CLICK_DELAY = 500;
private static Context mContext;
private static int mClickCount;

private static class MyHandler extends Handler {
  //Using a weak reference means you won't prevent garbage collection
  private final WeakReference<WidgetProvider> myClassWeakReference;
  public MyHandler(WidgetProvider myClassInstance) {
    myClassWeakReference = new WeakReference<WidgetProvider>(myClassInstance);
  }
  @Override
  public void handleMessage(Message msg) {
    WidgetProvider myWidget = myClassWeakReference.get();
    if (myWidget != null) {
        //...do work here as in almisoft original...
        int clickCount = mContext.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);
        if (clickCount > 1) {
          Toast.makeText(mContext, "doubleClick", Toast.LENGTH_SHORT).show();
        } else {
          Toast.makeText(mContext, "singleClick", Toast.LENGTH_SHORT).show();
        }
        mContext.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", 0).commit();
    }
  }
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
    Intent intent = new Intent(context, getClass());
    intent.setAction("Click");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.image, pendingIntent);
    appWidgetManager.updateAppWidget(appWidgetIds, views);
    context.getSharedPreferences("widget", 0).edit().putInt("clicks", 0).commit();
}

@Override
public void onReceive(final Context context, Intent intent) {
    mContext=context;
    mIntent=intent;
    if (intent.getAction().equals("Click")) {
        int clickCount = context.getSharedPreferences("widget", Context.MODE_PRIVATE).getInt("clicks", 0);
        context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit().putInt("clicks", ++clickCount).commit();
        final Handler handler=new MyHandler(this);
        if (clickCount == 1) new Thread() {
            @Override
            public void run(){
                try {
                    synchronized(this) { wait(DOUBLE_CLICK_DELAY); }
                    handler.sendEmptyMessage(0);
                } catch(InterruptedException ex) {}
            }
        }.start();
      }
    super.onReceive(context, intent);
    }

}


text:
Q: 'BLOB is not a valid UTF-8 string' error? Im reading in a document that the user uploads from the visualFlow:
<apex:inputFile value="{!contentFile}" filename="{!nameFile}" id="file"/>

And its accessed in apex in this manner:
String nameFile = contentFile.toString();

And it works like a charm. I am able to parse through the document and extract all the information needed, but only for English users. But for Spanish users that's not the case.
Those files have some special characters, and cause a BLOB is not a valid UTF-8 string error.
I've tried to base64Encode the file contents, but the results come out illegible.
String nameFile= EncodingUtil.base64Encode(contentFile);

A: While it does not appear to be clearly documented, having scanned a number of forum posts about this. The Blob type only supports UTF-8 encoded strings, you must ensure that the file you're uploading complies with this encoding, otherwise you will get this error in cases where you have special characters.
To ensure your file is UTF-8, for example in Windows Notepad make sure that you select to save as Unicode UTF-8 in the Save As dialog, other applications will likely have a similar option (for command line this answer might be of use).

A: Try this code to convert Blob in known charset to UTF-8 string
    /**
    @param input    Blob data representing correct string in @inCharset encoding
    @param inCharset    encoding of the Blob data (for example 'ISO 8859-2')
*/
public static String blobToString(Blob input, String inCharset){
    String hex = EncodingUtil.convertToHex(input);
    System.assertEquals(0, hex.length() & 1);
    final Integer bytesCount = hex.length() >> 1;
    String[] bytes = new String[bytesCount];
    for(Integer i = 0; i < bytesCount; ++i)
        bytes[i] =  hex.mid(i << 1, 2);
    return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
}

Note though this code works correctly, but wastes a lot of CPU time


text:
Q: Using a List (Spark List Control) as a Spark Datagrid Column Item renderer I have the following problem:
I need to create a dynamic datagrid, but the content of the cells are an ArrayCollection.
I'm trying to use the Spark List Control, as the item renderer of each column, but is not working properly.
Does anyone already had to do something similar or know a good example of the solution?
Thanks.

A: I've just found the solution, it's something like:
<s:GridItemRenderer>

<s:List id="eventsGroup" borderVisible="false" contentBackgroundAlpha="0" useVirtualLayout="false"`>
        <s:layout>
            <s:VerticalLayout variableRowHeight="true"/>
        </s:layout>
    </s:List>
</s:GridItemRenderer>

And then we can just add a simple item renderer for each List element.


text:
Q: AS3 mouseClick ignore a movieclip Is there a way in AS3 to make a the mouse ignore a certain movieclip? I need it to be on top of the other movieclips (due to transparancy effects), but have it in a way that allows clicking on the movieclips underneath it. I know about ".mouseChildren = false", but that only makes all the stuff inside that movieclip unclickable, but it still functions as a "barrier" on top of all the others buttons.
Is there a way to do this, or do I need to remove it completely ?

A: You need to set both .mouseChildren and .mouseEnabled to false before you can click on objects behind the MovieClip. This makes the mouse ignore the objects within the MovieClip and the MovieClip itself.
Source: http://pixelfumes.blogspot.com/2008/01/clicking-through-movieclips-to.html
EDIT: Oops, didn't see that comment by Alex, sorry.


text:
Q: Is it possible to auto drop trigger and sequence when I drop table I am using Oracle XE.
Is there any way to drop trigger and sequence automatically when I drop table?
Here is my table, sequence and trigger:
create table country(
country_id number(5) primary key,
country varchar2(36),
country_code varchar2(3)
);

create sequence country_seq
start with 1 increment by 1;

create or replace trigger country_trig
before insert on country
referencing new as new
for each row
begin
select country_seq.nextval into :new.country_id from dual;
end;
/

I am using this when main table record removes then all records of child table are auto deletes

A: Sequences created with create sequence are not associated with any particular table and so they are never automatically dropped. For one thing, you might reuse a sequence for multiple tables. There is no sense in which a sequence belongs to one table.
The only sequences that are automatically dropped are the ones generated as part of an identity column. (This feature was added in Oracle 12.1, and as you tagged 11g it means you don't have identity columns.)
Demo using identity columns (12.1 and later):
create table demo
( demo_id integer generated always as identity
, some_column varchar2(20) );

create or replace trigger demo_trg
before insert on demo for each row
begin
    dbms_output.put_line('Trigger firing: '||$$plsql_unit);
end demo;
/

Now I have a table with a trigger, and also a sequence associated with the identity column:
select * from user_tab_identity_cols where table_name = 'DEMO';

TABLE_NAME
COLUMN_NAME
GENERATION_TYPE
SEQUENCE_NAME
IDENTITY_OPTIONS

DEMO
DEMO_ID
ALWAYS
ISEQ$$_88798
START WITH: 1, INCREMENT BY: 1, MAX_VALUE: 9999999999999999999999999999, MIN_VALUE: 1, CYCLE_FLAG: N, CACHE_SIZE: 20, ORDER_FLAG: N, SCALE_FLAG: N, EXTEND_FLAG: N, SESSION_FLAG: N, KEEP_VALUE: N

Here, sequence ISEQ$$_88798 was created automatically for my demo_id identity column. We can also see it in user_sequences:
select * from user_sequences where sequence_name = 'ISEQ$$_88798';

SEQUENCE_NAME
MIN_VALUE
MAX_VALUE
INCREMENT_BY
CYCLE_FLAG
ORDER_FLAG
CACHE_SIZE
LAST_NUMBER
SCALE_FLAG
EXTEND_FLAG
SHARDED_FLAG

ISEQ$$_88798
1
1E28
1
N
N
20
21
N
N
N

and in user_objects:
select o.object_name, o.object_type, o.created
from   user_objects o
where  o.object_name in ('DEMO','DEMO_TRG','ISEQ$$_88798');

OBJECT_NAME
OBJECT_TYPE
CREATED

DEMO
TABLE
27/02/2021 11:09:02

DEMO_TRG
TRIGGER
27/02/2021 11:10:42

ISEQ$$_88798
SEQUENCE
27/02/2021 11:09:02

Now if I drop the table, all three disappear:
drop table demo purge;

select o.object_name, o.object_type, o.created
from   user_objects o
where  o.object_name in ('DEMO','DEMO_TRG','ISEQ$$_88798');

no rows selected

If I create a normal sequence as create sequence myseq then it has no association with the table, so if I want too drop it I must do it explicitly with drop sequence myseq.


text:
Q: Error compiling PyGraphviz 1.2 on OSX Mavericks with Xcode 5 G'day everyone,
I am trying to install PyGraphviz 1.2 on OSX Mavericks. I have just upgraded from Mountain Lion and now have Xcode 5.0.1 installed with Command Line Tools. I have downloaded the PyGraphviz source package, unpacked it and ran sudo python setup.py install.
I am getting the following error message (there is some output prior to this, including several warnings):
cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.9-intel-2.7/pygraphviz/graphviz_wrap.o -L/usr/local/lib/graphviz -L/usr/local/lib/graphviz -lcgraph -lcdt -o build/lib.macosx-10.9-intel-2.7/pygraphviz/_graphviz.so
ld: library not found for -lcgraph
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'cc' failed with exit status 1

Also, the first two lines of output are:
library_path=/usr/local/lib/graphviz
include_path=/usr/local/include/graphviz

which leads me to believe that compiler knows where to look for libraries.
What could be the problem? Just to make things clear: for technical reasons I have to use Apple's version of Python 2.7 and everything works fine on my other machine with OSX Lion and Xcode 4... (not sure what the exact version is).

A: I had a same error and resolved it by installing command line tools for XCode. Assuming you upgraded your XCode to 5.0.1, you can install command line tools by typing "xcode-select --install" to terminal and it will prompt you to install command line tools.


text:
Q: Call main thread object methods from second thread design pattern I have state pattern based program. Main thread initiates first state change following by starting second thread. All rest states changed according to second thread events that are generated like observer design pattern. It some state change cases I need to call several object that is in first(main) thread methods. This object is created in main thread and is responsible on information transfer via TCP. I'm not author of this object's class. Problem is that if I call this object methods in second thread it doesn't works. What is most elegant way to solve this problem? I would like not to change code of TCP object because it is huge and I have no time to go into analysis.
I must use Java version 1.4

A: If I got you right, you:

*

*have two threads;

*one thread does TCP traffic;

*sometimes you must initiate TCP traffic from the second thread;

*but it fails because the TCP code is not thread-safe.

It would seem like you need a single-threaded executor service which will do all the TCP work. You can submit tasks to that executor service from any other thread.


text:
Q: How to iterate through all users belonging to another user I'm working on a project to allow a teacher to do batch grade creation for students. I already have standard grade creation working fine when doing it for a specific student.
A teacher (User) has a number of students (User) that belong to them. What I'm trying to achieve is when you click 'create batch of grades', it takes you to the create_grade_path for the first student where you can input the grade and click create. This takes you to the create_grade_path for the next student and so on until all students have had a grade created.
My question is in a general sense what would be the best way to iterate through them as I haven't come across something like this. I have a variable @all_students that is an array of all students belonging to the current logged in teacher. Would I create copy of this and remove records from it until it's empty?
Thank you so much,

A: First consider adding additional parameter, something like batch_update, to your create_grade_path route. This parameter will indicate if this is batch or single create action.
If this is batch request, after successful save you need to redirect to grade view for another student. You can do that in many ways. You can fetch from database another student that doesn't have grade or you can use session for storing ids of students that need grades. With session you need to create another action that will initiate whole process.
def start_batch_create
  @all_students = Student.all # or other query
  sessions[:students_to_grade] = @all_students.map(&:id)
end

Now in create action you can access this session variable remove one student and redirect to create grade for another student unless there are some ids in the session variable.


text:
Q: How to calculate total length of process until it changes using two columns in python? Here is a snippet of data-frame which looks like this (original data frame contains 8k rows):
     User   State      change_datetime  endstate
0  100234     XIM  2016-01-19 17:03:12  Inactive
1  100234  Active  2016-01-28 17:17:15       XIM
2  100234  Active  2016-02-16 17:57:50       NaN
3  100234    Live  2016-02-16 17:58:51    Active
4  213421     XIM  2016-02-16 17:57:53       NaN
5  213421  Active  2018-02-01 10:01:51       XIM
6  213421  Active  2018-02-01 20:49:41       NaN
7  213421  Active  2018-02-13 20:40:11       NaN
8  213421       R  2018-03-04 05:38:51    Active
9  612312    B-98  2018-11-01 17:12:11       XIM

I'm trying to find out how long each unique User spends in an 'Active' state till they change into a different state other than 'Active'. There is an 'endstate' column which contains an 'Active' value, So I wanted to calculate the total time difference from when the 'State' column starts as 'Active' until the 'endstate' column contains 'Active'
Originally, I used the following code:
df["change_datetime"] = pd.to_datetime(df["change_datetime"])

cond1 = df["State"].eq("Active")
cond2 = df["State"].shift(-1).ne("Active")

start = df.loc[cond1].groupby("User")["change_datetime"].first()
end = df.loc[cond1&cond2].groupby("User")["change_datetime"].first()

print (end-start)
Active_state_duration = (end-start).to_frame()
Active_state_duration.head()

The returned results are:
User
100234   19 days 00:40:35
213421   12 days 10:38:20
Name: change_datetime, dtype: timedelta64[ns]

For User 100234, 19 days and 00:40:35 is calculated for Line 2 and 3 however it should be 19 days and 00:41:36 (using Line 4) as it takes the User 1 minute and 1 second to transition from 'Active' to 'Live'.
I was hoping to use the 'endstate' column in this code so that the time duration of the User being 'Active' is run using the 'State' column until the next line of code has 'Active' as the value in 'end_state' and a different value other than 'Active' for 'State'.
Here is an example of how i'm hoping to calculate the time duration:
Is there a way to do this?
Here is how i'm trying to calculate the duration:

A: Use Series.eq to create a boolean mask m then filter the dataframe using this mask and use DataFrame.groupby and agg the column change_datetime using np.ptp:
m = df['State'].eq('Active') | df['endstate'].eq('Active')
s = df[m].groupby(['User', (~m).cumsum()])['change_datetime'].agg(np.ptp).droplevel(1)

OR, if always need to consider one transition per user in the dataframe:
m1 = df['State'].eq('Active')
m2 = ~m1 & df['endstate'].eq('Active')

s1 = df[m1].groupby('User')['change_datetime'].first()
s2 = df[m2].groupby('User')['change_datetime'].first()

s = s2.sub(s1)

Result:
print(s)
User
100234   19 days 00:41:36
213421   30 days 19:37:00
Name: change_datetime, dtype: timedelta64[ns]


text:
Q: Error installing Crashlytics pod due to SSL certificate verfication When I try to install the Crashlytics pod I get the following error:
Installing Crashlytics (3.7.2)

[!] Error installing Crashlytics
[!] /usr/bin/curl -f -L -o /var/folders/gd/z79q6q5s1xs6n9jp60hbc5_00000gn/T/d20160809-2596-11a0t7q/file.zip https://kit-downloads.fabric.io/cocoapods/crashlytics/3.7.2/crashlytics.zip --create-dirs --netrc

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (51) SSL: certificate verification failed (result: 5)

Any ideas?


text:
Q: #2002 - — The server is not responding (or the local server's socket is not correctly configured) I am using UniServer Zero XIII 13.3.2. Everything was working correctly for me a few hours ago. I just made my PC sleep and I guess something suddenly broke the MySQL sockets or connections because next time I started the computer and tried to connect, I received this error:
#2002 -  — The server is not responding (or the local server's socket is not correctly configured).

I tried restarting the computer and starting/stopping Apache and MySQL multiple times. In theory, MySQL is starting successfully because I see green squares, not red:

Nonetheless, when I go to the MySQL Console, I see this:
Warning: Using a password on the command line interface can be insecure.
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (10061)

C:\Users\[path]\UniformServer13_3_2_ZeroXIII\UniServerZ\core\mysql\bin>

Also, when I go to http://localhost:90/us_opt1/index.php, I see this:
Welcome to phpMyAdmin

Error
MySQL said: Documentation

#2002 -  — The server is not responding (or the local server's socket is not correctly configured).
 mysqli_real_connect(): (HY000/2002): No se puede establecer una conexi�n ya que el equipo de destino deneg� expresamente dicha conexi�n.
 Connection for controluser as defined in your configuration failed.
 mysqli_real_connect(): (HY000/2002): No se puede establecer una conexi�n ya que el equipo de destino deneg� expresamente dicha conexi�n.
Retry to connect

Clearly, the MySQL connection was not successful even though apparently I can stop and start MySQL successfully from what I see in the UniServer Zero XIII panel. Any ideas about what broke the MySQL connection or environment and how to fix it? Thank you.

A: I have no idea what went wrong but what I did was to download again UniServer Zero XIII 13.3.2 from https://sourceforge.net/projects/miniserver/files/Uniform%20Server%20ZeroXIII/13_3_2_ZeroXIII/ and both Apache and MySQL were up and running, working correctly again from this new installation. Of course then I had to move source code to this new folder location where I completed the installation. I wanted to share this workaround instead of trying to figure out what happened, which I have no idea as I mentioned at the beginning of this answer.


text:
Q: Loop function inside html in javascript (React) I want to loop over my function SliderComponent, with different inputs, inside the Html in order to create several components.
I found this solution online where we build string and return as Html, using "id" and "getElementById" but I can't make it work.
 export function GrommetButtonEx() {
      return (

          <Grommet theme={grommetTheme}>
            <Sidebar
              border={{ color: "grey", size: "medium" }}
              width="340px"
              background={{ color: "black", opacity: "strong" }}
              style={{ borderRadius: "15px" }}
            >
              <Accordion style={{ color: "grey" }}>
                <AccordionPanel
                  style={{ height: "30px" }}
                  label={
                    <Text color="white" weight="bold" size="small">
                      Joint Position
                    </Text>
                  }
                >

                  {/* This works
                  <SliderComponent
                    sliderName={"slider 5"}
                    min={0}
                    max={17}
                    step={0.1}
                  />
                   */}
                </AccordionPanel>
              </Accordion>
            </Sidebar>
          </Grommet>

      );
    }

    window.onload = function () {
      var outputHTML = "";
      for (var k = 0; k < 5; k++) {
        outputHTML +=
          '<SliderComponent sliderName={"slider ' +
          k +
          '"} min={0} max={17} step={0.1}';
      }
      document.getElementById("output_div").innerHTML = outputHTML;
    };

I got the following error for:
TypeError: Cannot set properties of null (setting 'innerHTML')

at:
document.getElementById("output_div").innerHTML = outputHTML;
Is this the right way to do it, or is there a better way?

A: You should use the componentDidMount hook instead of onload.
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here (like in your case).
Read more about componentDidMount here - https://reactjs.org/docs/react-component.html#componentdidmount

A: In react you can write Javascript inside the "HTML" (This is called JSX). You don't have to write any Javascript logic outside the function component.
Also, you don't have to use innerHTML, instead, you have to write in JSX (inside the HTML), and make it return an instance of the component for each time the loop runs.
And to replace the "onload" you can use a hook called componentDidMount.
As for the question of how to write the loop logic in JSX (inside the HTML),  here is a link to a similar question.


text:
Q: How to know that property was changed from View My silverlight project uses MVVM.For examlpe, I have textbox, that binded to ViewModel property. Textbox content can change from View or ViewModel. I need know when content changed from View. How can I implement this accordingly MVVM?

A: If your viewmodel has INotifyPropertyChanged/INotifyPropertyChanging implemented then you can hook into it. That works for me.

A: if you use bindings, you get the information in your setter.
Here is a little example:
XAML:
<TextBox Text="{Binding MyProperty, Mode=TwoWay}" />

C# of your ViewModel:
private string myProperty = "Test";

        public String MyProperty
        {
            get { return myProperty; }
            set
            {
                Debug.WriteLine("Property set");
                myProperty = value;
                NotifyPropertyChanged("MyProperty");
            }
        }

Each time, you change the text and the TextBox looses the focus, the setter get called.
If you want to get the setter called each time you hit a key, have a look here. This is a little bit of a quick and dirty solution for triggering the binding ;) A better way would be to write an Behaviour for this.
Hope this helps!
BR,
TJ


text:
Q: Using an async predicate with `takeWhile` on an infinite generator Say I have the following generator that produces an infinite range:
const generateInfiniteRange = function* () {
  for (let i = 0; true; i++) {
    yield i;
  }
};
const infiniteRange = generateInfiniteRange();
const infiniteRange$ = from(infiniteRange);

I can do something like this with RxJS:
const predicate = i => i < 10;
infiniteRange$.pipe(
  takeWhile(predicate),
);

Now let's say that the predicate is asynchronous:
const predicate = async i => i < 10;

infiniteRange$.pipe(takeWhile(predicate)).subscribe(console.log);

How can I make this code work?
infiniteRange$.pipe(takeWhile(predicate));

I've tried using map as follows:
infiniteRange$.pipe(
  map(async i => ({
    i,
    predicateResult: await predicate(i),
  })),
  takeWhile(({predicateResult}) => predicateResult),
  pluck('i'),
);

but that just ends up mapping everything to a promise that always coerces to a truthy value, so everything passes through the takeWhile
I figured based on a previous question I've asked (for which originally I asked this question as an addendum in a comment of an answer, before deciding a question was more appropriate) that I could use concatMap, but that just generates an infinite emission before any of the internal observables hit the pipe.

A: If I understand this right, you can not achieve what you want.
The simple reason is that when, with from you create an Observable out of a generator, then you are creating a synchronous Observable, i.e. an Observable which emits all its values synchronously.
You can see clearly this looking at the fromIterable source code
function fromIterable<T>(iterable: Iterable<T>) {
  return new Observable((subscriber: Subscriber<T>) => {
    for (const value of iterable) {
      subscriber.next(value);
      if (subscriber.closed) {
        return;
      }
    }
    subscriber.complete();
  });
}

As you can see, the for loop is exited only when the subscriber is closed. But in our case the subscriber will be closed asynchronously, i.e. we need Node to stop the execution of the loop since no instructions are left and pick the next callback, the one that runs the predicate. This will never happen since the for loop will never end.
So the summary is that you can not have an async predicate working with a synchronous infinite stream of values, which is what you create using a Generator.
By the way, in order for the code to compile, you need to use concatMap to transform the value notified by the source stream to the Object used by the predicate. So a code that compiles is this one
infiniteRange$.pipe(
  tap(i => {
    console.log(i)
  }),
  concatMap(async i => {
    console.log('concatMap hit');
    return {
      i,
      predicateResult: await predicate(i),
    }
  }),
  takeWhile(({predicateResult}) => {
    console.log('takeWhile hit');
    return predicateResult
  }),
  pluck('i'),
).subscribe(console.log);

Running this snippet, you will see that you enter once in the concatMap input function (i.e. "concatMap hit" will be printed once) while you never enter the function passed to takeWhile (i.e. "takeWhile hit" will never be printed).
A SOLUTION WITH ASYNC GENERATORS
Actually, if you change the generator to be async, then using concatMap in the pipe we can reach the result you are looking for.
This is how the code would look like
const generateInfiniteRangeAsync = async function* () {
  for (let i = 0; true; i++) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    yield i;
  }
};

const predicate = async i => i < 10;

const infiniteRangeAsync = generateInfiniteRangeAsync();
const infiniteRangeAsync$ = from(infiniteRangeAsync);

infiniteRangeAsync$.pipe(
  concatMap(async i => {
    console.log('concatMap hit');
    return {
      i,
      predicateResult: await predicate(i),
    }
  }),
  takeWhile(({predicateResult}) => {
    console.log('takeWhile hit');
    return predicateResult
  }),
  pluck('i'),
)
.subscribe(console.log);

A: A simple solution, using iter-ops, which can handle asynchronous predicates out of the box:
import {pipeAsync, stop} from 'iter-ops';

// your infinite generator:
const generateInfiniteRange = function * () {
    for (let i = 0; true; i++) {
        yield i;
    }
};

// create our iterable:
const i = pipeAsync(generateInfiniteRange(), stop(async a => a >= 10));

// test:
(async function () {
    for await(const a of i) {
        console.log(a); //=> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    }
})();

P.S. I am the author of the library.


text:
Q: discord.py send_message usage I've started working on a project to accelerate my learning of python. I'm trying to recreate a discord bot I use quite a bit since i'm already use to its features. Below is my current code
import discord
from discord import User
from discord.ext.commands import Bot

import secrets

pybot = Bot(command_prefix = "!")

@pybot.event
async def on_read():
    print("Client logged in")

@pybot.command()
async def hello(*args):
    print(User.display_name)
    return await pybot.say("Hello, world!")

@pybot.command()
async def truck(*args):
    await pybot.send_message(message.user,'Watchout for that truck!')

pybot.run(secrets.BOT_TOKEN)

what im trying to get to happen is when someone types the command !truck <mention user> it sends a message to that mentioned user with the message "Watch out for that truck!".
I'm getting the following error:

Command raised an exception: NameError: name 'message' is not defined

I've tried looking up examples of what im trying to do but haven't found much, or am not understanding what I should be doing. Hopefully this isn't a repost of a similar question
Thanks.

A: The *args in your truck is no longer valid syntax I believe for the commands with discord.py
@pybot.command(pass_context=True)
async def truck(ctx):
    await pybot.send_message(ctx.message.user, 'Watchout for that truck!')

Checkout the github repository for Discord.py with their examples


text:
Q: Почему я не вижу public class? Есть сгенерированный public class. (из библиотеки grpc). Никак не могу его увидеть. Пытаюсь из класса GreetingClient достучатся до DummyServiceGrpc

Пытался импорты вручную прописать (и после перезагружал и ребилдил идею - помогает)

Это build.gradle
    plugins {
    id 'java'
    id 'com.google.protobuf' version '0.8.8'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    implementation 'io.grpc:grpc-netty-shaded:1.25.0'
    implementation 'io.grpc:grpc-protobuf:1.25.0'
    implementation 'io.grpc:grpc-stub:1.25.0'

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.10.0"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.25.0'
        }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
        }
    }
}

A: Нашел ответ, ваши комментарии помогли покапать в нужном напрвлении)
Только может мне кто-то может объяснить почему он не мог увидеть сгенерированные файлы, без этого (для общего развития)?
В build.gradle прописал
 sourceSets {
    main {
        java {
            srcDirs 'build/generated/source/proto/main/grpc'
            srcDirs 'build/generated/source/proto/main/java'
        }
    }
}


text:
Q: Create a copy of current workbook in current directory Below is a screengrab of a very basic version of the excel workbook I'm trying to create

The goal is to have the a Button that does the following things:

*

*Clicking on the Button creates a copy of this workbook, including
VBA

*The workbook needs to be saved in the same directory, with the
directory not being specific

*The name of the new copied workbook
needs to be taken from cells B6, then B7, then file extention . Ie.
in this example it would be "VW Golf 3RTY568.xlsm"

*In this newly created "VW Golf 3RTY568.xlsm" file, I want to clear
cell B2, B3 and B4 and cut&paste cell B6 and B7 to cell B3 and B4.
This part I have already got working through recording a macro

*The final requirement is that the new "VW Golf 3RTY568.xlsm"
workbook also has the same button element that performs step 1 to 4
So in short: clicking on the button needs to create a copy of the workbook (named after the Trade-in Car & License plate), and formats the cells so that the user can easily enter a new trade-in car and repeat the process by clicking the button.
The issue I am running into is in creating a copy of the workbook in the same directory, and ensuring that the copy (and all subsequent copies) have a functioning Button
This is my current code for creating a copy of the file, which already does not work correctly - it insteads create a copy in "/My Documents"
VBA Code:
Sub createnewWB()
    Dim thisWb As Workbook
    Dim newWBname As String

    newWBname = Range("B7")

    Set thisWb = ActiveWorkbook
    Workbooks.Add
    ActiveWorkbook.SaveAs Filename:=thisWb.Path & newWBname

End Sub

Sub buttoncalls()

Call createnewWB

End Sub

A: Something like this:
Sub Test()

    'Code that starts with a . refers to Sheet1 (With...End With)
    'e.g. .Range("B3") refers to Sheet1, while Range("B3") refers to the activesheet.
    With ThisWorkbook.Worksheets("Sheet1")

        .Range("B2:B4").ClearContents
        .Range("B6:B7").Copy Destination:=.Range("B3")

        ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & .Cells(6, 2) & .Cells(7, 2) & ".xlsm"

    End With

End Sub

If the workbook path is being synced with one-drive then your path may end up starting https in which case wrapping ThisWorkbook.Path with the function provided in this post seems to sort it out: Excel's fullname property with OneDrive.
I found the post by @PeterGSchild worked best for me.


text:
Q: Bluetooth peripheral connected to iOS doesn't work in the background I'm having an issue with a bluetooth peripheral working with a backgrounded iOS app. I need the app to respond to all bluetooth notifications in real-time. I've followed Apple's CoreBluetooth background process guide and it works around 10% of the time my app is backgrounded, but the other 90% of the time the events are queued and sent to my app in batches every 10 minutes.
I just need to fire a quick local subnet network request over wifi after a bluetooth event, so it takes well under the 10s iOS gives apps to work in the background.
As for CoreBluetooth settings, I followed the guide to the letter, and it does work in the background occasionally. But it also batches up notifications and re-launches my app every ten minutes, which makes me think it is configured correctly.
I can confirm the app isn't being killed. I can keep the debugger attached and it continues to run. In fact, the debugger shows that the notifications get queued and the app enters the foreground every ten minutes. It does work for a few minutes after I use the app. But it inevitably gets fully backgrounded.
I would expect the app to be woken up as soon as a bluetooth notification comes in. Checking the connected devices list in the iOS Settings > Bluetooth screen shows a connected peripheral. And it's clear iOS is capturing the notifications. But it rarely wakes the app to send the notifications.

UPDATE Aug 10th, 2016:
So the issue is not in the device itself. It stays connected and even iOS's Settings app shows the device is still connected. I realized though that I had beginBackgroundTaskWithExpirationHandler running on applicationWillResignActive, which was giving me pseudo-background activity. When I commented that out, the app no longer un-suspends on bluetooth notification from my device.
All of the bluetooth notifications are queued and all immediately fire when the app is re-launched manually. Debugging the app shows no activity when the app is in the background. So now it just looks like I haven't configured the app to correctly work with Bluetooth in the background.
So my hunch is that something is mis-configured in following the CoreBluetooth background doc. But there's only a few steps and I have implemented each of them. I would expect launchOptions?[UIApplicationLaunchOptionsBluetoothCentralsKey] to be sent to application(_:didFinishLaunchingWithOptions:), but it is never sent. And centralManager(_:willRestoreState:) is never called.
I have "Uses Bluetooth LE accessories" enabled.

I'm using CBCentralManagerOptionRestoreIdentifierKey:
manager = CBCentralManager(delegate: self, queue: nil, options:
                           [CBCentralManagerOptionRestoreIdentifierKey: "TTcentralManageRestoreIdentifier",
                            CBConnectPeripheralOptionNotifyOnDisconnectionKey: NSNumber(bool: true),
                            CBConnectPeripheralOptionNotifyOnConnectionKey: NSNumber(bool: true),
                            CBConnectPeripheralOptionNotifyOnNotificationKey: NSNumber(bool: true)])

I'm subscribing to the characteristic notification:
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
    if service.UUID.isEqual(CBUUID(string: DEVICE_V2_SERVICE_BUTTON_UUID)) {
        for characteristic: CBCharacteristic in service.characteristics! {
            if characteristic.UUID.isEqual(CBUUID(string: DEVICE_V2_CHARACTERISTIC_BUTTON_STATUS_UUID)) {
                peripheral.setNotifyValue(true, forCharacteristic: characteristic)
                let device = foundDevices.deviceForPeripheral(peripheral)
                device?.buttonStatusChar = characteristic
            } else if characteristic.UUID.isEqual(CBUUID(string: DEVICE_V2_CHARACTERISTIC_NICKNAME_UUID)) {
                peripheral.readValueForCharacteristic(characteristic)
            }
        }
    }
    ...
}

UIApplicationLaunchOptionsBluetoothCentralsKey is never called.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    ...
    let centralManagerIdentifiers = launchOptions?[UIApplicationLaunchOptionsBluetoothCentralsKey]
    if centralManagerIdentifiers != nil {
        print(" ---> centralManagerIdentifiers: \(centralManagerIdentifiers)")
    }
    ...
}

Finally, centralManager(_:willRestoreState:) is never called:
func centralManager(central: CBCentralManager, willRestoreState dict: [String : AnyObject]) {
    manager = central
    let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as! [CBPeripheral]
    print(" ---> Restoring state: \(peripherals)")
    ...
}

A: Figured it out. Let's play spot the bug...
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    var window: UIWindow?
    var bluetoothManager = TTBluetoothManager()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        ...
        return true
    }
    ...
}

See that var bluetoothManager = TTBluetoothManager() line? It should be a var bluetoothManager: TTBluetoothManager! and bluetoothManager = TTBluetoothManager() should be in application(_:didFinishLaunchingWithOptions:)
That did the trick and now my Bluetooth device runs in the background.

A: It should work. It works for me. Have you done the following?

*

*Check the "Uses Bluetooth LE accessories" background mode option.

*Adding the "CBCentralManagerOptionRestoreIdentifierKey" when creating the manager.

*Subscribe to characteristic notifications using: setNotifyValue:forCharacteristic:.

If not, then something is wrong. Perhaps try and init the manager on a dedicated dispatch queue just to make sure that the current queue is blocked for some reason.
If you show some code then I might be able to help out better. As I said, I know for a fact that it should work.
/A


text:
Q: Converting bare git repository into a copy where I can see the files I need to convert a local bare git repository to another form where I can see the actual files. My repository is roughly 13.5GB in size. Essentially, the repository is in a state in which it would be if it were hosted on a remote server.
I have a repository structure like the following:
- gitrepo
  - repo
    -branches
    -hooks
    -info
    -objects
    -refs
    -HEAD (file)
    -Description (file)
    -config (file)

When inspecting the folder in git bash, the gitrepo folder is master, and the repo folder is BARE:master.
I understand the git-clone command should be used to complete this action, but, when I git-clone each of the gitrepo and repo folders to another directory, I get the message saying I have cloned an empty directory.


text:
Q: Cloud composer detect container finished running I am using the bash operator in order to schedule a container to run on a compute instance.
gcloud beta compute instances create-with-container airflow-vm --zone us-central1-a --container-image gcr.io/cloud-marketplace/google/image-which-does-calculations:1.0

The container automatically starts a process to do some calculations. How Can I detect that the process has completed it's calculations?


text:
Q: gettext not translating all utf-8 characters test.php file echoes some greek letters for testing
<head>
<meta charset = "UTF-8" />
</head>
<?php
$language = "en_US";
$lang_path = "language";
putenv("LC_ALL=$language");
setlocale(LC_ALL, $language);
bindtextdomain("lang", $lang_path);
bind_textdomain_codeset("lang","UTF-8");
textdomain("lang");
echo gettext("α");
echo gettext("β");
echo gettext("γ");
echo gettext("δ");
echo gettext("ε");
echo gettext("ζ");
?>

My folders and files are structured like
 language/en_US/LC_MESSAGES/lang.mo and lang.po

mo file is correctly compiled, and it must translate to abcdez. In poedit i have used utf-8 everywhere. The code produces αβcδεζ , so only letter c is translated! I have restarted my server, i have en_US encoding installed in my system and i can't understand why only one letter is translated..

A: A simple implementation i wrote reading zend and cakephp code. It does not support plurals, and it simply replaces words, so you can replace not only from one language.
test.php file
<head>
<meta charset = "UTF-8" />
</head>
<?php
    require_once "gettext.php";
    echo __("something");
    echo __("α");
    echo __("β");
    echo __("γ");
    echo __("δ");
    echo __("ε");
    echo __("ζ");
?>

gettext.php file
<?php
define('APPPATH','/opt/lampp/htdocs/test/');
/* please change APPPATH to an ultimate directory of the language folder */

/**
 * Loads the binary .mo file and returns array of translations
 *
 * @param string $filename Binary .mo file to load
 * @return mixed Array of translations on success or false on failure
 */
    function loadMo($filename) {
        $translations = false;

        // @codingStandardsIgnoreStart
        // Binary files extracted makes non-standard local variables
        if ($data = file_get_contents($filename)) {
            $translations = array();
            $header = substr($data, 0, 20);
            $header = unpack("L1magic/L1version/L1count/L1o_msg/L1o_trn", $header);
            extract($header);

            if ((dechex($magic) == '950412de' || dechex($magic) == 'ffffffff950412de') && $version == 0) {
                for ($n = 0; $n < $count; $n++) {
                    $r = unpack("L1len/L1offs", substr($data, $o_msg + $n * 8, 8));
                    $msgid = substr($data, $r["offs"], $r["len"]);
                    unset($msgid_plural);

                    if (strpos($msgid, "\000")) {
                        list($msgid, $msgid_plural) = explode("\000", $msgid);
                    }
                    $r = unpack("L1len/L1offs", substr($data, $o_trn + $n * 8, 8));
                    $msgstr = substr($data, $r["offs"], $r["len"]);

                    if (strpos($msgstr, "\000")) {
                        $msgstr = explode("\000", $msgstr);
                    }
                    $translations[$msgid] = $msgstr;

                    if (isset($msgid_plural)) {
                        $translations[$msgid_plural] =& $translations[$msgid];
                    }
                }
            }
        }
        // @codingStandardsIgnoreEnd

        return $translations;
    }

    /*
        Your system folder must be ULTIMATE_PATH/language/$language
        where language is a parametre like en,el,fr or english or whatever
        domain is the name of the mo file without mo extension e.g. default
        You can pass this parameteres with the __ function below
    */
    function translate($singular, $language = null, $domain = null) {
        $directory = APPPATH."language/"; // your path to language folder
        if (strpos($singular, "\r\n") !== false) {
            $singular = str_replace("\r\n", "\n", $singular);
        }

        if (is_null($language) ) { // default el
            $language = "el";
        }

        if (is_null($domain)) {
            $domain = "default";
        }

        $localeDef = $directory . $language;
        $file = $localeDef."/".$domain;
        $translations = null;

                if (is_file($file . '.mo')) {
                    $translations = loadMo($file . '.mo');
                }

        if (!empty($translations[$singular])) {

                $trans = $translations[$singular];

                if (strlen($trans)) {
                    return $trans;
                }
            }

        return $singular;
    }
    /*
    take language (must be in language folder) from $_GET["lang"];
    */
    function __($singular) {
        if (!$singular) {
            return;
        }
        if (isset($_GET["lang"]) ) // you can use cookie, session etc
            $translated = translate($singular,$_GET["lang"]);
        else
            $translated = translate($singular);
        return $translated;
    }
?>

In my code i have default language el, and you get the language with GET['lang']. (You can change that to a COOKIE, SESSION etc. Also the mo files must be called default.mo. (You can change that also in the code). So you can have in your directory:
test.php
gettext.php
language/el/deafult.mo
language/en/default.mo

default is el/default.mo and you can change to en with ?lang=en in your url.


text:
Q: RedirectToAction with complex-type parameters I can't figure out how to send DTOs via a redirect.
I've tried everything I could find in both this Question and this documentation.
How can I accomplish this?
Below is a record of what I've tried and the results:
public ActionResult Create(ComRuleCompoundKeyDto ruleKey)
{
    var dto = new ComRuleOverrideDto()
    {
        Company = 42
    };

Sends null dtos:
    //var routeValues = new RouteValueDictionary
    //{
    //    { "ruleKey", ruleKey },
    //    { "dto", dto },
    //};
    //return RedirectToAction(nameof(MaintainOverride), routeValues);

Sends StupidDto filled with null:
    //var routeValues = new RouteValueDictionary(new StupidDto
    //{
    //    ruleKey = ruleKey,
    //    dto = dto
    //});
    //return RedirectToAction(nameof(MaintainOverride), routeValues);

Sends dtos filled with default values:
    //ControllerContext.RouteData.Values.Add("ruleKey", ruleKey);
    //ControllerContext.RouteData.Values.Add("dto", dto);
    //return RedirectToAction(nameof(MaintainOverride));

Sends null dtos:
    //return RedirectToAction(nameof(MaintainOverride), new { ruleKey, dto });

System.InvalidOperationException: The view 'create' or its master was not found or no view engine supports the searched locations:
    //return MaintainOverride(ruleKey, dto);

    return null;
}

public ActionResult MaintainOverride(ComRuleCompoundKeyDto ruleKey, ComRuleOverrideDto dto)
{
    var currencies = _srv.GetAllCurrenciesUsedByDealers().Select(x => x.CurrencyCode);

    var custTypes = _srv.GetAllCustomerTypes();
    var unitIds = _srv.GetUnitIds();
    var vm = new OverridesViewModel(currencies, custTypes, unitIds, ruleKey, dto);

    return View(vm);
}

public class StupidDto
{
    public ComRuleCompoundKeyDto ruleKey;
    public ComRuleOverrideDto dto;
}

A: I managed to get it to work by explicitly setting the View's name (nameof(MaintainOverride)) when returning another action (as opposed to redirecting).
public ActionResult Create(ComRuleCompoundKeyDto ruleKey)
{
    var dto = new ComRuleOverrideDto()
    {
        Company = 42
    };

    return MaintainOverride(ruleKey, dto);
}

public ActionResult MaintainOverride(ComRuleCompoundKeyDto ruleKey, ComRuleOverrideDto dto)
{
    var currencies = _srv.GetAllCurrenciesUsedByDealers().Select(x => x.CurrencyCode);

    var custTypes = _srv.GetAllCustomerTypes();
    var unitIds = _srv.GetUnitIds();
    var vm = new OverridesViewModel(currencies, custTypes, unitIds, ruleKey, dto);

    return View(nameof(MaintainOverride), vm);
}


text:
Q: Perl Hash of Hashes Issue I've seen similar questions asked on here ad nauseum but none of those could answer my own question specifically.
I am trying to programatically create a hash of hashes. My problem code is as follows:
my %this_hash = ();
if ($user_hash{$uuid})
{
    %this_hash = $user_hash{$uuid};
}

$this_hash{$action} = 1;

$user_hash{$uuid} = %this_hash;
my %test_hash = $user_hash{$uuid};
my $hello_dumper = Dumper \%this_hash;

According to my output, $this_hash is being assigned properly but
$user_hash{$uuid} = %this_hash

is showing a value of 1/8 in the debugger; not sure what his means. I'm also getting a warning: "odd number of elements in hash assignment..."

A: It's not really a "hash of hashes"; it's a "hash of references to hashes".
Try:
$user_hash{$uuid} = \%this_hash;

A: Any time you write
%anything = $anything

you're doing something wrong. Almost any time you write
$anything = %anything

you're doing something wrong. That includes when $anything is an array or a hash access (i.e. $array[$index] or $hash{$key}). The values stored in arrays and hashes are always scalars, and arrays and hashes themselves aren't scalars. So, when you want to store a hash in a hash, you store a reference to it: $hash{$key} = \%another_hash. And when you want to access a hash that's had a reference to it stored in a hash, you dereference: %another_hash = %{ $hash{$key} } or $hashref = $hash{$key}; $value = $hashref->{ $another_key } or $value = $hash{$key}{$another_key}.
For getting up to speed with references I strongly recommend reading the Perl References Tutorial and the Perl Data Structures Cookbook.


text:
Q: Safely rename branch in TFS 2015 I have a branch created in TFS 2015 that has a lot of work already done, but not yet checked-in.  However, I need to rename the branch now, but I don't want to have to lose or reapply existing updates in order to do so.
Is there a way to safely change the branch name without losing any work?

A: Is there a reason you don't want to checkin before the rename? That sounds like the safest approach.
If not, I would create a shelveset as a backup before renaming. Then when you unshelve you might need to use the TFS Power Tools to do a tfpt unshelve /migrate.