text:
Q: SyntaxWalker Visitor doesn't visit Methods I got this walker
internal class MyWalker : CSharpSyntaxWalker
{
            public int MethodCount { get; private set; }

    public MyWalker() : base(Microsoft.CodeAnalysis.SyntaxWalkerDepth.Trivia)
    { }

    public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
         MyMethodCount ++;
    }

    public override void VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        Class++;
        Complexity++;
    }
}

I call the walker with this code
    var code = @"
    public class foo
    {
        public void MyMethod()
        {

        }
    }
";

  SyntaxTree node = CSharpSyntaxTree.ParseText(source);
  var root = node.GetRoot();

  var walker = new MyWalker();
  walker.Visit(root);

but the visit MethodDeclaration is never called.
To get sure I compared with the SyntaxTree Analyzer I can see that roslyn should recognize it as Method declaration.

What am I missing?

A: I found it. I didn't have the base call in the visit class method. so just a bug of mine
so it should be
   public override void VisitClassDeclaration(ClassDeclarationSyntax node)
        {
[...]
            base.VisitClassDeclaration(node); // this was missing
        }


text:
Q: Polygons to lines in PostGIS? I have a Postgis table containing land parcels as polygons. These land parcels have boundaries defined by hedges, walls, fences etc. I would like to create a table of the individual boundary components for further survey and evaluation. The first step to this would be cutting the polygon boundaries into strings at each node.
It looks like ArcMap can do this using the "Polygon To Line" function (http://desktop.arcgis.com/en/arcmap/10.3/tools/data-management-toolbox/polygon-to-line.htm) but I can't find anything equivalent in Postgis or QGIS.
Any suggestions?

A: Here is what we can do,

*

*Create a GeometryCollection with one polygon using the ST_Polygonize aggregate. This is our test data.

*Access the first element of the GeometryCollection with ST_GeometryN(geom,1). If your input is already a polygon, you'll pick up from here.

*Extract the boundary with ST_Boundary. The boundary is a LINESTRING.

*Decompose that LINESTRING into points using ST_PointN, and using those points as arguments to ST_MakeLine
It looks like this,
SELECT ST_AsText(ST_Boundary(ST_GeometryN(ST_Polygonize(l),1)))
FROM ( VALUES
  ( ST_MakeLine(ST_MakePoint(5,0),ST_MakePoint(0,0)) ),
  ( ST_MakeLine(ST_MakePoint(0,0),ST_MakePoint(0,5)) ),
  ( ST_MakeLine(ST_MakePoint(0,5),ST_MakePoint(5,5)) ),
  ( ST_MakeLine(ST_MakePoint(5,5),ST_MakePoint(5,0)) )
) AS t(l);
            st_astext
---------------------------------
 LINESTRING(5 0,0 0,0 5,5 5,5 0)
(1 row)

Now we have to decompose the boundary into 2-point line strings. First we move the aggregate into an inner-select
SELECT ST_AsText(b)
FROM (
  SELECT ST_Boundary(ST_GeometryN(ST_Polygonize(l),1)) AS b
  FROM ( VALUES
    ( ST_MakeLine(ST_MakePoint(5,0),ST_MakePoint(0,0)) ),
    ( ST_MakeLine(ST_MakePoint(0,0),ST_MakePoint(0,5)) ),
    ( ST_MakeLine(ST_MakePoint(0,5),ST_MakePoint(5,5)) ),
    ( ST_MakeLine(ST_MakePoint(5,5),ST_MakePoint(5,0)) )
  ) AS t(l)
) AS i(b);

Then we recompose simple lines,
SELECT ST_AsText(ST_MakeLine(
  ST_PointN(b.geom,gs.pt),
  ST_PointN(b.geom,gs.pt+1)
))
FROM (
  SELECT ST_Boundary(ST_GeometryN(ST_Polygonize(l),1)) AS b
  FROM ( VALUES
    ( ST_MakeLine(ST_MakePoint(5,0),ST_MakePoint(0,0)) ),
    ( ST_MakeLine(ST_MakePoint(0,0),ST_MakePoint(0,5)) ),
    ( ST_MakeLine(ST_MakePoint(0,5),ST_MakePoint(5,5)) ),
    ( ST_MakeLine(ST_MakePoint(5,5),ST_MakePoint(5,0)) )
  ) AS t(l)
) AS b(geom)
CROSS JOIN LATERAL generate_series(1,ST_NPoints(b.geom)-1) gs(pt);

That returns..
      st_astext
---------------------
 LINESTRING(5 0,0 0)
 LINESTRING(0 0,0 5)
 LINESTRING(0 5,5 5)
 LINESTRING(5 5,5 0)
(4 rows)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where should I ask "X"? If I'm not sure what Stack Exchange site to ask a question on, what's the recommended protocol? Do I ask the meta-question here on meta.stackoverflow.com? It looks like there are several "Where should I ask..." questions here, and the FAQ doesn't really cover this area.

A: Asking here is fine. As I mentioned in my comment, either somebody will be able to give you a definitive answer, or at least will point you to a site-specific meta if it's hard to tell 100% if your question would belong on that site. You can then get further clarification there if needed.
We even have a tag dedicated to this entire concept; tag your question here with site-rec!

A: I'd start by browsing the directory:
https://stackexchange.com/sites
There's a fairly succinct definition of each site there.
While there are some grey areas of overlap between sites (the example I always use is URL rewriting questions, which could be on SO, SF, or even Webmasters), it's not too difficult to resolve by asking yourself "what's my job title" or "what professional hat do I usually wear?" and ask it of that community.
In other words, if you have a question about motorcycles, you don't start yelling out your question on crowded street corners hoping someone will answer. You go to the place where motorcyclists hang out, first...


text:
Q: Django request/response multithreading The workflow of my app is -
User submits a file
On receiving -> process_file()
return response

This could result in timeouts if the process_file() takes much time, so how could I send back the response before and then process the file and send the desired output to user later.
I have checked out django-celery but I think it's quite heavy for a small app which I am trying to build.
Update: I searched a bit around on the internet, and if anyone would like to use celery, here is a nice blog post, that could help you solve this situation - [Link]

A: You can use Celery for that matter:

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.
The execution units, called tasks, are executed concurrently on a single or more worker servers using multiprocessing, Eventlet,   or gevent. Tasks can execute asynchronously (in the background) or synchronously (wait until ready).


text:
Q: Who lived in Barad-dûr? Barad-dûr was a stupendously tall tower in Mordor and home to the Dark Lord Sauron.
Apart from the big man himself, who actually lived there, though? It's hard to imagine such a huge building lying largely empty. Were there orcs who were assigned to stay there? I'd include people who worked in Barad-dûr or those who stayed there from time to time as well as any permanent residents. I have no specific time period in mind.

A: As a small addition to Victim of Circumstance's answer, from thelandofshadow.com:

The tower was full of treasure, weapons, armor, materials, great stores, barracks for the footsoldiers of the tower (on the lower levels), and rooms for high-ranking captains like the Mouth of Sauron.

From tolkiengateway.com:

Around T.A. 1050 Sauron returned and secretly made a stronghold at Dol Guldur.[3] Gandalf did not discover that Sauron was the master of Dol Guldur until T.A. 2850, and in T.A. 2941 the White Council attacked the fortress. Sauron retreated to Barad-dûr, which the Nazgûl had prepared for him, and began to rebuild it in T.A. 2951. From then on Sauron stayed in Barad-dûr and conducted his war on the free people of Middle-earth from there.

A: Orcs
From The Two Towers, Book III, Chapter 9, "Flotsam and Jetsam":

'All this about the Orcs of Barad-dûr, Lugbúrz as they call it, makes me uneasy,' said Aragorn.

The books are full of other references, particularly to the name Lugbúrz, and it's clear that in addition to Orcs the high command of Sauron's forces also dwell there.  For example, from the earlier chapter "The Uruk-hai":

'You seem to know a lot,' said Ugluk. 'More than is good for you, I guess. Perhaps those in Lugbúrz might wonder how, and why.'


text:
Q: Модификатор "i" не работает в регулярном выражении Опять проблема с регулярными выражениями в PHP. Собственно код:

<?
$sw="аромат";
$pattern="#.*$sw.*#i";
$v="АрОмАт";
preg_match_all($pattern, $v, $matches);
print_r($matches);
?>

Результат:
Array ( [0] => Array ( ) )

Другими словами модификатор "i" не работает. У кого-нибудь такое бывало?
A: Попробуй:
$pattern = '/.*' . preg_quote($sw) . '.*/iu';


text:
Q: Best way to implement a dict with a fixed key type (e.g. an Enum type)? The Setting
I have a data object that comprises a number of properties, let's say:
FaceProperties( eye_color:EyeColorEnum, has_glasses:bool,
                nose_length_mm:float, hair_style:str )

*

*All of these are optional, so instances may only define a subset of them.

*For each single version of the software, there is a fixed set of supported properties (trying to set/get any other would be an implementation error)

*It is quite likely that I need to add a new one to future versions every now and then

What happened so far
In principle, I would very much like to collect them in a dict, so that I can do all the nice things one can do with a dict (extend with new keys, iterate over, access by key...). However, an ordinary dict (and linter) would not notice when an unsupported key is used, e.g. due to some typo, especially with keys that are strings.
Due to these concerns, I started the project using an ordinary class with ordinary properties and implemented all the generic stuff  (iteration etc) manually.
Are there better options?
I am currently refactoring the software, and started wondering if a map with a fixed key type (for which I could use a SupportedProperties Enum) would solve my problem better, and if there is such a thing in python.
Now, I can simply use the Enum values as keys with an ordinary dict and probably be reasonably fine, but it would be even nicer if there was some specialized dict class that would not even accept keys of other types.
Is there maybe some collection (preferably a builtin one) I could use for that? Or would I have to derive my own class from UserDict and do the type checking myself?

A: How about dataclasses (Python 3.7+)?
from enum import Enum
from dataclasses import dataclass, asdict

class EyeColorEnum(Enum):
    BLUE = 1
    RED = 2

@dataclass()
class FaceProperties:
    eye_color: EyeColorEnum = None
    has_glasses: bool = None
    nose_length_mm: float = None
    hair_style: str = None

fp = FaceProperties(eye_color=EyeColorEnum.BLUE)
print(fp)
print(asdict(fp))

outputs
FaceProperties(eye_color=<EyeColorEnum.BLUE: 1>, has_glasses=None, nose_length_mm=None, hair_style=None)
{'eye_color': <EyeColorEnum.BLUE: 1>, 'has_glasses': None, 'nose_length_mm': None, 'hair_style': None}

A: As others have mentioned in the comments, all you need is one check to ensure that the key is in a certain set of values:
class FixedKeyDict(dict):
    def __init__(self, *args, allowed_keys=(), **kwargs):
        super().__init__(*args, **kwargs)
        self.allowed_keys = allowed_keys

    def __setitem__(self, key, value):
        if key not in self.allowed_keys:
            raise KeyError('Key {} is not allowed'.format(key))
        super().__setitem__(key, value)

Now give it a list of the allowed values:
hair_dict = FixedKeyDict(allowed_keys=('bald', 'wavy', 'straight', 'mohawk'))

This only overrides the [] operator though, you want to subclass UserDict like you've said and override all the other methods too, but you get the idea. Regardless, you must implement it yourself, such thing doesn't exist in the standard library.


text:
Q: How to use when statement in ansible Can anyone check the script? I don't know why the "when" statement failed.

ok: [labvMME01] => {
      "msg": [
          "Wait!",
          "Exported result: /tmp/DPE_CORE/home/jackl/ConfigFile_from_export"
      ]
  }*******************************************************************
  fatal: [labvMME01]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'path' is undefined\n\nThe error appears to

- name: mme command
  shell: gsh export_config_active
  register: command_result

- name: check result
  debug: msg="{{command_result.stdout_lines}}"

- name: get the path of the config file
  set_fact: path="{{command_result.stdout_lines}}"
  when: '"Exported" in command_result.stdout_lines'
- debug: msg="{{path}}"

A: Please try as below.
- name: get the path of the config file
  set_fact: path="{{command_result.stdout}}"
  when: '"Exported" in command_result.stdout'


text:
Q: How to specify a local source for Install-Package My goal is conveniently adding my own library to my projects within my local network. I put the library in a SMB shared directory.
Get-Package -Source \\my\share\nuget -ListAvailable

showed the package. But when I tried
Install-Package ClassLibrary1 -Source \\my\share\nuget

VS ignored that source because of transient management or something and installed it from nuget.org. I searched the web and found this existing question, but adding that SMB share to VS's source list (after nuget.org) did not work because it still get it from nuget.org. I tried to specify the source like
Install-Package ClassLibrary1 -Source Local

where "Local" was the name I used in VS, but it did not work either. How can I make a local source work within my local network?

A: From this link we can see that:

The URL or folder path for the package source to search. Local folder
paths can be absolute, or relative to the current folder. If omitted,
Install-Package searches the currently selected package source.

\\my\share\nuget is a UNC path. So this path format doesn't work for "-source":

You can uncheck nuget.org in package sources, clear the nuget cache and then use this command to install the package.


text:
Q: Intersection multiplicity of two curves. I want to compute the intersection multiplicity of $YZ=X^2$ and $YZ=(X+Z)^2$ at $P=(0:1:0)$
In an affine nbd of $P$, let $(X:Y:Z)=(x:1:z)$
$$I_P=\dim \mathcal{O}_{\mathbb{A}_k^2,(0,0)}/(x^2-z,x^2+2xz+z^2-z)$$
In my previous question, I learned that if $(0,0)$ is the only zero, I can change the local ring to $k[x,z]$. But the problem occurs since there are intersection points not only $(0,0)$, but also $(-2,4)$. I saw the Fulton's book(section 2.9 prop 6), which says that $$k[x,z]/I \simeq \mathcal{O}_{(0,0)}/I\mathcal{O}_{(0,0)} \times \mathcal{O}_{(-2,4)}/I\mathcal{O}_{(-2,4)}$$
So now how can I compute the intersection multiplicity?

A: That there are multiple points of intersection does not really affect your calculation. In order to compute the intersection multiplicity at $P,$ we must pass to the local ring, which forgets other intersection points. Thus, you can compute $$I_P=\dim_k k[x,z]_{(x,z)}/(z-x^2,z-(x+z)^2)_{(x,z)},$$
i.e. we can localize $k[x,z]$ at the prime $(x,z)$ and then take the quotient. Of course, localization commutes with quotients, so we have
$$I_P=\dim_k (k[x,z]/(z-x^2,z-(x+z)^2))_{(x,z)}=\dim_k (k[x]/(x^2-(x+x^2)^2))_{(x)}=\dim_k (k[x]/(x^3(-2-x)))_{(x)}=\dim_k k[x]/(x^3)$$
since $-2-x$ is a unit in the localization $k[x]_{(x)}$. This shows that the multiplicity is $I_P=3.$


text:
Q: 'Vector' operating on many vectors to minimize scalar function. How do I minimize it with respect to this 'vector'? I've done optimization before, but today I'm trying to do some exact nonlinear optimization in a problem with 2 vector spaces. I do not yet see a parallel for this in matrix operations if there is one. I've really tried looking for this online and here, but I don't know what to call the construction I've made.
Here is a minimal example. Say you have just N=4 vectors that are all in $\mathbb{R}^3$:
$A = \langle 1, 2, 3\rangle$
$B = \langle 4, 5, 6\rangle$
$C = \langle 7, 8, 9\rangle$
$D = \langle 10,11,12\rangle$
I am finding a M-dimensional 'vector' $X$ (an array of scaling parameters) that minimizes another scalar function, by solving a system of nonlinear equations that each involve a few elements in $X$, and each element in this 'vector' operates on the above vectors.
$X = [x_0, x_1, x_2]$
Example scalar, polynomial objective function to get the idea, not my real function which is 2000+ characters when written concisely with sigma notation:
$f(X, A, B, C, D) = (x_0 A) \cdot (x_1 B) + (x_1 B) \cdot (x_2 C) + (x_2 C) \cdot (x_0 D)$
I also have vectors in the function I need to do dot products with, of a form like $(x_0 A) + (x_1 B)$, which are functions of $X$, $A$, $B$, $C$, and $D$.
Now I'm having to solve the gradient of, say, $(x_0 A) + (x_1 B)$ with respect to the M dimensions of X, and I don't know if I'm breaking any rules. So in this example I would like to know... is $\nabla ((x_0 (A \cdot B)) + (x_1 (C \cdot D)))$ equal to $[(A \cdot B), (C \cdot D), 0]$ or no? And is it still even true that $\nabla (V \cdot V) = 2 V \cdot \nabla V$ in this use-case?

EDIT: It looks like the gradient with respect to $X$works out. Not a proof of course, but this example seems to work...
Assume $\nabla (V \cdot V) = 2 V \cdot \nabla V$
$\nabla ( (x_0 A + x_1 B) \cdot (x_0 A + x_1 B) ) = 2 (x_0 A + x_1 B) \cdot \nabla (x_0 A + x_1 B)$
$ \nabla ( x_0^2 A \cdot A + 2 x_0 x_1 A \cdot B + x_1^2 B \cdot B) = 2 (x_0 A + x_1 B) \cdot \langle A, B, 0 \rangle)$
$\langle 2 x_0 A \cdot A + 2 x_1 A \cdot B, 2 x_0 A \cdot B + 2 x_1 B \cdot B, 0 \rangle = 2 \langle x_0 A \cdot A + x_1 B \cdot A, x_0 A \cdot B + x_1 B \cdot B, 0 \rangle$
$2 \langle x_0 A \cdot A + x_1 A \cdot B, x_0 A \cdot B + x_1 B \cdot B, 0 \rangle = 2 \langle x_0 A \cdot A + x_1 A \cdot B, x_0 A \cdot B + x_1 B \cdot B, 0 \rangle$

But my main question here is, can someone tell me what branch of mathematics this $X$ 'vector' is in?
UPDATE: Using the gradient is working, but I'd still like to know what branch of mathematics this is because $(x_0 A + x_1 B) \cdot \langle A, B, 0 \rangle$ looks unlike anything I've seen before. I have not yet thought of a better way to rewrite these expressions either.


text:
Q: Pointer indirection with an array I'm trying to have three levels of pointer indirection with an additional pointer pointing to level two of the indirection. This is for a class, and I'm having some real issues. This is what I'm doing.
int ***s = new int **[row];
*s = new int *[row];
**s = new int[row];

Now if these where just int and not arrays I could do,
***s = 1;

To store it into the yellow square on my picture, but I don't know how to access the array elements, I have tried a few things and it either crashes or will not compile. Any help, even pointing me in the right direction would be very useful. Thank you.

A: You've created something like this (assume row is 2 and type T):

                           T***
                          +-----+
                          |     |
                          +--/--+
                            /
                           / T**
                       +--/--+-----+
                       |     |     |
                       +-----+--+--+
                       -/       |
                    --/      T* |
                +--/--+-----+ +-+---+-----+
                |     |     | |     |     |
                +-----+-----+ +--+--+-----+
            ----/      -/        |      \---
      -----/        --/      T   |          \--
  +--/--+-----+ +--/--+-----+ +--+--+-----+ +--\--+-----+
  |     |     | |  X  |     | |     |     | |     |     |
  +-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+

Every node would point to the next level's first node. Dereferencing every level would give the level next but you've to also take care of the index of the element in the array you want to reach. This, I see, isn't done in your code. For scalars you dereference using * while for arrays the array index syntax does dereferencing too apart from choosing the right element. * on arrays would just get you the first element always.
To access X in the above figure you'd do
T** v = u[0];
T* w = v[1];
T x = w[0];
// shorthand for above
x = u[0][1][0];

To just have an array at the last level, you should be doing this
int*** p = new int**;
*p = new int*;
**p = new int[row];

This would just give you █ → █ → █ → █ █ █ …, where p itself (the first box) is an automatic variable (usually stored in the stack space) and rest comes from the freestore (usually living in the heap).
Live example.

A: Let's say row = 3 for this example.
int ***s;
// s=[?]
// s is an uninitialized variable.

s = new int **[row];
// s[*] -> [?]
//         [?]
//         [?]
// s points to the first element of an array of size 3.
// The elements are uninitialized.

*s = new int *[row];
// s=[*] -> [*] -> [?]
//          [?]    [?]
//          [?]    [?]
// We've initialized s[0]. It points to another array of size 3.
// All elements of that array are also uninitialized, along with s[1] and s[2].

**s = new int[row];
// s=[*] -> [*] -> [*] -> [?]
//          [?]    [?]    [?]
//          [?]    [?]    [?]
// More of the same. s[0][0] is initialized.
// This last array contains uninitialized ints, not pointers.

***s = 1;
// s=[*] -> [*] -> [*] -> [1]
//          [?]    [?]    [?]
//          [?]    [?]    [?]
// We traverse three levels of pointers (->) and store 1 in the cell.

All of this should compile and work fine (as long as you don't access any of the uninitialized elements).

s + 1 points to the second element of the first array.
// s=[*] -> [*] -> [*] -> [1]
// s + 1 -> [?]    [?]    [?]
//          [?]    [?]    [?]

*(s + 1) refers to the cell [?] pointed to by s + 1 in the diagram above. This cell is uninitialized.
**(s + 1) tries to dereference a garbage pointer, which is invalid (and often crashes).


text:
Q: How do I wait for multiple semaphores using dispatch on Mac? On Windows, I am using WaitForMultipleObjects() to wait for multiple semaphores using the following code.
DWORD waitobject = WaitForMultipleObjects( cnt, semaphores, false, INFINITE );

return waitobject - WAIT_OBJECT_0;

I tried using dispatch_semaphore_wait() on Mac without success using the following code.
while( true )
    for( int = 0;  i < semaphoreCnt;  ++i )
        if( dispatch_semaphore_wait( semaphores[ i ], DISPATCH_TIME_NOW ) == 0 )
            return i;

It keeps waiting and never finishes. Any ideas why?
What I am trying to achieve is that the code wait for one of the given semaphores is signalled and give back which one.

A: I mean the code, as written should work - if I plug it into a very simple objective-c program it behaves as expected:
#import <Foundation/Foundation.h>
#import <pthread.h>

int wait_on_a_sema(int sema_count, dispatch_semaphore_t __strong *sema)
{
    while (true) {
        for (int i = 0; i < sema_count; i++) {
            if (dispatch_semaphore_wait(sema[i], DISPATCH_TIME_NOW) == 0) {
                return i;
            }
        }
    }
}

void* PosixThreadMainRoutine(void* data)
{
    // Do some work here.
    sleep(5);
    dispatch_semaphore_signal((__bridge dispatch_semaphore_t)data);
    return NULL;
}

void LaunchThread(dispatch_semaphore_t __strong sema)
{
    // Create the thread using POSIX routines.
    pthread_attr_t  attr;
    pthread_t       posixThreadID;
    int             returnVal;

    returnVal = pthread_attr_init(&attr);
    assert(!returnVal);
    returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    assert(!returnVal);

    int     threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, (__bridge void *)sema);

    returnVal = pthread_attr_destroy(&attr);
    assert(!returnVal);
    if (threadError != 0)
    {
         // Report an error.
    }
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        dispatch_semaphore_t sems[10];
        for (int i = 0; i < 10; i++) {
            sems[i] = dispatch_semaphore_create(0);
        }
        NSLog(@"Hello, World!");
        int item = arc4random_uniform(10);
        LaunchThread(sems[item]);
        int ret = wait_on_a_sema(10, sems);
        NSLog(@"%d - %d", ret, item);
    }
    return 0;
}

I can even alter the wait function to display a form of progress -
time_t start_time = time(0);
uint64_t loopcount = 0;
while (true) {
    loopcount++;
    time_t curr_time = time(0);
    if (curr_time > start_time) {
        NSLog(@"LoopCount: %llu", loopcount);
        start_time = curr_time;
    }

And you can see it display the significant number of times the loop is gone through in the 5 seconds.


text:
Q: Ошибка при отправке ajax-запроса Есть Api, запускается в vs 2017 Ctrl+F5, так же на локальном IIS есть фронтенд.
По нажатию на Войти должен приходить токен.
Проверяю в постмене - все работает:.
код ajax с postman:
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://localhost:44311/api/user/login",
  "method": "POST",
  "headers": {
    "Content-Type": "application/json",
    "cache-control": "no-cache",
    "Postman-Token": "49834433-34a0-4c59-9593-8ea5bd8515b2"
  },
  "processData": false,
  "data": "{\n\t\"UserName\":\"MARS\",\n\t\n\t\"PasswordHash\":\"123qweASD!\"\n}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

результат:

теперь тоже самое но с ajax запроси по нажатию кнопки войти:
       $.ajax({
            async: true,
            crossDomain: true,
            url: "https://localhost:44311/api/user/login",
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "cache-control": "no-cache",
                "Postman-Token": "c236d8f2-4ef0-4187-bfea-494d032e179a",
                // "Access-Control-Allow-Credentials": "true"
            },
            processData: false,
            dataType: 'json',
            data: { "UserName": "MARS", "PasswordHash": "123qweASD!" },
            success: function (res) {
                alert(res);
            },
            error: function () {
                alert("error.");
            }
        });

ошибки:
 Access to XMLHttpRequest at 'https://localhost:44311/api/user/login' from origin 'http://localhost:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Upgrade:
Запорос:
$.ajax({
            async: true,
            // crossDomain: true,
            url: "https://localhost:44311/api/user/login",
            type: "POST",
            headers: {
                "Content-Type": "application/json",
                "cache-control": "no-cache",
                "Postman-Token": "c236d8f2-4ef0-4187-bfea-494d032e179a",
                // "Access-Control-Allow-Credentials": "true"
            },
            processData: false,
            jsonp: "callback",
            dataType: 'jsonp',
            data: { "UserName": "MARS", "PasswordHash": "123qweASD!" },
            success: function (res) {
                alert(res);
            },
            error: function () {
                alert("error.");
            }
        });

Что в браузере:

Как правильно сделать ajax запрос???

A: Попробуй тип запроса сделать jsonp.
Ссылка на мануал - learn.jquery.com
// Using YQL and JSONP
$.ajax({
    url: "http://query.yahooapis.com/v1/public/yql",

    // The name of the callback parameter, as specified by the YQL service
    jsonp: "callback",

    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",

    // Tell YQL what we want and that we want JSON
    data: {
        q: "select title,abstract,url from search.news where query=\"cat\"",
        format: "json"
    },

    // Work with the response
    success: function( response ) {
        console.log( response ); // server response
    }
});


text:
Q: Angularjs getting variable name with highest value I have several variables with some values assigned. For ex:
Gain_weight = 0.01
Gain_weather = 0.02
and some more like this. Now I want to get the variable name with highest value assigned.
When I do something like this It returns the value not the name.
var rootNode = Math.max(Gain_weight,Gain_smoking,Gain_exercising,Gain_foodhabits,Gain_parent_heartattack,
            Gain_alcohol,Gain_occupation,Gain_workinghrs);

So instead of value how can I get the highest value assigned string?

A: After checking this question it seems it may not be possible to get the name.
A way around can be either using an object or a associate array with name as same of variable name and it's value as the variable value
Hope this snippet will help to understand
// Array with name value pair
var _myDemoArray = [
{name:'Gain_weight',
 value:0.01},
{name:'Gain_weather',
value:0.02}]

 // sort the array in descending order to get the element with maximum value.
var _getSortedElem = _myDemoArray.sort(function(a,b){
  return b.value -a.value;
});
// The first element of this sorted array will have element with maximum value
console.log(_getSortedElem[0].name);

Check this jsfiddle for demo


text:
Q: How to disable view caching in Ionic2? Can i disable view caching?
I need my view to be up to date when the user hits the "back" button.
I can update date but the view wont update.
Example:
First page: List of tasks
Second page: Task
I enter the list of tasks page, get the tasks from the database and list them.
I show the user which task is done and which is not (with a special css class)
When the user taps a task he is redirected to a task page. There he can update the task to done. But when he goes back the tasks list will not be updated.
How can i make this happen?
Thank you

A: Using Ionic 2, this actually isn't as bad as it was in the first iteration. Check out the NavController docs at http://ionicframework.com/docs/v2/api/components/nav/NavController/
Using the page event "ionViewDidEnter()" will allow you to add logic that you want to fire every time the page loads, even if it's been cached in the Nav Stack.
ionViewDidEnter     Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page.

A: There is a little work to do to achieve this. In fact each component has its own state (properties).
In your case to notify the list component that one element was updated, the list generic way is to leverage a shared service with an observable. Through this observable the details component can emit an event to notify the list one. The event will contain the updated value of the element.
The list has registered on this event and will be notified. In this case it will be able to update the element in the list.
For more details of this approach, you could have a look at the following links:

*

*Delegation: EventEmitter or Observable in Angular2

*https://angular.io/docs/ts/latest/cookbook/component-communication.html

A: Your question doesn't provide much information but this might apply to your situation.
You could try to implement CanReuse in you component to always return false which prevents the router reusing a component instance.
routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) { return false; }

A: I believe the Ionic V2 accepted way is to use the lifecycle event from ionic called ionViewWillEnter() and this function will fire every time that page is loaded.


text:
Q: Explicit inverse in Shapiro's Lemma For a seminar on group cohomology I want to avoid having the students talk about group rings and resolutions for the time being and do everything with explicit inhomogenous cochains.
Now let $A$ be a $G$ module where $G$ is a (finite) group. Let $H$ be a subgroup (not necessarily normal). Let $CoInd_H^G(A)=Map(G/H,A)$ be the coinduced module with the $G$ action given by $(g.f)(x)=g.(f(g^{-1}x))$ for $x\in G/H$.
Evaluation at $H$ gives a map $p:Map(G/H,A)\rightarrow A$.
Given a cochain $f:G^n\to CoInd_H^G(A)$ we obtain a map $p\circ f|_H:H^n\to A$. This induces $H^n(G,CoInd_H^G(A))\rightarrow H^n(H,A)$.
I want to see that this is an isomorphism, but I cannot find the inverse.

A: D. Naidu constructs an explicit inverse map $H^n(H,A) \rightarrow H^n(G,CoInd_G^H(A))$ for the case $n=1,2$. For the construction and proof, check out lemma $2.1, 2.2$ in his paper https://arxiv.org/pdf/math/0605530.pdf.


text:
Q: Understanding the evaluation and execution order with semicolon syntax I already learned a little bit about FFL semicolons from my previous question. However, it is still not clear what order of evaluation or execution they enforce. So here is a more concrete example:
 [ expr_a, expr_b ; expr_c, expr_d ; expr_e, expr_f ]

What should be the order of execution for the above code? In my head, it should be:

*

*evaluate a & b

*execute a, execute b

*evaluate c & d

*execute c, execute d

*evaluate e & f

*execute e, execute f

Now let's imagine that expr_b = add(test_list, ['b saw ' + str(test_list)]) and similar for all the other expressions. Then what would be the final contents of test_list?
In my head, it should be:

a saw []
b saw []
c saw [a saw [], b saw []]
d saw [a saw [], b saw []]
e saw [a saw [], b saw [], c saw [a saw [], b saw []], d saw [a saw [], b saw []]]
f saw [a saw [], b saw [], c saw [a saw [], b saw []], d saw [a saw [], b saw []]]

Please explain why that is not the case.

A: To begin with, you probably don't want to write code exactly like this. Generally, semi-colons have very low precedence, but a list literal isn't an operator, and the code will be seen like this:
[a, (b; c), (d; e), f]
This means that you are starting off four command pipelines in parallel (though two of them only have a single member). It will evaluate a, b, d, f. Then it will execute the results of a, then the results of b. Executing b will trigger the next step in the command pipeline, so it will evaluate and execute c. Then it will execute d, then evaluate and execute e, finally it will execute f.
So:
a saw []
b saw []
c saw [a saw [], b saw []]
d saw []
e saw [a saw [], b saw [], c saw [a saw [], b saw []], d saw []]
f saw []


text:
Q: Coding IF statements in Excel I have created a Risk Log in Excel, there are two columns, labels Priority & Impact (where High (H), Medium (M) or Low (L) can be inputted). I would like to create a third column called "Measure".
This will calculate a value based on the priority and the impact of these risks.
The numbers are shown in the table below, where the horizontal axis is Impact, and the Vertical in Priority
 H  3   7   9
 M  2   5   8
 L  1   4   6
    L   M   H
Impact

So for example, a priority of H and an impact of H would give you 9 in the measure column, a priority of M and an impact of H would give you 8, and a priority of H and an impact of M would give you 7.
I am not quite sure how to code the "Measure" column so that I get the number desired. I am  assuming some kind of "If" statement, but not sure as there are so many options. Below is my current spreadsheet, and I would like to add the measure column to the right.
Any help is great!

A: This can be done with an Index/Match lookup. No nesting of IFs required.
=INDEX($B$1:$D$3,MATCH(F2,$A$1:$A$3,0),MATCH(G2,$B$4:$D$4,0))

Copy down. You can place the lookup table on a different sheet, of course.

The first Match function finds the row according to the values in A1 to A3. The second Match finds the column according to the values in B4 to D4. Index returns the cell where the found row and column cross.


text:
Q: FlashDevelop is putting entire class path on new instance declaration This is more of a nuisance than anything, but when I use FlashDevelop and declare a new instance it puts the whole class path instead of just the class name.
For example I have a class called "FrameText" for a game I'm working on, it's located in the path "display.text.gameText.test.FrameText". I have an instance of type FrameText called "currentTask", and when I put currentTask = new the auto-prediction grabs the class FrameText since that's the instance type. I hit enter to accept that class and it puts
currentTask = new display.text.gameText.test.FrameText
instead of just currentTask = new FrameText. I've tried to look through the program settings to get it to stop putting the whole class path but I can't find anything.

A: My brother figured it out (thanks homie), turns out I had two FrameText classes since I'm testing a text overhaul for my game. I renamed the test class to FrameTextTest and it worked perfectly.


text:
Q: Xamarin Portable Class Library Gets Proxy Access Denied on iPhone Simulator I've run into a bit of an issue with the iPhone simulator when trying to access a WCF REST service.
I've asked the question on the Xamarin forums, but no joy.
Some context:

*

*I have a PCL for a Xamarin cross platform project, in VS 2012.

*I use the Portable Microsoft HttpClient package and the Json.NET package.

*I have a pretty simple WCF REST service sitting in the background.

When testing

*

*I can access the service fine from a browser on the dev machine.

*I can access it fine using a console application going via the PCL.

*I can access it fine via the app, from a real android device on the WiFi network of
the same corporate network.

*I can access it fine from Safari on the build Mac.

*I can access it fine from Safari on the iPhone simulator on the build Mac.

The issue is, as soon as I try to access the service via the app on the iPhone simulator, I get a 407, Proxy Access Denied error.
Here is the code I'm using to set up the connection:
private static HttpRequestMessage PrepareRequestMessage(HttpMethod method, string baseUri,
    string queryParameters, out HttpClient httpClient, string bodyContent)
{
    var finalUri = new Uri(baseUri + queryParameters);

    var handler = new HttpClientHandler();

    httpClient = new HttpClient(handler);

    var requestMessage = new HttpRequestMessage(method, finalUri);

    if (handler.SupportsTransferEncodingChunked())
    {
        requestMessage.Headers.TransferEncodingChunked = true;
    }

    if (method == HttpMethod.Post || method == HttpMethod.Put)
    {
        requestMessage.Content =
            new StringContent(bodyContent, Encoding.UTF8, "application/json");
    }

    return requestMessage;
}

That code gives me the 407 error.
I have tried setting the proxy by using various combinations of SupportsProxy and SupportsUseProxy. (Both returning false from the simulator.)
I've tried forcing the proxy settings regardless. I've tried setting the credentials on the handler itself. I've tried playing with the UseDefaultCredentials and UseProxy flags. I've also tried setting the IfModifiedSince value in the message header. I've tried using the PortableRest package as well.
All of that only seemed to make things worse. Where I was initially getting the 407 error, the call to httpClient.GetAsync would just immediately return null.
I am at a bit of a loss here, so any help would be greatly appreciated.
PS. For completeness, the rest of the surrounding code that makes the call: (please forgive crappy exception handling, I'm still playing around with the errors)
public static async Task<T> SendRESTMessage<T>(HttpMethod method, string baseUri,
    string queryParameters, T contentObject)
{
    HttpClient httpClient;

    var payload = string.Empty;
    if (contentObject != null)
    {
        payload = JsonConvert.SerializeObject(contentObject);
    }
    var requestMessage =
        PrepareRequestMessage(method, baseUri, queryParameters, out httpClient, payload);

    HttpResponseMessage responseMessage = null;
    try
    {
        if (method == HttpMethod.Get)
        {
            responseMessage = await httpClient.GetAsync(requestMessage.RequestUri);
        }
        else
        {
            responseMessage = await httpClient.SendAsync(requestMessage);
        }
    }
    catch (HttpRequestException exc)
    {
        var innerException = exc.InnerException as WebException;
        if (innerException != null)
        {
            throw new Exception("Unable to connect to remote server.");
        }
    }

    return await HandleResponse<T>(responseMessage);
}

private static async Task<T> HandleResponse<T>(HttpResponseMessage responseMessage)
{
    if (responseMessage != null)
    {
        if (!responseMessage.IsSuccessStatusCode)
        {
            throw new Exception("Request was unsuccessful");
        }

        var jsonString = await responseMessage.Content.ReadAsStringAsync();
        var responseObject = JsonConvert.DeserializeObject<T>(jsonString);
        return responseObject;
    }

    return default(T);
}

This was my attempt at implementing IWebProxy quick and dirty, which I think could have made things worse:
public class MyProxy : IWebProxy
{
    private System.Net.ICredentials creds;

    public ICredentials Credentials
    {
        get
        {
            return creds;
        }
        set
        {
            creds = value;
        }
    }

    public Uri GetProxy(Uri destination)
    {
        return new Uri("proxy addy here");
    }

    public bool IsBypassed(Uri host)
    {
        return true;
    }
}

Thanks again for taking the time to read my question.

A: So I finally got it working.
Turns out it was something really stupid, but being new to iOS mobile dev and the fact that the service worked via Safari on the simulator threw me for a loop.
I read that the simulator uses the proxy settings as defined on the Mac. So I went to the network settings and added the service address to the proxy bypass list.
Works like a charm now.
If anybody feels there is a better way to do this, please add your opinions.


text:
Q: React useEffect default value does not update properly I am getting the property endDate from a redux store and I am sure that the property is not null or undefined, but then again the state keeps it's previous displayed value until the page is refreshed. I want the page to automatically set the state of timeLeft to millisecondsToTime(now, endDate) by default, but currently it fails, despite working after reload.
import React, { FC, useEffect, useState } from "react";
import { millisecondsToTime } from "src/utils/helpers";

import {
  StyledCountdownTimer,
  StyledTimeBox,
  StyledTimeBoxNumbers,
  StyledTimeBoxText
} from "./StyledCountdownTimer";
import { getActiveCampaign } from "../../reduxStore";

export interface CountdownTimerProps {
  endDate?: string;
}

const CountdownTimer: FC<CountdownTimerProps> = ({ endDate }) => {
  const now = Date.now();
  const [timeLeft, setTimeLeft] = useState(millisecondsToTime(now, endDate));

  const data = getActiveCampaign();

  console.log(data);

  useEffect(() => {
    const timer = setTimeout(() => {
      setTimeLeft(millisecondsToTime(now, endDate));
    }, 1000);

    if (timeLeft.finished) {
      clearTimeout(timer);
    }

    return () => {
      clearTimeout(timer);
    };
  }, [endDate, now, timeLeft.finished]);

  return (
    <StyledCountdownTimer>
      {endDate}
      {timeLeft.days}
      {millisecondsToTime(now, endDate).days}
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.days}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Days</StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.hours}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Hours</StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.minutes}</StyledTimeBoxNumbers>
        <StyledTimeBoxText></StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.seconds}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Seconds</StyledTimeBoxText>
      </StyledTimeBox>
    </StyledCountdownTimer>
  );
};

export { CountdownTimer };


text:
Q: WPF Prism - What is the point of using Prism Regions? I'm just wondering what the point of regions are. I guess I don't understand the problem they solve.
For example, I see a lot of people using regions for a navigation region, but then why not just have an ItemsControl bound to an ObservableCollection instead of having a region and load in different navigation elements into that region?

A real-world example of it's use/benefits over the alternatives would rock!

A: Regions allow you to define a spot in your program that exists for a specific purpose. So for example, you might have a Menu Region, or a Footer Region. You can then separate out the Views/ViewModels for those specific regions into their own section of the program.
So instead of having an ApplicationViewModel containing properties for the MenuViewModel and FooterViewModel, and having the View bind each section to those properties, you would have separate ViewModels for Menu and Footer, and your ApplicationViewModel would only deal with the content. It's a better way to separate some logical boundries in your application.
Personally I think Regions are horribly overused and abused. I almost never use them unless I have something like a Header or a Footer that is unrelated to the rest of my Application code. They're also mostly used in View-First development, and I prefer ViewModel-First.

A: Compare the RegionManager to the EventAggregator and you'll see the advantage of it...
The EventAggregator allows different components to publish/subscribe to events without being coupled to each other. The same goes with the RegionManager... you can load a view into a region without your other view knowing what is going on in there. It decouples your views from each other... that's not to say EVERY view should be unaware of each other... there are times where a view should know about another view.

Look at Microsoft Outlook (note: I'm making things up here, including names, as Outlook is not written in WPF, but instead C++):
The main UI would have the following regions:

*

*MenuRegion

*NavigationRegion

*ContentRegion

*SideRegion

Regions are defined on standard controls (so you still need standard controls), more specifically ItemsControl, ContentControl, and Selector out of the box (you can extend other controls to be "region supportive"). They allow another section of code to manage the regions by resolving and loading the appropriate views into those regions. Basically, to keep things decoupled.
You're main UI does not need to know everything about your application; instead, it just simply needs to know that it has a Menu, Navigation, Content, and Side Region. Which views that actually are placed in the regions doesn't matter. Now, that doesn't mean every view should be decoupled from each other. I'll get to that later.
So, how does it actually decouple? Here's a scenario: click on the calendar icon in the Navigation control. So what should happen when you do that?

*

*NavigationView - The Button (Icon) is bound to an ICommand, so it calls the ExecuteLoadCalendar() function.

*NavigationViewModel - The ExecuteLoadCalendar() function uses the EventAggregator to announce that the user is attempting to launch the calendar.

*ContentController - The ContentController had subscribed to the LoadCalendarAggregateEvent, so that is executed. Here, it resolves/activates the CalendarView (COUPLED) using the IRegionManager and the region name. It should do this by grabbing an ICalendarView instead of a CalendarView.

Throughout the process each part is decoupled except for the ContentController and the CalendarView/ICalendarView. Of course, you could say that the NavigationView/NavigationViewModel sort of knew about the CalendarView/CalendarViewModel by having an ICommand and function. Well, "sort of" isn't the same as "they do", because the code-behind and view-model code should never reference the actual CalendarView/CalendarViewModel objects.
Also, we can remove the "sort of" by making the execute generic. Instead of having a ExecuteLoadCalendar() function, it can have a LoadContent(NavigationItem item) function where the AggregateEvent payload is an identification of some sort, for example, item.Name (String) (loaded in from a DB, XML, etc) to state they clicked "Calendar". The ContentController uses the same data to resolve "Calendar" instead of an ICalendarView (because really it shouldn't care what interface/type is resolved/activated in the ContentRegion -- it just needs an Object to activate). I use MEF, so this can be achieved with the following code block:
[Export("Calendar")]
public class CalendarView : UserControl, ICalendarView { }

So, can views know about each other? Yes! For example, my EmailUserControl has a search bar/list of emails as well as a preview pane. These 2 controls can be EmailListUserControl, which is composed of a search bar and an ItemsControl, and a EmailContentUserControl, which is just a preview pane for the selected email. Do they have to be separate controls? No, but if they are then we can reuse the EmailContentUserControl when we open the email in a separate window. So, this is an example where the EmailUserControl is coupled to 2 different views (the EmailListUserControl and the EmailContentUserControl).

Why is this better/different from other approaches: It decouples views from each other (and guard against view-models needing to know about views).

A: Scenarios that Region enables
I skimmed this article to get the answer: http://www.developmentalmadness.com/archive/2009/10/14/mvvm-and-prism-101-ndash-part-3-regions.aspx
As far as I can tell, the Region feature is designed to enable View registration/injection in code that is neither your view nor your view model.
Take for example a ContentPresenter control.  If you used it instead of a Region, your view model would have to return concrete views in order to keep the main view agnostic of its child views.
If you used a ItemsControl and bound it to arbitrary data on the view model, you would need to specify which views to instantiate in a DataTemplate on the main view.
With a Region, you can register a view to a Region in the Dependency Injection container.  Neither the view nor the corresponding view models need to know anything about the concrete view that will be used at runtime.  It will be injected in by the container.
This lets you completely decouple a main view from knowing anything about its child views, without forcing your view model to know anything about those child views.
Concrete use cases
How useful this is, and what concrete scenarios this would enable, I'm not sure.  I've used a ContentPresenter with a plugin architecture, but I am not sure that fits well with this model.  With a plugin model, you want the view and view model to be bound together, so this approach buys you nothing.
I suppose it would work best if you find you have big unrelated views and want to split them up.  It might be useful for isolating your integration tests from each other, by injecting only part of the view and view model at a time.
I'm grasping at straws for compelling real-world use cases :)  In nearly all the cases you could simply use a UserControl instead, and could forgo the whole dynamic registration thing, with no real down side.


text:
Q: Does Kubernetes (local Docker method) really work? As per the official documentation here on running Kubernetes locally within a Container -- I have followed all the steps carefully, and I am still getting the message connection refused when I type kubectl get nodes.
docker ps shows that api-server is not running, and docker logs kubelet does indeed varify so:
[kubelet.go:1137] Unable to register 127.0.0.1 with the apiserver: Post http://localhost:8080/api/v1/nodes: dial tcp 127.0.0.1:8080: connection refused.

After a little while, docker logs kubelet
E0711 16:07:06.814735   33792 event.go:202] Unable to write event: 'Post http://localhost:8080/api/v1/namespaces/default/events: dial tcp 127.0.0.1:8080: connection refused' (may retry after sleeping)

Apparently, I am not alone in experiencing this problem.

UPDATE:
After several hours, docker logs kubelet
E0712 08:28:03.528010   33792 pod_workers.go:138] Error syncing pod 4c6ab43ac4ee970e1f563d76ab3d3ec9, skipping: [failed to "StartContainer" for "controller-manager" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=controller-manager pod=k8s-master-127.0.0.1_default(4c6ab43ac4ee970e1f563d76ab3d3ec9)"
, failed to "StartContainer" for "apiserver" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=apiserver pod=k8s-master-127.0.0.1_default(4c6ab43ac4ee970e1f563d76ab3d3ec9)"
, failed to "StartContainer" for "setup" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=setup pod=k8s-master-127.0.0.1_default(4c6ab43ac4ee970e1f563d76ab3d3ec9)"
]

A: The easiest way to run Kubernetes locally now is Minikube, though I'd expect the local docker method to still be functional.
Does docker ps -a show any crashed kube-apiserver containers that might have any clues in their logs?


text:
Q: Check if two MovieClips are the same? I'm trying to check wether two MovieClips are of the same kind or not.
I have a collection of MovieClips stored in a dictionary, I'm then iterating over the entries and comparing each MovieClip with a MovieClip passed into the function. The problem is, it doesn't work. Neither does (==).
Any ideas?
Cheers.
    public function hideAllPagesExcept(activatedPage:MovieClip):void {
        for(var key:String in _navItems) {
            var mc:MovieClip = MovieClip(_navItems[key]);
            if(mc is activatedPage) {
                trace("Same");
            }
        }
    }

A: If this doesn't work then the MovieClip you are passing in is not what you think it is.
public function hideAllPagesExcept(activatedPage:MovieClip):void {
    for each (var mc:MovieClip in _navItems) {
        if(mc == activatedPage) {
            trace("Same");
        }
    }
}

A: The problem is the way you are using the keys of the dictionary. Using == to check for equality is fine. The line mc is activatedPage is just wrong, the is operator is used to check the type of an object, like mc is MovieClip.
You are assuming the keys of the dictionary are Strings, which isn't always true. The point of a dictionary is that you can use any object as a key. If all you need are string based keys, use an Object.
By using for(var key:String in _navItems) you are converting the keys to strings, which leads to mc being null, because the key might look like [object Object] after the convertion and _navItems["[object Object]"] doesn't exist.
Either use for(var key:Object in _navItems) or use a for each loop, like The_asMan suggested. It iterates over the values of each key, instead of just over the keys.


text:
Q: HTML5 bar chart exported from Flash does not work  in IE6, IE7 or IE8 I have made a graph using flash and have exported it to a HTML5 format. Its works fine in IE9,Mozilla Firefox, Google Chrome and most of the major browsers. But I want a work around to make it work in IE 6 and 7. I tried changing the doctype but still it soen't display anything in my IE 6 browser.
HTML
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled</title>
<!--Adobe Edge Runtime-->
    <script type="text/javascript" charset="utf-8" src="sample_edgePreload.js"></script>
    <style>
        .edgeLoad-EDGE-36508108 { display:none; }
    </style>
<!--Adobe Edge Runtime End-->

</head>
<body style="margin:0;padding:0;">
    <div id="Stage" class="EDGE-36508108">
    </div>
</body>
</html>

A: Internet Explorer 6-8 rendering engines do not support HTML5, as they were built on the time when people where still hunting mammoths with sticks and this was before HTML5.
To add the support of HTML5 in Internet Explorer 6-8 consider using the following Google Chrome Frame installer Javascript:
http://www.chromium.org/developers/how-tos/chrome-frame-getting-started/#TOC-Detecting-Google-Chrome-Frame-and-Prompting-to-Install


text:
Q: Postgresql 9 on Debian 6 doesn't restart I just installed postgres on Debian 6 with apt-get. It works fine, but I had to change some configuration in postgresql.conf and now I'm trying to restart postgres.
If I try "service postgresql restart", I get the following error:

Stopping PostgreSQL 9.0 database server: mainError: Could not open /proc/8134/comm ... failed!

The same happens with cd /etc/init.d/postgresql restart
I tried this last as root and also as postgres user
Any clues?

A: It looks like the issue is with the postgresql-common (123). Caused by this change:
* PgCommon.pm, cluster_info(): If we have a PID file and can read it (i. e.
as root), prefer doing this over probing the port. This delivers the
correct result with e. g. "pg_ctlcluster restart" when the port got
changed in the configuration file. (Closes: #643850)

The bug is being addressed and I suspect will be released with postgresql-common (124)?
See: Launchpad PostgreSQL Repo
You should be able to use the above code to fix your issue, or try changing line 532 of /usr/share/postgresql-common/PgCommon.pm.
Change:
if (open PS, "/proc/$pid/comm") {

to something that exists:
if (open PS, "/proc/$pid/cmdline") {

That should work until the real fix is released.


text:
Q: CSS issue on IE7 - Navigation Menu I have designed a Navigation Menu, it working properly on Chrome, Firefox and IE8.
It appear it not working properly on IE7, the margin and the size of the
 is too small, sub-menu is not appearing in full and also #background is missing.
It should look the same as Chrome and Firefox.
See example: http://jsfiddle.net/FFWfp/
How to fix this?
HTML

Home

                Category

PHP

HTML

CSS

                Account

One

Two

Three

Logout

CSS

A: This should be simple, clearfix, containing floats whatever.. but it's not This is a hasLayout error that compounds, it is one of the rare situations where you need to remove haslayout, but where it's not possible to do so.
The way your code is written (nothing wrong with it by the way!) means the #background div needs hasLayout to contain the floated children (even trying an extra clearing element doesn't work which shows the out and out IE error). Your code has this with overflow : hidden;, but then because there's hasLayout on the .nav-block due to the 50px height, that height, in IE7, is all that's being "contained" - this is of course wrong, as the floated lists are children of #background too.. however it's because of an error that hasLayout even works to contain floats so there's no use arguing the specs!
I tried every hack I knew how and but the simplest way was to rewrite the code and avoid hasLayout where possible, and use margins and line-heights instead - so I reversed the coloring of the two containing blocks. I made the background black and the .nav-block grey & gave the background a top padding of 50px to make the black bar.. then I moved the menu which is inside the grey bit up by 43px with a negative top margin. it's 43px because in your example I measure the black bar @ 50px; and the top links @ 36px in height which meant to keep them looking vertically centered on the black bar they would have need 50px-36px = 14px / 2 = 7px top & bottom 'spacing'.
the .nav-block div then needed to be the one that was made to contain the floated children, but overflow: hidden won't work now because of the negative top margin, it would hide the top links! so instead I floated it left and gave it a width of 100%; which is another way of creating a new block formatting context and giving IE the hasLayout it needs without clipping the content.
then I pretty much followed what you had done to achieve the short top links and full width (130px) child links only floating the top links so they would "shinkwrap" - without the float on the child lists the child links could be made display: block so they take the full width of the ul. For the height on the top links IE needed both line-height and padding, but line-height on the child links was enough because of the display: block;
Example Fiddle
HTML is the same as yours above..
CSS:
html, body {margin: 0; padding: 0;}

#background  { /* black bar */
    background: #000;
    padding: 50px 0 0 0;
}

.nav-block {
    background: #EBE9E1;
    float: left;
    width: 100%;
    padding-bottom: 3px;
}

#nav, #nav ul {
    margin: 0;
    padding: 0;
    list-style:none;
}

#nav { /* black bar = 50px, top links = 36px, difference = 14px, = 7px from top */
    margin-top: -43px;
}

#nav ul {
    width:130px;
    border-right: 2px solid black;
    border-bottom: 2px solid black;
    border-left: 2px solid black;
    margin-left:-2px;
}

#nav > li { /* top links only */
    float: left;
    margin: 0 0 0 30px;
}

#nav a {
    line-height: 36px;
    background-color:white;
    color:#C51721;
    padding: 10px;
    text-decoration: none;
}

#nav ul a { /* child list links */
    display: block;
    padding: 0 10px;
    line-height: 24px;
    border-bottom:1px solid #DEDEDE;
}

A: Apparently you either have to comment out the spaces between or put all your
 elements on one line.
E.g.:

PHP

HTML

CSS

or

PHP

HTML

CSS

A: This is a common problem in learning css.
I reccomend using this example as your guideline: http://www.htmldog.com/articles/suckerfish/dropdowns/
The background for #background isn't appearing because it contains only floated elements.
You can fix this bey giving it a set height in css, or by using the "clearfix" method ( http://perishablepress.com/press/2009/12/06/new-clearfix-hack/ )


text:
Q: Is there a JavaScript undefined property handling like in Angular2 templates I was wondering if there is a neat way of doing this:
if (app && app.object && app.object.foo) {
  alert(app.object.foo.bar);
}

This is really long and "ugly".
I found out that Angular2 has something really great for cases like this. But I think it's only for templates:
<div>{{this?.object?.foo?.bar}}</div>

This got me really exited because I have a lot of code that looks just like the first example. It get's the job done but I'm really hopping there is something more sophisticated.

A: I found this solution sometime back on net :
function checkNested(obj /*, level1, level2, ... levelN*/) {
  var args = Array.prototype.slice.call(arguments, 1);

  for (var i = 0; i < args.length; i++) {
    if (!obj || !obj.hasOwnProperty(args[i])) {
      return false;
    }
  obj = obj[args[i]];
 }
  return true;
}

var test = {level1:{level2:{level3:'level3'}} };

checkNested(test, 'level1', 'level2', 'level3'); // true
checkNested(test, 'level1', 'level2', 'foo'); // false

jsFiddle : https://jsfiddle.net/nikdtu/kjsxnunp/

A: not out of the box.
var string = function(v){ return v == null? "": String(v) }  //because I usually want this behaviour

var fetch = function(path, obj){
    path instanceof Array || (path = string(path).split('.'));
    for(var i=0, v=obj; i<path.length; v = v[path[i++]])
        if(v == null) return void 0;
    return v;
}

and your code:
if(fetch("object.foo", app)){
    alert(app.object.foo.bar);
}

or even more direct:
alert( fetch("object.foo.bar", app) );
//will alert undefined, if the path could not be resolved

Argument order is this way around, because this function is usually curried in my code, so I can do sth like:
arr.map(fetch('some.deeper.path'));

A: Slightly shorter (than original) way in JavaScript (less readable)
if ((a = app) && (o = a.object) && (f = o.foo)) {
  alert(f.bar);
}

The way I'd write it in CoffeeScript (my preferred method)
alert f.bar if f = app?.object?.foo?

If you're really into using Javascript and want it to appear clean, you could use something like:
function ifExist (name) { // Returns undefined if it doesn't exist
  arr = name.split('.');
  obj = eval('if (typeof '+(x = arr.splice(0,1)[0])+' !== \'undefined\') '+x);
  for (i = 0; i < arr.length; i++) {
    if (typeof obj === 'undefined') {
      return obj;
    }
    else {
      obj = obj[arr[i]];
    }
  }
  return obj
}

alert(ifExist('app.object.foo.bar'));

Because it uses eval, it could pose a security risk if app.object.foo.bar is generated by a the user. It works in simple cases (such as the one you posted above), but using something like app.object['foo'].bar in it would probably break it without adding some input checks.

A: Many languages have this functionality, some call it safe navigation operator or even Elvis operator (yes haha).
JavaScript does not have this functionality. If you are open to use  CoffeeScript, you might take a look at the existential operator.
But, if you want to keep with JS, you should take a look at lodash.get(), which lets you do something like this:
var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, 'a.b.d.c', 'default');
// → 'default'


text:
Q: Exit from stored procedure in sybase I am getting some parameters in my stored procedure. Before operating on these parameters, I want to validate them and if the parameters are not as per the requirement then I want to exit from the stored procedure with an error message.
sample code:
   create proc abcd
    (
       zip   varchar(20),
       name   varchar(20),
       network varchar(1)
    )

    -- validation section
    IF (len(zip)<>5 OR LEN(zip)<>9)
    begin
          print "The zip must be of 5 or 9 characters"
          <---- how to exit from here--->
    end
    IF (len(name)<2)
    begin
          print "The name must be of at least 2 characters"
          <---- how to exit from here--->
    end

---- main code

How can I exit the procedure once I get the error as mentioned above?

A: You can use return command as below
-- validation section
IF (len(zip)<>5 OR LEN(zip)<>9)
begin
      print "The zip must be of 5 or 9 characters"
      return 1
end
IF (len(name)<2)
begin
      print "The name must be of at least 2 characters"
      return 2
end

return 0 -- on the end of procedure

to catch the result you can use this code:
declare @ProcResult int
execute @ProcResult = abcd @Zip = ..., @name...
select @ProcResult

A: Let me suggest a few changes:
create procedure abcd
       @zip     varchar(20),
       @name    varchar(20),
       @network varchar(1)
AS
    -- validation section
    IF (len(@zip)<>5 AND LEN(@zip)<>9)
    begin
          -- print "The zip must be of 5 or 9 characters"
          raiserror 20000 "The zip must be of 5 or 9 characters"
          return 1
    end
    IF (len(@name)<2)
    begin
          -- print "The name must be at least 2 characters"
          raiserror 20001 "The name must be at least 2 characters"
          return 2
    end

There are numerous options with raiserror but this should point you in the right direction.
Edit: added return statements


text:
Q: AngularJS couting the data from factory I am dealing with annoying problem. I have a angular factory that holds an array of dummy data. And I am grabing this data from factory to my controller and displaying in my view using ng-repeat and it works just fine. But my question is how and where I should write some code to get more information about my data in array, For example If array looks like this:
[
...
{"id":186,"imie":"Bérangère","nazwisko":"West","plec":"Female","adres":"4 Lindbergh Park","zawod":"solution","narodziny":"1927-01-31"},
{"id":187,"imie":"Marylène","nazwisko":"Cooper","plec":"Male","adres":"7 Summit Avenue","zawod":"Profound","narodziny":"1931-09-24"},
{"id":188,"imie":"Gösta","nazwisko":"Nelson","plec":"Female","adres":"5 Corscot Terrace","zawod":"context-sensitive","narodziny":"1954-11-03"},
{"id":189,"imie":"Clélia","nazwisko":"Moore","plec":"Male","adres":"500 Daystar Plaza","zawod":"task-force","narodziny":"1997-01-14"}
...
]

I want to display a total count of users with "plec":"Female".
Should I write a JavaScript for loop to check my data, or there is an "Angular way" to deal with it?

A: In Angular, it is best practice to do it in your factory
(function () {
        'use strict';

        angular
            .module('app')
            .factory('MyFactory', MyFactory);

        MyFactory.$inject = ['$http'];

        /* @ngInject */
        function MyFactory($http) {
            var service = {
                dummyUserData: [],
                getUserCountsWhere: getUserCountsWhere
            };

            return service;

            ////////////////

            function getUserCountsWhere(key, value) {
                // key is plec , value is "Female"
                return service.dummyUserData.filter(function(user){
                    return user[key] == value;
                }).length;
            }

        }
    })();

A: In your factory (or wherever you can access this object), you can write a function that counts and returns the number of females in your array:
var data = [ ... ];

var countFemales = function() {
    var counter = 0;
    for(var i = 0; i < data.length; i++) {
        if(data[i].plec == "Female") counter++;
    }
    return counter;
}

A: Try this, using lodash' reduce, which seems a little neater:
function countingMethod() {
  return _.reduce(data, (key, val, acc) => {
    if (data[key]['plec'] === 'Female') {
      acc++;
    }
    return acc;
  }, 0);
}

Or the non-lodash version:
function countingMethod() {
  return data.reduce((key, val, acc) => {
    if (data[key]['plec'] === 'Female') {
      acc++;
    }
    return acc;
  }, 0);
}


text:
Q: Always unlink() the POSIX named semaphore in shared memory In the following code, each thread runs sell_tickets() function, takes the mutex lock and decrement the tickets number. In order to limit the active threads number, the checkin() and checkout() threads is a producer-consumer model using semaphore.
But in the unit-test, it seems that consumer function checkout() calls pthread_join() function before the producer checkin() even creating new threads. So anything wrong? Is it because threads don't share the stack memory segment, since I didn't malloc() heap space for some parameters.
/**
 * Using semaphore to limit maximum thread number.
 */
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>

/**
 * If arguments that pthread_create() pass to sell_tickets() are more than one,
 * they need to be wrapped into a single structure.
 */
typedef struct {
    unsigned agent_id;              // simulate an agent
    unsigned tickets_tosell;        // agent's personal goal of the day
    pthread_mutex_t *pool_lock;     // mutex lock for visiting the shared tickets pool
    unsigned *tickets_pool;         // shared tickets pool
} agent;

/**
 * Constructor
 */
static void new_agent(agent *a, unsigned agentid, unsigned ticketsnum, pthread_mutex_t *lock, unsigned *tickets_pool) {
    a->agent_id = agentid;
    a->tickets_tosell = ticketsnum;
    a->pool_lock = lock;
    a->tickets_pool = tickets_pool;
}

/**
 * Implement void *(*start_rtn)(void *);
 * -------------------------------------
 * Each thread execute this function.
 */
static void *sell_tickets(void *agent_addr) {
    agent *a = (agent *)agent_addr;
    while (a->tickets_tosell > 0) {
        pthread_mutex_lock(a->pool_lock);
        (*a->tickets_pool)--;
        printf("agent@%d sells a ticket, %d tickets left in pool.\n", a->agent_id, *a->tickets_pool);
        pthread_mutex_unlock(a->pool_lock);
        a->tickets_tosell--;
        printf("agent@%d has %d tickets to sell.\n", a->agent_id, a->tickets_tosell);
    }
    pthread_exit((void *)&a->agent_id);
}

typedef struct {
    /* shared threads pool */
    pthread_t *pool_addr;
    unsigned pool_size;
    /* a pair of producer-consumer semaphore */
    sem_t *producer_sem;
    sem_t *consumer_sem;
    /* producer & consumer thread id */
    pthread_t *producer_tid;
    pthread_t *consumer_tid;
} threads_pool;

static void new_threads_pool(threads_pool *tp,
                        pthread_t *pool_addr, unsigned pool_size,
                        sem_t *producer_sem, sem_t *consumer_sem,
                        pthread_t *ptid, pthread_t *ctid) {
    tp->pool_addr = pool_addr;
    tp->pool_size = pool_size;
    tp->producer_sem = producer_sem;
    tp->consumer_sem = consumer_sem;
    tp->producer_tid = ptid;
    tp->consumer_tid = ctid;
}

typedef struct {
    sem_t *checkin_b;
    sem_t *checkout_b;
} barrier;

static void new_barrier(barrier *b, sem_t *inb, sem_t *outb) {
    b->checkin_b = inb;
    b->checkout_b = outb;
}

typedef struct {
    unsigned num_agents;
    unsigned num_tickets;
} project;

static void new_project(project *p, unsigned num_agents, unsigned num_tickets) {
    p->num_agents = num_agents;
    p->num_tickets = num_tickets;
}

typedef struct {
    project *pj;
    threads_pool *tp;
    barrier *b;
} project_params;

static void new_project_params(project_params *pp, project *pj, threads_pool *tp, barrier *b) {
    pp->pj = pj;
    pp->tp = tp;
    pp->b = b;
}

/**
 * producer thread
 * create agent sell_tickets() threads
 */
static void *checkin(void *params) {
    project_params *pp = (project_params *)params;

    /* barrier assure that checkin() and checkout() thread begin to work when two threads are both created. */
    sem_post(pp->b->checkout_b);
    sem_wait(pp->b->checkin_b);

    unsigned tickets_pool = pp->pj->num_tickets;    // shared resourses
    pthread_mutex_t tickets_pool_lock;              // mutex object

    agent agents[pp->pj->num_agents];               // arguments pass to 10 threads
    unsigned id;                                    // agent id
    pthread_t tid;                                  // current sell_tickets() thread id
    int err;                                        // thread_create() function return the error code

    pthread_mutex_init(&tickets_pool_lock, NULL);

    for (unsigned i = 0; i < pp->pj->num_agents; i++) {
        id = i + 1;
        new_agent(&agents[i], id, pp->pj->num_tickets / pp->pj->num_agents, &tickets_pool_lock, &tickets_pool);

        sem_wait(pp->tp->producer_sem);
        err = pthread_create(pp->tp->pool_addr + (i % pp->tp->pool_size), NULL, sell_tickets, &agents[i]);
        if (err != 0) {
            printf("error[%d]: can't create thread.", err);
            pthread_cancel(*pp->tp->consumer_tid);
            pthread_exit(NULL);
        } else {
            tid = *(pp->tp->pool_addr + (i % pp->tp->pool_size));
            printf("thread of agent@%d created, thread id = @%lx\n", id, (unsigned long)tid);
            sem_post(pp->tp->consumer_sem);
        }
    }

    /* wait for checkout() thread to finish */
    pthread_join(*pp->tp->consumer_tid, NULL);

    pthread_mutex_destroy(&tickets_pool_lock);
    if (tickets_pool == 0) {
        printf("Today's tickets are sold out!\n");
    } else {
        printf("%d tickets left at the end of the day!\n", tickets_pool);
    }
    pthread_exit(NULL);
}

/**
 * consumer thread
 * wait for old agent sell_tickets() thread to exit and increment the producer semaphore
 */
static void *checkout(void *params) {
    project_params *pp = (project_params *)params;

    /* barrier assure that checkin() and checkout() thread begin to work when two threads are both created. */
    sem_post(pp->b->checkin_b);
    sem_wait(pp->b->checkout_b);

    void *tret;     // to store pthread_exit() exit status rval_ptr
    int errcode;    // pthread_join() return err code

    for (unsigned i = 0; i < pp->pj->num_agents; i++) {
        sem_wait(pp->tp->consumer_sem);
        errcode = pthread_join(*(pp->tp->pool_addr + (i % pp->tp->pool_size)), &tret);
        sem_post(pp->tp->producer_sem);
        printf("agent@%d has finished his job!\n", *(unsigned *)tret);
    }
    pthread_exit(NULL);
}

/**
 * producer-consumer model using semaphore
 * maximum 10 agent sell_tickets() threads work at a time
 */
static void run(void) {
    unsigned num_agents = 30;
    unsigned num_tickets = 300;
    /*
     * project
     */
    project pj;
    new_project(&pj, num_agents, num_tickets);

    /*
     * thread pool of maximum 10 thread
     */
    unsigned threads_pool_size = 10;
    pthread_t pool[threads_pool_size];

    /*
     * checkin() and checkout() threads
     */
    pthread_t checkin_tid, checkout_tid;
    int checkin_err, checkout_err;
    /* a pair of producer-consumer semaphores */
    sem_t *checkin_sem, *checkout_sem;
    checkin_sem = sem_open("/checkin_sem", O_CREAT, S_IRWXG, threads_pool_size);
    checkout_sem = sem_open("/checkout_sem", O_CREAT, S_IRWXG, 0);
    /* barrier */
    barrier b;
    sem_t *checkin_b, *checkout_b;
    checkin_b = sem_open("/checkin_b", O_CREAT, S_IRWXG, 0);
    checkout_b = sem_open("/checkout_b", O_CREAT, S_IRWXG, 0);
    new_barrier(&b, checkin_b, checkout_b);
    /* wrap checkin() checkout() parameters into a single structure */
    threads_pool tp;
    new_threads_pool(&tp, &pool[0], threads_pool_size, checkin_sem, checkout_sem, &checkin_tid, &checkout_tid);
    project_params pp;
    new_project_params(&pp, &pj, &tp, &b);
    /* create checkin(), checkout() threads */
    checkin_err = pthread_create(&checkin_tid, NULL, checkin, &pp);
    checkout_err = pthread_create(&checkout_tid, NULL, checkout, &pp);
    if (checkin_err != 0 || checkout_err != 0) {
        if (checkin_err != 0) printf("error: checkin() thread creation failed!\n");
        if (checkout_err != 0) printf("error: checkout() thread creation failed!\n");
        sem_close(checkin_sem);
        sem_close(checkout_sem);
        sem_close(checkin_b);
        sem_close(checkout_b);
        return;
    }

    /*
     * wait for checkin() and checkout() to exit
     */
    pthread_join(checkin_tid, NULL);
    pthread_join(checkout_tid, NULL);

    /*
     * free resources
     */
    sem_close(checkin_sem);
    sem_close(checkout_sem);
    sem_close(checkin_b);
    sem_close(checkout_b);
}

int main(void) {
    run();
}

lldb shows that thread_join() return error code 3:ESRCH.
Process 46631 stopped
* thread #3, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x0000000100003b39 agtktp`checkout(params=0x00007ffeefbff618) at agents_tickets_pool.c:221:46
   217  errcode = pthread_join(*(pp->tp->pool_addr + (i % pp->tp->pool_size)), &tret);
   218  pthread_t tid = *(pp->tp->pool_addr + (i % pp->tp->pool_size));
   219  printf("thread@%u = %lx\n", i + 1, (unsigned long)tid);
   220          sem_post(pp->tp->producer_sem);
-> 221          printf("agent@%d has finished his job!\n", *(unsigned *)tret);
   222      }
   223      pthread_exit(NULL);
   224  }
Target 0: (agtktp) stopped.
(lldb) fr v errcode
(int) errcode = 3
(lldb) fr v tid
(pthread_t) tid = 0x0000000000000050

=== 01/03/2021 UPDATE 2 ===
I've posted the solution. Feel free to correct me if something wrong. Thanks everyone, especially @Semion.
=== END 01/03/2021 UPDATE 2 ===
=== 01/03/2021 UPDATE 1 ===
Currently I have fixed the problem, and find out I've made a typical mistake in the following code.
I need some time to re-edit this question and give an answer, to make it useful for later POSIX Semaphore user. Please DO NOT close this question (it has already 2 close votes). Thanks.
=== END 01/03/2021 UPDATE 1 ===

A: The bug is fixed now. The problem is in sem_close().
According to "Unix Networking Program - Vol.2 - ch10", sem_close() closes a semaphore, but does not remove it from the system shared memory. POSIX named semaphores are "kernel-persistent".
So basically I'm using the same pair of old semaphore called /checkin_sem and checkout_sem for each run. Once the program exit improperly and leave some strange values in the semaphore, all subsequent tests will crash. That's why some others said that the program works well on their machine. Because they have no legacy semaphore on their system.
To solve this, we should use sem_unlink() instead, with which semaphore name will be removed from system, and the destruction of the semaphore will take place until the last sem_close() occurs. Since close operation occurs automatically on process termination, we don't have to write sem_close() explicitly.
sem_unlink("/checkin_sem");
sem_unlink("/checkout_sem");
sem_unlink("/checkin_b");
sem_unlink("/checkout_b");

And to prevent the legacy semaphore affect our program, it's better to add O_EXCL when create the semaphore, which will pop an error when semaphore already exists.
checkin_sem = sem_open("/checkin_sem", O_CREAT | O_EXCL, S_IREAD | S_IWRITE, threads_pool_size);
checkout_sem = sem_open("/checkout_sem", O_CREAT | O_EXCL, S_IREAD | S_IWRITE, 0);

At last, for the permission flag, if the program doesn't concern inter-process communication, the simple read, write for owner is enough, which is S_IREAD | S_IWRITE or S_IRUSR | S_IWUSR.
Here's the final version of this producer-consumer threads pool.
/**
 * Using semaphore to limit maximum thread number.
 */
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

/**
 * If arguments that pthread_create() pass to sell_tickets() are more than one,
 * they need to be wrapped into a single structure.
 */
typedef struct {
    unsigned agent_id;              // simulate an agent
    unsigned tickets_tosell;        // agent's personal goal of the day
    unsigned *tickets_pool;         // shared tickets pool
    pthread_mutex_t *pool_lock;     // mutex lock for visiting the shared tickets pool
} agent;

/**
 * Constructor
 */
static void new_agent(agent *a, unsigned agentid, unsigned tickets_num, unsigned *pool, pthread_mutex_t *lock) {
    a->agent_id = agentid;
    a->tickets_tosell = tickets_num;
    a->tickets_pool = pool;
    a->pool_lock = lock;
}

/**
 * Implement void *(*start_rtn)(void *);
 * -------------------------------------
 * Each thread execute this function.
 */
static void *sell_tickets(void *agent_addr) {
    agent *a = (agent *)agent_addr;
    while (a->tickets_tosell > 0) {
        pthread_mutex_lock(a->pool_lock);   // begin of race condition
        (*a->tickets_pool)--;
        fprintf(stdout, "agent@%d sells a ticket, %d tickets left in pool.\n", a->agent_id, *a->tickets_pool);
        fflush(stdout);
        pthread_mutex_unlock(a->pool_lock); // end of race condition
        a->tickets_tosell--;
        fprintf(stdout, "agent@%d has %d tickets to sell.\n", a->agent_id, a->tickets_tosell);
        fflush(stdout);
    }
    pthread_exit((void *)&a->agent_id);
}

/**
 * Simulate a tickets selling project
 */
struct {
    unsigned num_agents;
    unsigned num_tickets;
} project;

/**
 * Shared threads pool
 */
struct {
    unsigned pool_size;
    pthread_t *pool;
} threads_pool;

/**
 * Producer, consumer threads id
 */
struct {
    pthread_t producer;
    pthread_t consumer;
} producer_consumer;

/**
 * A pair of semaphore
 */
struct {
    sem_t *producer_sem;
    sem_t *consumer_sem;
} sem;

/**
 * Barrier is not implemented in mac os, we use a pair of semaphore instead.
 */
struct {
    sem_t *producer_b;
    sem_t *consumer_b;
} barrier;

/**
 * producer thread
 * create agent sell_tickets() threads
 */
static void *producer(void *arg) {
    /* barrier assure that checkin() and checkout() thread begin to work when two threads are both created. */
    sem_post(barrier.consumer_b);
    sem_wait(barrier.producer_b);

    unsigned tickets_pool = project.num_tickets;    // shared resource for each agent
    pthread_mutex_t tickets_pool_lock;              // mutex lock for visiting tickets pool

    agent agents[project.num_agents];               // arguments pass to 10 threads
    unsigned id;                                    // agent id
    pthread_t tid;                                  // current sell_tickets() thread id
    int err;                                        // thread_create() return err code

    pthread_mutex_init(&tickets_pool_lock, NULL);

    for (unsigned i = 0; i < project.num_agents; i++) {
        id = i + 1;
        new_agent(&agents[i], id, project.num_tickets / project.num_agents, &tickets_pool, &tickets_pool_lock);

        sem_wait(sem.producer_sem);
        err = pthread_create(threads_pool.pool + i % threads_pool.pool_size, NULL, sell_tickets, &agents[i]);
        if (err != 0) {
            fprintf(stdout, "error[%d]: can't create thread.\n", err);
            fflush(stdout);
            pthread_cancel(producer_consumer.consumer);
            pthread_exit(NULL);
        } else {
            tid = *(threads_pool.pool + i % threads_pool.pool_size);
            fprintf(stdout, "thread of agent@%d created, thread id = @%lx\n", id, (unsigned long)tid);
            fflush(stdout);
            sem_post(sem.consumer_sem);
        }
    }

    /* wait for checkout() thread to finish */
    pthread_join(producer_consumer.consumer, NULL);

    pthread_mutex_destroy(&tickets_pool_lock);
    if (tickets_pool == 0) {
        fprintf(stdout, "Today's tickets are sold out!\n");
        fflush(stdout);
    } else {
        fprintf(stdout, "%d tickets left at the end of the day!\n", tickets_pool);
        fflush(stdout);
    }
    pthread_exit(NULL);
}

/**
 * consumer thread
 * wait for old agent sell_tickets() thread to exit and increment the producer semaphore
 */
static void *consumer(void *arg) {
    /* barrier assure that checkin() and checkout() thread begin to work when two threads are both created. */
    sem_post(barrier.producer_b);
    sem_wait(barrier.consumer_b);

    void *tret;     // to store pthread_exit() exit status rval_ptr

    for (unsigned i = 0; i < project.num_agents; i++) {
        sem_wait(sem.consumer_sem);
        pthread_join(*(threads_pool.pool + i % threads_pool.pool_size), &tret);
        sem_post(sem.producer_sem);
        fprintf(stdout, "agent@%d has finished his job!\n", *(unsigned *)tret);
        fflush(stdout);
    }
    pthread_exit(NULL);
}

/**
 * maximum 10 agent sell_tickets() threads work at a time
 */
static void run(void) {
    /* project */
    project.num_agents = 30;
    project.num_tickets = 300;
    /* threads pool */
    threads_pool.pool_size = 10;
    pthread_t pool[threads_pool.pool_size];
    threads_pool.pool = &pool[0];
    /* producer-consumer semaphore */
    sem.producer_sem = sem_open("/producer_sem", O_CREAT | O_EXCL, S_IREAD | S_IWRITE, threads_pool.pool_size);
    sem.consumer_sem = sem_open("/consumer_sem", O_CREAT | O_EXCL, S_IREAD | S_IWRITE, 0);
    /* barrier */
    barrier.producer_b = sem_open("/producer_b", O_CREAT | O_EXCL, S_IREAD | S_IWRITE, 0);
    barrier.consumer_b = sem_open("/consumer_b", O_CREAT | O_EXCL, S_IREAD | S_IWRITE, 0);
    /* create producer(), consumer() threads */
    int producer_err = pthread_create(&producer_consumer.producer, NULL, producer, NULL);
    int consumer_err = pthread_create(&producer_consumer.consumer, NULL, consumer, NULL);
    if (producer_err != 0 || consumer_err != 0) {
        if (producer_err != 0) {
            fprintf(stdout, "error: checkin() thread creation failed!\n");
            fflush(stdout);
        }
        if (consumer_err != 0) {
            fprintf(stdout, "error: checkout() thread creation failed!\n");
            fflush(stdout);
        }
        sem_unlink("/producer_sem");
        sem_unlink("/consumer_sem");
        sem_unlink("/producer_b");
        sem_unlink("/consumer_b");
        return;
    }

    /*
     * wait for checkin() and checkout() to exit
     */
    pthread_join(producer_consumer.producer, NULL);
    pthread_join(producer_consumer.consumer, NULL);

    /*
     * free resources
     * --------------
     * Always use sem_unlink() to remove the semaphore, but not sem_close().
     * Close a semaphore does NOT remove the semaphore from system shared memory.
     * Close operation occurs automatically on process termination, we don't have
     * to write sem_close() explicitly.
     */
    sem_unlink("/producer_sem");
    sem_unlink("/consumer_sem");
    sem_unlink("/producer_b");
    sem_unlink("/consumer_b");
}

int main(void) {
    run();
}


text:
Q: Is there a name for $\max \| A x \|$ for all $\|x\|=1?$ Is there a name for $\max \| A x \|$ for all $\|x\|=1?$
($A$ is a matrix, and $x$ is a vector)
One might be inclined to guess that it's the spectral radius of $A$, but that's not true. I'm wondering if there is a special term for this property of $A$.

A: It is called the induced matrix norm. If the underlying vector norm is the Euclidean one, then it is also called the largest singular value.

A: This is the norm of a linear map or the operator norm. It checks "how much does this matrix stretch values."
It is a theorem that $$\mathrm{Sup}_{x \in X}\frac{\|Ax\|}{\|x\|}=\mathrm{Sup}_{\|x\|=1}\|Ax\|.$$

A: Can be called a subordinate norm.

A: It goes by the name of operator norm. It's equal to $\sqrt{\rho(A^HA)}$ when the norms are the usual euclidean ones.

A: As already mentioned, it is called the operator norm (more precisely the operator norm of the linear transformation induced by the map $x \to Ax$).
I will add that it is frequently used in real analysis to "bound things". In particular, the operator norm satisfies the following (extremely) useful property:
$$\Vert Ax \Vert \leq \Vert A \Vert  \Vert x \Vert \quad \text{for all }x$$

A: It looks like it's also called the natural norm.


text:
Q: Policy for informing Stack Exchange about illegit Stack Overflow merchandise I came across this t-shirt which has Stack Overflow logo on it and is available in various colors and styles.

This doesn't look legit and I understand from this answer that Stack Exchange store is closed. From this comment from a Stack Exchange employee I understand that this is against their trademark. Is there a policy that I should follow to report these like there is a policy for reporting a SCRAPER? or Is a post like this is sufficient?

A: Since it is up to Stack Exchange, Inc to enforce their trademark, there is little the community can do.  The best course of action is to contact the SE Community team directly via the contact us link in the footer of every page.  Or by emailing them at team@stackexchange.com.
The process is probably going to be similar to reporting a scraper since they are going to need most of the same info.


text: Q: How to retrieve text from draft js while keeping the styling (bullet points) and mention names intact? I am using draft js in my project for generating notes. After the note is generated, the user can copy the note content into their clipboard. However, only the plain text is copied as it is while the mentions are not copied properly (the type of mention is copied instead). Is there a work around to this?


text:
Q: Inject content scripts from external urls in chrome extension I am writing a chrome extension that adds a small notification to the bottom corner of web pages.
I have multiple ways to do this, being

*

*Include a content.js in manifest and use the file

*Inject a script file through chrome.tabs.executeScript api

*Inject code through chrome.tabs.executeScript api

Now, I don't want the design of the notification to be hardcoded into the extension . I want to host a .html file and fetch it from the server whenever the notification is to be shown. By this way, I want to change the design of the notification frequently to boost engagement.
How do I inject a DOM element fetched from external sources into the webpages?

A: The method of how you inject into the website is irrelevant.  You just need to make an ajax call to get the html.  Something like this:
$.ajax({
    url: "yourremotehtml.html",
    type: "GET",
    dataType: "html",
    success: function (data) {
        //append data wherever you want it on the page
    }
});

Depending on your details, you may want to change this up a bit.  For example, maybe there's a template and you want to use a templating language like underscore etc to change it dynamically, maybe you want to cache the html, etc.


text:
Q: After sending on a socket, connection has been closed I am using the example at Microsoft: asynchronous-server-socket-example.
The problem is, when I send back the data to the client the data arrives to the client; but when I try again from the client to send data to the server listener then it seems the connection has been closed, because nothing will arrive on the server socket.
In my application I should run an async tcp server that is listening and sometimes for certain messages i have to send back some data on the connection established for the port of that socket.


text:
Q: I need to delete all the records whise expiry date has not been given I wrote the following I need to delete all the records whose expiry date has not been given. I wrote the following command, which has not deleted the records.
delete * from products where expdate=null;

Help to run the query by removing the error

A: Today we need to eliminate a lot of data with null data, which is the beginning.
DELETE FROM products WHERE expdate = NULL;

Found incorrect, the number of affected rows is 0;
Should be written as follows :
delete from products where expdate IS NULL;

As you were told in the comments.
Null as a value
In simple terms, NULL is simply a placeholder for data that does not exist. When performing insert operations on tables, there will be times when some field values will not be available.
To meet the requirements of true relational database management systems, MySQL uses NULL as the placeholder for values that have not been sent. The following screenshot shows what NULL values look like in the database.

Let us now look at some of the basic concepts for NULL before going deeper into the discussion.

*

*NULL is not a data type; this means that it is not recognized as "int", "date" or any other defined data type.

*Arithmetic operations involving NULL always return NULL, e.g. 69 + NULL = NULL.

*All added functions affect only rows that do not have NULL values.
IS NULL : is the keyword that performs the Boolean comparison. It returns true if the provided value is NULL and false if the provided value is not NULL.
NOT NULL : is the keyword that performs the Boolean comparison. It returns true if the value provided is NOT NULL and false if the value provided is null.
Let us now look at a practical example that uses the NOT NULL keyword to remove all column values that have null values.
Continuing with the previous example, suppose we need details of members whose contact number is not null. We can run a query like
 SELECT * FROM `members` WHERE contact_number IS NOT NULL;

Executing the above query only provides records where the contact number is not null.
Suppose we want member records where the contact number is null. We can use the following query
SELECT * FROM `members` WHERE contact_number IS NULL;

URL : https://guru99.es/null/
I hope it helps you, greetings.


text:
Q: Deploying a .wsp File with PowerShell I am attempting to install a farm solution with a Jenkins job so I need to do everything through PowerShell. So with PowerShell scripts I can:

*

*Create a web application

*Create a site collection

*Deploy a custom master page

What I still need to do is (unless I am missing something):

*

*Deploy a solution

*Deploy visual web parts to the web part library

I can create an "Empty SharePoint 2013" project in Visual Studio, edit the appropriate files, and deploy it successfully through Visual Studio. When I go to the URL my solution should deploy to, everything works. But when I try to deploy through PowerShell, I get a different result. When I run the following PowerShell script:
# Deploy and Install Solution

# ---- CONFIGURATION BLOCK ----
$site = "http://sharepointpilot/"
# The file found at ($solutionPath + "\" + $solutionName) must be a WSP file
$solutionPath = "C:\SharePointPilot\dir\dir\bin\Debug"
$solutionName = "solution.wsp"

# ---- CODE ----
$web = Get-WebApplication -Site $site
Add-SPSolution -LiteralPath ($solutionPath + "\" + $solutionName)
Install-SPSolution -Identity $solutionName -GACDeployment

It installs, but does not deploy correctly.
When I run:
# Print XML Format of Solution Information
stsadm -o enumsolutions

I get the following:
<Solutions Count="1">
   <Solution Name="solution.wsp">
      <Id>1b9fc6b2-1fb0-43b7-982e-5e0643800694</Id>
      <File>solution.wsp</File>
      <Deployed>TRUE</Deployed>
      <WebApplicationSpecific>FALSE</WebApplicationSpecific>
      <ContainsGlobalAssembly>TRUE</ContainsGlobalAssembly>
      <ContainsFullTrustBinAssembly>FALSE</ContainsFullTrustBinAssembly>
      <ContainsCodeAccessSecurityPolicy>FALSE</ContainsCodeAccessSecurityPolicy>
      <LastOperationResult>DeploymentSucceeded</LastOperationResult>
      <LastOperationTime>9/29/2016 6:46 PM</LastOperationTime>
   </Solution>
</Solutions>

When I go to the URL my solution is supposed to be deployed, I get a 404 error.
I did notice when deploying in Visual Studio it says "enabling features" in the output. I tried to research that, but it ended up going nowhere.
If you can offer any help at all, it would be appreciated. Thanks for reading.

A: What I am seeing is the enabling feature part is missing. Solution deployment most 3 steps process

*

*Add solution, which u did

*Install solution, you already did

*Now missing part is enabling the feature on your site collection. Use following codeEnable-SPFeature -Url "[Site Collection URL]" -Identity "solution identity "
After enabling l, you will see it.


text:
Q: How can i get rid of this error: Msg 102, Level 15, State 1, Procedure assignhousekeeping, Line 13 [Batch Start Line 57] Incorrect syntax near ')' I am writing a trigger code to insert a data to cleaning table when a new data is inserted in condos table. this is the code that I have written:
create trigger assignhousekeeping
on condos
after insert
as
    insert into CLEANING(Condo#, DateCleaned, HKID)
        value(
            (select Condo# from inserted),
            getdate(),
            (select PID
             from PERSONNEL
             where FName = 'janice'
               and LName = 'avery'));

After running this I get these error messages:

Msg 102, Level 15, State 1, Procedure assignhousekeeping, > Line 6 [Batch Start Line 57]
Incorrect syntax near 'value'.
Msg 102, Level 15, State 1, Procedure assignhousekeeping, > Line 8 [Batch Start Line 57]
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Procedure assignhousekeeping, > Line 13 [Batch Start Line 57]
Incorrect syntax near ')'.

and the trigger did not go off as well. How can I fix this?

A: The correct insert syntax uses values not value.  However, that is only the beginning of your problems, because the trigger assumes that inserted has only one row.
I can speculate that you actually want:
insert into CLEANING (Condo#, DateCleaned, HKID)
    select Condo#, getdate(), p.pid
    from inserted i left join
         PERSONNEL p
         on p.FName = 'janice' and LName = 'avery';


text:
Q: How to download a file with Python using tqdm I want to make a .py file that downloads an image from a link with a progressbar included can I do it with tdqm?
This is what I have so far
from tqdm import tqdm
import requests

chunk_size = 1024

url = "example.com"

r = requests.get(url, stream = True)

total_size = int(r.headers['content-length'])
filename = url.split('/')[-1]

with open(filename, 'wb') as f:
    for data in tqdm(iterable = r.iter_content(chunk_size = chunk_size)):
        total = total_size/chunk_size, unit = 'KB')
        f.write(data)
print("Download complete!")

A: Found out how to do it
from tqdm import tqdm
import requests
import math
url = "http://ipv4.download.thinkbroadband.com/5MB"
r = requests.get(url, stream=True)

total_size = int(r.headers.get('content-length', 0))
block_size = 1024
wrote = 0
with open('output.bin', 'wb') as f:
    for data in tqdm(r.iter_content(block_size):
        total=math.ceil(total_size//block_size) , unit='KB', unit_scale=True)
        wrote = wrote  + len(data)
        f.write(data)
if total_size != 0 and wrote != total_size:
    print("ERROR, something went wrong")